如何使用Passport.js和Node for Single Page App

时间:2014-07-09 21:42:53

标签: node.js express passport.js

我不认为这样的问题一直困扰着我。似乎有0个地方可以查看或回答这个问题。我想做的就是拿到护照来拦截打电话给' / login'和' / getloginStatus'。

登录时我只想使用Json对象作为{username / password}的参数。当我登录时,如果用户在浏览器中有auth票证,我只想返回true / false。

这就是我所拥有的,但它没有丝毫工作,一半的问题似乎是我的本地策略实施从未被调用....

var passport = require('passport')
    , LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
    function(username, password, done) {

        console.log('this NEVER gets called');

    }
));

app.post('/api/authentication/login', function(req, res, next) {
            passport.authenticate('local', function(err, user, info) {

            console.log('this does get called but so what?');

            if (err) { return next(err); }

            if (!user) { return res.redirect('/login'); }
            req.logIn(user, function(err) {

                console.log('this does get called but so what am I logged in?');

                next();

            });
        })(req, res, next);
});

app.get('/api/authentication/getloginStatus', function(req, res, next) {
            passport.authenticate('local', function(err, user, info) {

             //what do I return here? !!!?

        })(req, res, next);
});

任何帮助都非常感谢!

1 个答案:

答案 0 :(得分:0)

Passport.js使用当前经过身份验证的用户填充request.user。因此,要获取有关当前用户的信息,您可以执行此操作

app.get('/api/authentication/getloginStatus', function(request, response) {
  if(request.user) {
    response.json(request.user);
  } else {
    response.status(401); //Authorization required
    response.json({"error":"Authorization required!", "code":401"})'
  }
});