如何使用passport-local.js存储其他表单字段

时间:2016-04-21 06:26:33

标签: node.js passport.js

我正在进行节点+ passport.js身份验证。我做了一个简单的登录/注册应用程序。它工作正常,但它只存储用户名和密码。

如何通过带有工作登录护照身份验证的signup.html页面将其他表单字段(如电话号码,电子邮件,爱好,性别)存储到数据库中?任何人都可以有解决方案,所以我可以存储数据库中的所有字段....

//my schema is :--
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = mongoose.Schema({
    local            : {
        username     : String,
        gender       : String,
        phone        : String,
        email        : String,
        password     : String
    }
 });
userSchema.methods.generateHash = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
userSchema.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.local.password);
};


var User = mongoose.model('user', userSchema);

module.exports = User;

在此代码中,我使用电子邮件,用户名,密码,性别电话的架构以及signup.html页面中的字段。但它只存储用户名和密码字段.........

4 个答案:

答案 0 :(得分:6)

打开passport.js文件(gernally在config文件夹中)

找到这行代码。

    passport.use('local-signup', new LocalStrategy({   // 'login-signup' is optional here   
    usernameField : 'email',
    passwordField : 'password',        
    passReqToCallback : true },function(req, email, password, done) {
   var gender = req.body.gender;
  var username = req.body.username;
  var phone = req.body.phone;
 // Now you can access gender username and phone

}));

答案 1 :(得分:0)

添加option passReqToCallback,您可以访问req.body中的所有请求正文数据:

