Node.js:Passport,检查用户是否已登录

时间:2016-04-14 12:23:35

标签: javascript node.js express passport.js

对于使用令牌系统登录用户的用户,我有这个快速路由器:

var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/user');
var Verify = require('./verify');

router.post('/register', function(req, res) {
    User.register(new User({ username : req.body.username }),
      req.body.password, function(err, user) {
        if (err) {
            return res.status(500).json({err: err});
        }
        passport.authenticate('local')(req, res, function () {

            return res.status(200).json({status: 'Registration Successful!'});
        });
    });
});

router.post('/login', function(req, res, next) {

  passport.authenticate('local', function(err, user, info) {
    if (err) {
      return next(err);
    }
    if (!user) {
      return res.status(401).json({
        err: info
      });
    }
    req.logIn(user, function(err) {
      if (err) {
        return res.status(500).json({
          err: 'Could not log in user'
        });
      }

      var token = Verify.getToken(user);
        res.status(200).json({
        status: 'Login successful!',
        success: true,
        token: token
      });
    });
  })(req,res,next);

});

module.exports = router;

验证文件:

var User = require('../models/user');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('../config.js');

exports.getToken = function (user) {
    return jwt.sign(user, config.secretKey, {
        expiresIn: 3600
    });
};

exports.verifyOrdinaryUser = function (req, res, next) {
    // check header or url parameters or post parameters for token
    var token = req.body.token || req.query.token || req.headers['x-access-token'];

    // decode token
    if (token) {
        // verifies secret and checks exp
        jwt.verify(token, config.secretKey, function (err, decoded) {
            if (err) {
                var err = new Error('You are not authenticated!');
                err.status = 401;
                return next(err);
            } else {
                // if everything is good, save to request for use in other routes
                req.decoded = decoded;
                next();
            }
        });
    } else {
        // if there is no token
        // return an error
        var err = new Error('No token provided!');
        err.status = 403;
        return next(err);
    }
};

现在,我正在验证用户是否使用success属性登录。我希望我的路由检查用户是否已经登录登录路由,然后再通过护照身份验证。我如何实现这一目标?

2 个答案:

答案 0 :(得分:1)

你需要这样的东西:

proc datasets

答案 1 :(得分:0)

将其添加到您的路线中,例如:

app.route('/checkout', verifyOrdinaryUser, function(req, res) {
});

该函数将在使用请求和响应对象的回调之前运行,因此如果它未经过身份验证,它将执行您要求它执行的任何操作,如果它已经过身份验证,它将继续