V
V
Valery Orlov2018-08-22 23:13:58
Node.js
Valery Orlov, 2018-08-22 23:13:58

NodeJS How to generate password in Passport?

The Passport registration code looks like this:

const LocalStrategy   = require('passport-local').Strategy;
const User       		= require('../app/models/user');
const randomPass = require('randomstring');

module.exports = function(passport) {
    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({
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true 
    },
    function(req, email, password, done) {
          User.findOne({ 'local.email' :  email.toLowerCase() }, function(err, user) {
            if (err)
                return done(err);

            if (user) {
                return done(null, false, req.flash('signupMessage', 'Адрес электронной почты уже занят'));
            } else {
                var newUser            = new User();
                newUser.local.email    = email.toLowerCase();
                newUser.local.password = newUser.generateHash(password);

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

Here, Passport accepts an email and password field and is already doing the registration. But I need to generate a password randomly, via randomPass.generate(7). How can I fix the code so that Passport only receives the email field, and the password is already generated randomly?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Abcdefgk, 2018-08-23
@lungdesire29

var newUser            = new User();
newUser.local.email    = email.toLowerCase();
password = randomPass.generate(7);
newUser.local.password = newUser.generateHash(password);

S
SagePtr, 2018-08-23
@SagePtr

It’s easier to write your own route, which will take the login field from req.body, check if there is such a user in the database, and if not, add it to the database and call the req.login method from the passport to log in a freshly registered user.
'local-signup' bundled with the passport is flawed if you need something different from the default login-password pair.

S
Sardort2001, 2022-02-17
@Sardort2001

const { Router } = require('express')
const router = Router()
const Users = require('../models/Users')
const bcrypt = require('bcryptjs')
const fileUpload = require('../middleware/fileUpload.js')

router.get('/signin', (req, res, next) => {
    res.render('user/signin', {
        title: 'User sign in'
    })
})

router.get('/signout', (req, res) => {
    req.session.destroy(() => {
        res.redirect('/user/signin')
    })
})

router.post('/signin', async (req, res) => {
    try {
        const { nickname, password } = req.body


        const candidateUser = await Users.findOne({ nickname })
        if (candidateUser) {
            const areSame = await bcrypt.compare(password, candidateUser.password) //true || false
            if (areSame) {
                req.session.userAuth = true
                req.session.users = candidateUser
                res.redirect('/users')
            } else {
                res.redirect('/user/signin')
            }
        } else {
            res.redirect('/user/signin')
        }
    } catch (error) {
        console.log(error);
    }
});

router.get('/signup', (req, res) => {
    res.render('user/signup', {
        title: 'User sign up'
    })
})

router.post('/signup', async (req, res) => {
    const { nickname, name, password } = req.body
    const userHasPassword = await bcrypt.hash(password, 10)

    const users = new Users({
        nickname,
        name,
        password: userHasPassword,
    })

    await users.save()
    res.redirect('/user/signin')
})


module.exports = router

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question