6

I am working on a node+passport.js authentication. I make a simple login/signup app. It's working fine but, it stores only username and password.

How can I store the other Form Fields like Phone number, email, hobbies, gender into database through a signup.html page with working login passport authentication? Can anybody have solution for that so I can store all the fields in the database....

//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;

In this code I use schema of email, username, password, gender phone and also given fields in signup.html page. but it stores only username and password fields only.........

beane
  • 158
  • 1
  • 12
RohanArihant
  • 2,560
  • 4
  • 19
  • 29

4 Answers4

8

Open passport.js file ( gernally inside config folder)

find this line of code.

    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

}));
Shubham Batra
  • 2,357
  • 5
  • 29
  • 48
0

Add option passReqToCallback and you can access all request body data from req.body:

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

We can also try in this way.Its working in right way.In passport.js file write below code :

       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);
        });
    });
};
Swati
  • 28,069
  • 4
  • 21
  • 41
0

Here is the simple to way to use passport module with passport-local strategy using passport-local-mongoose plugin to register and authenticate user with additional signup fields apart from username and password.

userModel.js Defines the User Schema

(No need to add username, password fields as they will be added by 'passport-local-mongoose' plugin )
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 - handles all the requests with /signup and /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!'});  
});  

There you go, '/signup' router will take are of registering user with addition fields and '/login' will take care of authenticating the user.

Here are is the /signup request sent using post method

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

Here is /signup the response

{
    "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
    }
}

Here is the /login request using post

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

And the /login response along with the new cookie

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