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

Jak*_*kub 6 javascript node.js express angularjs passport.js

我尝试使用PassportJS通过Facebook登录我的用户并将用户数据传递给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);
 };
};
Run Code Online (Sandbox Code Playgroud)

根据我对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());
Run Code Online (Sandbox Code Playgroud)

快递和护照配置包括:

app.use(express.cookieParser());
app.use(express.session({secret: '1234567890QWERTY'}));
app.use(express.bodyParser());
app.use(passport.initialize());
app.use(passport.session());
Run Code Online (Sandbox Code Playgroud)

现在在角度方面,我尝试从如下定义的服务中获取会话中的用户数据:

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;

    }
]);
Run Code Online (Sandbox Code Playgroud)

不幸的是,用户数据在角度侧的window.user中不可用.我在这里做错了什么想法?

小智 3

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 });
   });
Run Code Online (Sandbox Code Playgroud)

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

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

在 Angular 方面,您可以从 $http 响应将用户数据设置为 rootscope,

$rootScope.session = {}
$rootScope.session.user = res.user;
Run Code Online (Sandbox Code Playgroud)