正确设置Passport Local

时间:2015-12-06 19:22:23

标签: node.js express passport.js

我很难绕过Passportjs文档并了解应该用于创建用户的内容与用于通过登录对用户进行身份验证的内容。我的登录post方法实际上是创建新用户,但没有电子邮件。我应该使用LocalStrategy方法代替我的/sign-up post方法来创建用户吗?

当前路由:

   var express = require('express');
    var siteRoutes  = express.Router();
    var passport = require('passport');
    var LocalStrategy = require('passport-local').Strategy;
    var models = require('../models/db-index');

    /*====  Passport Configuration  ====*/


    passport.use(new LocalStrategy({
        usernameField: 'email',
        passwordField : 'password'
        },

        function(username, password, done) {
            User.findOne({ username: username }, function(err, user) {
          if (err) { return done(err); }
          if (!user) {
            return done(null, false, { message: 'Incorrect username.' });
          }
          if (!user.validPassword(password)) {
            return done(null, false, { message: 'Incorrect password.' });
          }
          return done(null, user);
        });
      }
    ));


    /*====  Index   ====*/

    siteRoutes.get('/', function(req, res){
        res.render('pages/index.hbs');
    });

    /*====  Login   ====*/


    siteRoutes.route('/login')

        .get(function(req, res){
            res.render('pages/login.hbs');
        })

        .post(passport.authenticate('local', {
            successRedirect: '/app',
            failureRedirect: '/login'
        }));



    siteRoutes.route('/sign-up')

        .get(function(req, res){
            res.render('pages/sign-up.hbs');
        })

        .post(function(req, res){

            models.User.create({
                firstName: req.body.firstName,
                lastName: req.body.lastName,
                email: req.body.email,
                password: req.body.password
            }).then(function() { 
            res.redirect('/');
        }).catch(function(error){
            res.send(error);
        })

    });








    module.exports = siteRoutes;

0 个答案:

没有答案