成功login后,将用户数据从Nodejs服务器推送到Angular
我尝试通过使用PassportJS通过Facebooklogin我的用户,并将用户数据传递给Angular。 在服务器端,用户控制器中的Facebookcallback代码如下:
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());
快递和护照configuration包括:
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; } ]);
不幸的是,用户数据在window.user中不可用。 任何想法我在这里做错了吗?
正如Girish所说,护照会话对象在客户端不可用。 正如你似乎使用express
,一个简单的方法来做到这一点是使用快递公开 。
如果您希望用户数据在用户通过身份validation时在所有页面上可用,则可以在路由声明之前添加这样的内容
app.use(function (req, res, next) { if (req.isAuthenticated()) res.expose(req.user, 'user'); next (); });
用户数据将作为window.user
可用的客户端。
护照会话对象将不会在窗口对象上可用,而是需要使用某个服务或redirecturl从服务器获取。
authentication成功后,主路由function将被调用,在这种情况下,将把用户redirect到主页面。
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 }); });
或者您可以创build一个路线来获取login的用户数据
app.get('/account', function(req, res){ if (req.isAuthenticated()) { res.send({user : req.user}); }else{ res.redirect('/login'); } });
在Angular方面,您可以将$ http响应中的用户数据设置为rootcope,
$rootScope.session = {} $rootScope.session.user = res.user;