PassportJS本地策略中的这个选项对象参数是什么?

时间:2015-05-16 21:27:21

标签: mysql node.js passport.js

所以,我正在使用关系和passportJS在我的Node应用程序中验证用户。我无法找到护照本地策略中第一个参数的信息。此对象是否为用户提供了存储在MySQL中的模式,usernameFieldpasswordField来自何处?

    passport.use('local-signup', new localStrategy({
        //provide a schema?
        usernameField: 'username',
        passwordField: 'password',
        //pass back the entire request to the callback
        passReqToCallback: true
    },
    //passport.authenticate() passes in the parsed out password and username
    function (req, username, password, done) {
    //....
    }

1 个答案:

答案 0 :(得分:0)

server/auth/index.js中,您将找到要使用的不同策略的不同映射。

然后,您将能够检查策略:

var express = require('express');
var passport = require('passport');
var config = require('../config/environment');
var User = require('../api/user/user.model');

// Passport Configuration
require('./login/passport').setup(User, config);

var router = express.Router();
router.use('/local', require('./local/index'));

然后,在./local/index.js

var passport = require('passport');
var auth = require('../auth.service.js');

var router = express.Router();

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

  console.log.req;

  passport.authenticate('local', function (err, user, info) {
    var error = err || info;
    if (error) return res.json(401, "THAT´S BAD");
    if (!user) return res.json(404, {message: 'Something went wrong, please try again.'});
    var token = auth.signToken(user._id, user.role);
    res.json({token: token, user:user});
  })(req, res, next)
});

module.exports = router;

然后,在./local/passport.js

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

exports.setup = function (User, config) {
  passport.use("local", new Local({
      usernameField: 'apikey',
      passwordField: 'apisecret'
    },

    function(apikey, apisecret, done) {
//THIS FUNCTION IS THE ONE YOU HAVE TO CHANGE TO YOUR MYSQL CODE TO CHECK WHETHER THE USER IS REGISTERED
      User.findOne({
        apikey: apikey,
        apisecret: apisecret
      }, function(err, user) {
        if (!user) {
          return done("YOUR API KEY HAS NOT AUTHORIZATION", false, { message: 'This email is not registered.' });
        }
        return done(null, user);
      });
    }
  ));

  passport.serializeUser(function(user, done) {
    done("USER", user);
  });

  passport.deserializeUser(function(user, done) {
    done(null, user);
  });


};

编辑如您所见,我使用快递,我需要用户模型。这是一个使用mongodb和mongoose运行的平均fullstack应用程序。无论如何,我认为你可以使用mysql(我强烈建议你阅读那些fullstack生成器)https://github.com/DaftMonk/generator-angular-fullstack 如果您正在启动应用程序,请考虑将mysql更改为mongodb - expressjs-angularjs-nodejs

希望它有所帮助!!