通过Passport Js注册用户

时间:2017-11-23 13:44:45

标签: javascript node.js express authentication passport.js

我想通过passport.js的帮助从注册页面添加新用户 注册表格如下

<form id="Signup-form" name="SignupForm" action="/signup" method="post"/>
<input type="text" id="firstname" name="Firstname" >
<input type="text" id="lastname" name="Lastname"/>
<input type="email" name="email" />
<input type="text" id="rollno" name="rollno"/>
<input type="password" name="password" id="password"/>
<input type="password" name="confirm" id="confirm-password"/>
<input type="radio" name='Gender' value="Male" />
<input type="radio" name='Gender' value="FeMale" />
</form>

我的护照在app.js中初始化为

必需

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
db设置后

require('./config/passport');

初始化为

app.use(passport.initialize());
app.use(passport.session());

发布注册路线

router.post('/signup', passport.authenticate('local.signup' , {
successRedirect : '/home',
failuerRedirect : '/signup',
failuerFlash: true
}));

我的用户模型

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs')

const UserSchema = new Schema({
First_Name : String,
Last_Name : String,
email : String,
Roll_No : String,
Gender : String,
password : String
},{collection : 'Users'});

UserSchema.methods.encryptPassword = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(5), null);
};

UserSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.password);
}
var User = mongoose.model('User' , UserSchema); 
module.exports = User;

现在我的配置目录中的passport.js文件是

var passport = require('passport');
var User = require('../models/user');
var LocalStrategy = require('passport-local').Strategy;
passport.serializeUser(function (user, done) {
done(null, user.id);
});

passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
 });
});

我的主要问题是如何为所有领域的这条路线编写策略

passport.use('local.signup', new LocalStrategy({
//strategy code here
}));

4 个答案:

答案 0 :(得分:3)

这是一个很好的例子Easy Node Authentication: Setup and Local

passport.use('local-signup', new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
    function(req, email, password, done) {

        // find a user whose email is the same as the forms email
        // we are checking to see if the user trying to login already exists
        User.findOne({ 'local.email' :  email }, function(err, user) {
            // if there are any errors, return the error
            if (err)
                return done(err);

            // check to see if theres already a user with that email
            if (user) {
                return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
            } else {

                // if there is no user with that email
                // create the user
                var newUser            = new User();

                // set the user's local credentials
                newUser.local.email    = email;
                newUser.local.password = newUser.generateHash(password);

                // save the user
                newUser.save(function(err) {
                    if (err)
                        throw err;
                    return done(null, newUser);
                });
            }

    }));

答案 1 :(得分:1)

使用以下链接进行使用护照的登录注册 https://github.com/sourabhkum/expressapp

答案 2 :(得分:0)

对于试图弄清楚如何在用户名(可以是电子邮件)和密码旁边的本地护照中添加其他字段的人,可接受的答案仅暗示如何进行。假设您要为用户模型使用名称,电子邮件和密码。您可以使用Passport-local这样操作:

const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
const User = require('./model/user');

passport.use('signup', new localStrategy({
  usernameField : 'email',
  passwordField : 'password',
  passReqToCallback: true
}, async (req, email, password, done) => {
  try {
    const name = req.body.name;
    const user = await User.create({ name, email, password });
    return done(null, user);
  } catch (error) {
    done(error);
  }
}));

要注意的事情是:护照localStrategy对象不接受username字段和passwordField之外的其他字段。但是您可以将请求对象传递给回调。然后,在将用户保存到数据库之前,将字段从req.body对象中拉出并将它们放入create方法中(如果使用的是Mongoose.js)。

答案 3 :(得分:0)

Passportjs也具有实用程序功能。如果您不想使用中间件来注册用户,则可以使用常规的帖子请求来创建用户,然后使用password js中的登录功能对其进行身份验证(将新创建的用户对象添加到当前会话中)

router.post('/auth/signup',(req,res,next) => {
  const user = new User();
  
  req.login(user,(err) => {
    console.log("success");
  }
})

有关更多详细信息,请参见此链接http://www.passportjs.org/docs/login