passport.use(new LocalStrategy({ 
  passReqToCallback: true 
}, function (req, username, password, cb) {
  // Form fields are in req.body if using body-parser
  // ...
});

答案 2 :(得分:0)

我们也可以尝试这种方式。它的工作方式正确。在passport.js文件中,将以下代码编写为:

       module.exports = function(passport) {
              var criteria;
              passport.use(
               new LocalStrategy({ usernameField: 'username' }, (username, password, done) => {
               if(username.indexOf('@') > -1) { 
               criteria = {
                    email: username,
                };
               } else {
                criteria = {
                    mobile: username,
                };
              }

                // Match user
                User.findOne(criteria).then(user => {
                  if (!user) {
                      return done(null, false, {
                        success: null,
                        errors: "User is not registered",
                        result:null
                    });
                }

                // Match password
                bcrypt.compare(password, user.password, (err, isMatch) => {
                    if (err) throw err;
                    if (isMatch) {
                        return done(null, user);
                    } else {
                        return done(null, false, { 
                            success: null,
                            errors:'Password incorrect',
                            result: null
                         });
                    }
                });
            });
        })
    );
    enter code herepassport.serializeUser(function(user, done) {
        done(null, user.id);
    });

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

答案 3 :(得分:0)

这是将通行证模块与通行证本地化策略结合使用的简便方法,该策略使用通行证本地-mongoose插件通过用户名和密码之外的其他注册字段来注册和认证用户。

userModel.js定义用户架构

(无需添加用户名和密码字段,因为它们将由“ passport-local-mongoose”插件添加)
var mongoose = require('mongoose');  
var passportLocalMongoose = require('passport-local-mongoose');   
var Schema = mongoose.Schema;   

var User = new Schema(   
    {  
        firstname:  { type: String},  
        lastname:  {type: String},  
        email:  {type: String},  
        admin:   {type: Boolean, default: false}  
    }  
);  

User.plugin(passportLocalMongoose);  

module.exports = mongoose.model('User', User);  

userRouter.js-使用/ signup和/ login处理所有请求

var express = require('express');  
var bodyParser = require('body-parser');  
var mongoose = require('mongoose');
var session = require('express-session');
var FileStore = require('session-file-store')(session);
var passport = require('passport');  
var User = require('../models/userPassportModel');  
var LocalStrategy = require('passport-local').Strategy;  

var app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser('12345-67890-09876-54321'));

app.use(session({
    name: 'session-id',
    secret: '12345-67890-09876-54321',
   saveUninitialized: false,
   resave: false,
   store: new FileStore()
}));

passport.use(new LocalStrategy(User.authenticate()));  
passport.serializeUser(User.serializeUser());  
passport.deserializeUser(User.deserializeUser());  

var router = express.Router();  
router.use(bodyParser.json());  

// Handles Signup Request  
router.post('/signup', (req, res, next) => {  
        var usr =   new User({   
                        username: req.body.username,   
                        firstname:req.body.firstname,   
                        lastname:req.body.lastname,      
                        email:req.body.email  
                    });  
        var registerCallback =  (err, user) => {      
            if(err) {  
                res.statusCode = 500;  
                res.setHeader('Content-Type', 'application/json');  
                res.json({err: err});  
            }  
            else {  
                passport.authenticate('local')(req, res, () => {  
                    res.statusCode = 200;  
                    res.setHeader('Content-Type', 'application/json');  
                    var jsonResponse = {  
                        success: true,   
                        status: 'Registration Successful!',  
                        user:user  
                    };  
                    res.json(jsonResponse);  
                });  
            }  
        };  
        User.register(usr, req.body.password, registerCallback );  
});  

// Handles Login Request  
router.post('/login', passport.authenticate('local'), (req, res) => {  
        res.statusCode = 200;  
        res.setHeader('Content-Type', 'application/json');  
        res.json({success: true, status: 'You are successfully logged in!'});  
});  

您可以使用'/ signup'路由器来注册具有附加字段的用户,而'/ login'将负责对用户进行身份验证。

这是使用post方法发送的/ signup请求

{  
  "username":"harrhys",
  "password":"stackoverflow",
  "firstname":"Harrhy",
  "lastname":"Saladagu",
  "email":"harrhy.saladagu@gmail.com"
}

这是/ signup响应

{
    "success": true,
    "status": "Registration Successful!",
    "user": {
        "admin": false,
        "_id": "5f2ae017ae44c31b5049a477",
        "username": "harrhys",
        "firstname": "Harrhy",
        "lastname": "Saladagu",
        "email": "harrhy.saladagu@gmail.com",
        "salt":    
"6a6567e15575124e10f1046e55459ce0b8a3b496359b3a7b3201003a62471b06",
        "hash": 
"cae72972632b5f62be7a978d660e1c205a9b6633748ec17d9f907619fd3e043532c29418a3853765e92dd453db5084135b4432dde5584ebe4b7db8d4c5651c75c3d5d506982d9a4aa6c5b7d1c1aaa39ef49a203849279352d48b2ae4da4dedd005179ee393e29c7cf03f363edb60b70defbc761fc9a461541710e64ab719f3412766be1382b9392d590383e0b24a3a3df890ca67d810ce44eef7ca2191424701544d94b0723c2b9acafec1a76f65e936670f1ca04034cf2e6e1c1e386ff21b987cabbcd6f3f8cf962943b4f7c0eafc140e99f3dc80ae5902588a8324f2ef91fa3639429767bd807257751df7f5a16b86dc181d906568d0f134430b825fa891fc74e55318937a11549d6352d24d42b4f4ddd44ccac1afe694a061976ae0fcf5d038207b9129e4c3592ecbffab48925abd9514a58aff9fd012241f280d93159c4f1eecbb5f7b87d2d7c027ee5fd75ecb05afee991507524395d4df5a047144fcef1fe418cdee39b8ae2ad8ca856854856a47b1d115b39631ff6e121bc6ac54961520ba0af2a1a2a4c7cd980e05956eeb18965f4931b7cd54a6dadab9a087b8275ca88b5654bda81c402720c0ec5b622a860b0ea2fc9da87e50659a829d5b3a5bd62801f74ab27f7eff234ac422caf68421d30b3a3534165df2c72a425e3170a3033a04f2f19e37710cbfa07e337969d62b6adee18dbfc9b4085e3fa2a778c25d45",
        "createdAt": "2020-08-05T16:36:40.610Z",
        "updatedAt": "2020-08-05T16:36:40.610Z",
        "__v": 0
    }
}

这是使用post的/ login请求

{  
  "username":"harrhys"  
  "password":"stackoverflow"  
}  

/ login响应以及新的Cookie

{
    "success": true,
    "status": "You are successfully logged in!"
}