passport.js - How do I allow email as an alternative to username while authenticating with PassportJS? -
how allow uses log in using username or email? authenticating using passport local strategy
connected mongoose
schema. currently, i'm able authenticate username (and password, of course). /login
route looks this:
// lib/authenticate.js router.post('/login', (req, res) => { passport.authenticate('local')(req, res, () => { // logged in, return user info token if (req.user) { const userdata = json.stringify(req.user); let token = jwt.sign({ username: req.user.username, firstname: req.user.firstname, lastname: req.user.lastname, email: req.user.email, img: req.user.img, }, process.env.jwt_secret); res.cookie('token', token); return res.send(userdata); } // otherwise return error return res.send(json.stringify({ error: 'there error logging in' })); }); });
the mongoose model passport hooked is:
// /models/user.js const { mongoose } = require('../config/dbconfig'); const schema = mongoose.schema; const passportlocalmongoose = require('passport-local-mongoose'); const user = new schema({ username: { type: string, lowercase: true, required: true, }, password: { type: string, select: false, required: true, }, firstname: { type: string, required: true, }, lastname: { type: string, required: true, }, email: { type: string, lowercase: true, required: true, }, img: { type: string, }, }, { timestamps: true }); user.plugin(passportlocalmongoose); module.exports = mongoose.model('user', user);
the auth script above improvisation on 1 got off passportjs tutorial , works fine still struggling see it's doing authentication. mean how know match payload against right fields (in case, username
, password
)? don't see explicit field mapping anywhere in script. automagic going on here?
wiki
Comments
Post a Comment