0

我正在尝试使用everyauth 示例登录facebook。我打印了显示身份验证已成功执行的everyauth 调试消息。但是,everyauth.loggedIn 变量未设置。我不确定为什么。我实际上有这样的代码

我有一个页面,其中有 auth/facebook 的链接。当用户单击该链接时,将发送用户进行 facebook 身份验证,一切都完成了。但是,当我检查everyauth.loggedIn 它总是未定义

if(everyauth.loggedIn) {
   console.log('The user has logged in');
}

以上是我在'/' url 有请求时尝试检查的内容。这是在执行 facebook 身份验证之后。但是,它总是未定义。可能是因为局部,全局变量问题。我将everyauth 变量传递给几个模块。任何建议将不胜感激

app.js(设置快速应用程序)

var exp = require('express');
var app = exp.createServer();

var conf = require('/path/example/conf')
var everyauth = require('everyauth');

everyauth.debug = true;

var usersById = {};
var nextUserId = 0;

function addUser (source, sourceUser) {
  var user;
  user = usersById[++nextUserId] = {id: nextUserId};
  user[source] = sourceUser;
  return user;
}

var usersByFbId = {};
var usersByTwitId = {};

everyauth.everymodule
  .findUserById( function (id, callback) {
    callback(null, usersById[id]);
  });

everyauth
  .facebook
    .appId(conf.fb.appId)
    .appSecret(conf.fb.appSecret)
    .findOrCreateUser( function (session, accessToken, accessTokenExtra, fbUserMetadata) {
      return usersByFbId[fbUserMetadata.id] || (usersByFbId[fbUserMetadata.id] = addUser('facebook', fbUserMetadata));;
    })
    .redirectPath('/');

everyauth
  .twitter
    .consumerKey(conf.twit.consumerKey)
    .consumerSecret(conf.twit.consumerSecret)
    .findOrCreateUser( function (sess, accessToken, accessSecret, twitUser) {
      return usersByTwitId[twitUser.id] || (usersByTwitId[twitUser.id] = addUser('twitter', twitUser));;
    })
    .redirectPath('/');


app.root = __dirname;
global.host = 'local.host';

require('./app/config')(app, exp, everyauth);
require('./app/server/router')(app,everyauth);

app.listen(3000, function(){
    console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});

配置.js

