网站搜索

javascript - 在用户成功登录后,将用户数据从 Nodejs 服务器推送到 Angular


我尝试通过 Facebook 使用 PassportJS 登录我的用户,并将用户数据传递给 Angular。在服务器端,Facebook 回调的用户控制器代码如下,一切看起来正常:

exports.facebookCallback = function() {
return function(req, res, next) {
    passport.authenticate('facebook', function(err, user, email) {
        if (err || !user) {
            return res.redirect('/auth');
        }
        req.login(user, function(err) {
            if (err) {
                return res.redirect('/auth');
            }
            return res.redirect('/');
        });
    })(req, res, next);
 };
};

根据我对 PassportJS 文档的理解,调用 req.login 应该会将用户数据放入会话中。

我在服务器端的路由如下所示:

app.get('/auth', usersCtrl.auth);
app.get('/auth/signout', usersCtrl.logout);
app.get('/auth/facebook', passport.authenticate('facebook', {
    scope: ['email', 'user_hometown']
}));
app.get('/auth/facebook/callback', usersCtrl.facebookCallback());

Express 和护照配置包括:

app.use(express.cookieParser());
app.use(express.session({secret: '1234567890QWERTY'}));
app.use(express.bodyParser());
app.use(passport.initialize());
app.use(passport.session());

现在在 Angular 端,我尝试从会话中获取用户数据,在一个像这样的服务中定义:

module.exports = require('angular')
.module('HomeModule', [])
.controller('HomeCtrl', function ($scope) {
       //home controller code ors here
}).controller('NavbarCtrl', ['$scope', 'Authentication', function ($scope, Authentication) {
    $scope.authentication = Authentication;
    //rest of the navbar controller goes here
}]).factory('Authentication', [
    function() {
        var _this = this;

        _this._data = {
            user: window.user
        };

        return _this._data;

    }
]);

不幸的是,在 Angular 端 window.user 中无法获取用户数据。有人知道我哪里做错了吗?

答案#1

正如Girish所说,passport会话对象在客户端是不可用的。由于你似乎在使用express,一种简单的方法是使用express-expose。

如果你希望在用户通过身份验证后,用户数据在所有页面上都可用,你可以在路由声明之前添加类似这样的内容

app.use(function (req, res, next) {
    if (req.isAuthenticated()) res.expose(req.user, 'user');
    next ();
});

用户数据将在客户端作为 window.user 可用。

答案#2

Passport 会话对象不会在 window 对象上可用,相反,你需要通过某个服务或重定向 URL 从服务器获取它。

成功认证后,将调用主路由函数,在本例中,该函数会将用户重定向到主页。

   app.get('/auth/facebook/callback', 
     passport.authenticate('facebook', { failureRedirect: '/login' }),
     function(req, res) {
     res.redirect('/');
   });


   app.get('/', function(req, res){
    res.render('index', { user: req.user });
   });

或者你可以创建一个路由来获取已登录用户的数据

   app.get('/account', function(req, res){
     if (req.isAuthenticated()) { 
       res.send({user : req.user}); 
     }else{
       res.redirect('/login');
     }
   });

在 Angular 端,你可以从 $http 响应中将用户数据设置到 rootscope。

$rootScope.session = {}
$rootScope.session.user = res.user;