Passport-local-mongoose : Authenticate user right after registration

12,434

According to the API documentation of passport-local-mongoose at https://github.com/saintedlama/passport-local-mongoose you register a user by calling register(user, password, cb)

So your register.js should look something like this

 ...

 if (errors) {
     res.render("register" , { errors : errors } );
 }
 else {
     var newUser = new User({
         username : username,
         email : email,
         tel : tel,
         country : country
     });

     User.register(newUser, password, function(err, user) {
        if (errors) {
            // handle the error
        }
        passport.authenticate("local")(req, res, function() {
            // redirect user or do whatever you want
        });
     });
 }

and don't forget to require passport in register.js

Share:
12,434
TasDePixels
Author by

TasDePixels

Updated on June 04, 2022

Comments

  • TasDePixels
    TasDePixels almost 2 years

    I am trying to use passport-local-mongoose to authenticate a user after submitting a POST on the /register form. I can't figure out why i always get "unauthorized" & oddly no data is submitted on the database (it works if i remove "passport.authenticate('local') from app.post("/register") )

    any ideas ?


    app.js :

        // ====== Dependencies
    var express = require('express');
        bodyParser = require('body-parser');
        validator = require('express-validator');
        cookieParser = require('cookie-parser');
        expressSession = require('express-session');
        passport = require('passport');
        LocalStrategy = require('passport-local').Strategy;
        auth = require('./controllers/auth');
        registration = require('./controllers/register');
        User = require('./models/user');
    // ====== Options
    var app = express()
    .use(bodyParser.urlencoded({ extended: false }))
    .use(bodyParser.json())
    .use(validator())
    .set('view engine','ejs')
    .use(express.static("views"))
    .use(cookieParser())
    .use(expressSession({
        secret : 'soooosecret',
        resave : true,
        saveUninitialized : false
    }))
    .use(passport.initialize())
    .use(passport.session());
    passport.use(new LocalStrategy(User.authenticate()));
    passport.serializeUser(User.serializeUser());
    passport.deserializeUser(User.deserializeUser());
    
        app.post('/register', passport.authenticate('local'), registration.reg );
    
    app.listen(8080);
    console.log('Server running at 8080');
    

    register.js :

    var User = require('../models/user');
    
    var reg = function (req, res) {
    
        /* some form validation... */
        var errors = req.validationErrors();
    
         if (errors) {
             res.render("register" , { errors : errors } );
         }
         else {
             var newUser = new User({
                 username : username,
                 password : password,
                 email : email,
                 tel : tel,
                 country : country
             });
    
             User.createUser(newUser);
         }
    
    }
    module.exports = { reg : reg }
    

    user.js :

    var mongoose = require('mongoose');
        mongoose.connect('mongodb://localhost/mvpem');
    
    var passportLocalMongoose = require('passport-local-mongoose');
    
     var db = mongoose.connection;
    
    var Schema = mongoose.Schema;
    
    var UserSchema = new Schema({
        username    : String,
        password     : String,
        email      : String,
        tel      : Number,
        country : String
    });
    
    UserSchema.plugin(passportLocalMongoose);
    
    module.exports = mongoose.model('User', UserSchema);
    
    module.exports.createUser = function(newUser) {
        newUser.save(); 
    }
    
  • N1mr0d
    N1mr0d about 8 years
    with passport-local-mongoose, you actually set up the strategy just like the OP has it. mherman.org/blog/2013/11/11/…
  • Kannan T
    Kannan T over 6 years
    Hi i want to store mailid,address and few other details of the user so can i use your method which you have mentioned in else part having that in an object and using it in User.register will it work? And is there any other way rather than creating new User
  • G. Thabit
    G. Thabit over 6 years
    @kannan I'm not sure I understand your question. In the code snippet above 4 pieces of data stored: username, email, tel, and country. You can store whatever data you want, you need to define it in user model which is imported by the line var User = require('../models/user'); in register.js and then you can store it when creating the user just like the previous 4 pieces of data. I hope this helped.
  • Dmytro Medvid
    Dmytro Medvid over 6 years
    I am currently doing the same and my code is pretty similar to your example. But after successful registration there is only username and hash saved into user record in MongoDB. How I actually can save this additional data from user model into DB and how I can then access this data?