module.exports = function(app, exp, everyauth) {

    app.configure(function(){
        app.set('views', app.root + '/app/server/views');
        app.set('view engine', 'jade');
        app.set('view options', { doctype : 'html', pretty : true });
        app.use(exp.bodyParser());
        app.use(exp.cookieParser());
        app.use(exp.session({ secret: 'super-duper-secret-secret' }));
        app.use(everyauth.middleware(app));
        app.use(exp.methodOverride());
        app.use(require('stylus').middleware({ src: app.root + '/app/public' }));
        app.use(exp.static(app.root + '/app/server'));
        app.use(exp.static(app.root + '/app/public'));
    });

路由器.js

var CT = require('./modules/country-list');
var AM = require('./modules/account-manager');
var EM = require('./modules/email-dispatcher');


var mongodb = require('mongodb');
module.exports = function(app, everyauth) {

    // main login page //

    app.get('/', function(req, res){
      console.log('Root page called');
      // This is the problem area. everyauth.loggedIn always comes out undefined
      if(everyauth.loggedIn) {
         console.log('The user has logged in');
      } 

    // check if the user's credentials are saved in a cookie //
        if (req.cookies.user == undefined || req.cookies.pass == undefined){
            res.render('login', { locals: { title: 'Hello - Please Login To Your Account'}});
        }   else{
    // attempt automatic login //
            AM.autoLogin(req.cookies.user, req.cookies.pass, function(o){
                if (o != null){
                    req.session.user = o;
                    res.redirect('/dashboard');
                }   else{
                    res.render('login', { locals: { title: 'Hello - Please Login To Your Account' }});
                }
            });
        }
    });


    app.post('/', function(req, res){
      console.log('app called');
        AM.manualLogin(req.param('user'), req.param('pass'), function(e, o){
            if (!o){
                res.send(e, 400);
            }   else{
                req.session.user = o;
                if (req.param('remember-me') == 'true'){
                    res.cookie('user', o.user, { maxAge: 900000 });
                    res.cookie('pass', o.pass, { maxAge: 900000 });
                }
                res.send(o, 200);
            }
        });
    });

    app.post('/feedback', function(req,res) {
    var server = new mongodb.Server('localhost',27017, {auto_reconnect: true}, {safe:true});
        var db = new mongodb.Db('clicker', server);

    db.open(function(err, db) {
            if(!err) {
                db.collection('feedback', function(err, collection) {
                    var currentTime = new Date().getTime();
                    var feedback = {value:req.param('feedback'), datetime:currentTime}; 
                    collection.insert(feedback);
                    db.close();
                });
            }      
        });
        res.send('ok', 200);

    });

// logged-in user homepage //

    app.get('/home', function(req, res) {
        if (req.session.user == null){
    // if user is not logged-in redirect back to login page //
            res.redirect('/');
        }   else{
            res.render('home', {
                locals: {
                    title : 'Control Panel',
                    countries : CT,
                    udata : req.session.user
                }
            });
        }
    });

    app.get('/dashboard', function(req, res) {
        if (req.session.user == null){
    // if user is not logged-in redirect back to login page //
            res.redirect('/');
        }   else{
            res.render('dashboard', {
                locals: {
                    title : 'Dashboard',
                    countries : CT,
                    udata : req.session.user
                }
            });
        }
    });

    app.post('/home', function(req, res){
        if (req.param('user') != undefined) {
            AM.update({
                user        : req.param('user'),
                name        : req.param('name'),
                email       : req.param('email'),
                country     : req.param('country'),
                pass        : req.param('pass')
            }, function(o){
                if (o){
                    req.session.user = o;
            // udpate the user's login cookies if they exists //
                    if (req.cookies.user != undefined && req.cookies.pass != undefined){
                        res.cookie('user', o.user, { maxAge: 900000 });
                        res.cookie('pass', o.pass, { maxAge: 900000 }); 
                    }
                    res.send('ok', 200);
                }   else{
                    res.send('error-updating-account', 400);
                }
            });
        }   else if (req.param('logout') == 'true'){
            res.clearCookie('user');
            res.clearCookie('pass');
            req.session.destroy(function(e){ res.send('ok', 200); });
        }
    });

// creating new accounts //

    app.get('/signup', function(req, res) {
        res.render('signup', {  locals: { title: 'Signup', countries : CT } });
    });

    app.post('/signup', function(req, res){
        AM.signup({
            name    : req.param('name'),
            email   : req.param('email'),
            user    : req.param('user'),
            pass    : req.param('pass'),
            country : req.param('country')
        }, function(e, o){
            if (e){
                res.send(e, 400);
            }   else{
                res.send('ok', 200);
            }
        });
    });

// password reset //

    app.post('/lost-password', function(req, res){
    // look up the user's account via their email //
        AM.getEmail(req.param('email'), function(o){
            if (o){
                res.send('ok', 200);
                EM.dispatchResetPasswordLink(o, function(e, m){
                // this callback takes a moment to return //
                // should add an ajax loader to give user feedback //
                    if (!e) {
                    //  res.send('ok', 200);
                    }   else{
                        res.send('email-server-error', 400);
                        for (k in e) console.log('error : ', k, e[k]);
                    }
                });
            }   else{
                res.send('email-not-found', 400);
            }
        });
    });

    app.get('/reset-password', function(req, res) {
        var email = req.query["e"];
        var passH = req.query["p"];
        AM.validateLink(email, passH, function(e){
            if (e != 'ok'){
                res.redirect('/');
            } else{
    // save the user's email in a session instead of sending to the client //
                req.session.reset = { email:email, passHash:passH };
                res.render('reset', { title : 'Reset Password' });
            }
        })
    });

    app.post('/reset-password', function(req, res) {
        var nPass = req.param('pass');
    // retrieve the user's email from the session to lookup their account and reset password //
        var email = req.session.reset.email;
    // destory the session immediately after retrieving the stored email //
        req.session.destroy();
        AM.setPassword(email, nPass, function(o){
            if (o){
                res.send('ok', 200);
            }   else{
                res.send('unable to update password', 400);
            }
        })
    });

// view & delete accounts //

    app.get('/print', function(req, res) {
        AM.getAllRecords( function(e, accounts){
            res.render('print', { locals: { title : 'Account List', accts : accounts } });
        })
    });

    app.post('/delete', function(req, res){
        AM.delete(req.body.id, function(e, obj){
            if (!e){
                res.clearCookie('user');
                res.clearCookie('pass');
                req.session.destroy(function(e){ res.send('ok', 200); });
            }   else{
                res.send('record not found', 400);
            }
        });
    });

    app.get('/reset', function(req, res) {
        AM.delAllRecords( );
        res.redirect('/print');
    });

    app.get('*', function(req, res) { res.render('404', { title: 'Page Not Found'}); });

};

    }
4

2 回答 2

0

要启用像您这样的快速助手everyauth.loggedIn,您必须调用:

everyauth.helpExpress(app);
于 2012-12-28T22:13:33.280 回答
-1

我不确定为什么您的代码不起作用。我有一个可以正常工作的示例,但它需要 mongodb。如果您想尝试,只需推送到 github。 链接到 github

于 2013-07-12T02:24:43.750 回答