i want to know to handle user firstname and lastname in passportjs knowing i tried the folowing code:
passport.use('local-register', new passportLocal (strategyOption, function (email, password, firstname, lastname, callback) {
console.log(' ------- pass :' + password);
console.log(' ------- email :' + email);
console.log(' ------- fname :' + firstname);
console.log(' ------- lname :' + lastname);
var searchedUser = {
email: email
};
User.findOne(searchedUser, function (err, user) {
if (err) return callback (err);
//console.log(user);
if (user) return callback (null, false, {
message: 'User do exist!'
});
var newUser = new User({
firstname: firstname,
lastname: lastname,
email: email,
password: password
});
newUser.save(function (err) {
if(err) console.log('hi');
callback (null, newUser);
});
});
}));
but in the console i got the following stuff:
---- p: pass(the password giving) ---- email: the email... ---- fname: - here i got a wierd thing -
------- fname :function verified(err, user, info) {
if (err) { return self.error(err); }
if (!user) { return self.fail(info); }
self.success(user, info);
} ------- lname:undefined
and the worst: unknown callback... so node can't handle the callback and when i delete the fname and the lname parameter.. everything works like a charm so does anyone know how to handle the fname and lname in passport?
Thankx,
The following code worked for me:
Passport config:
passport.use('local-signup', new localStrategy({
usernameField: 'email',
passwordField: 'password'
},
async (email, password, done) => {
try {const user = await UserModel.create({
email, password
})
console.log(`Welcome!`)
return done(null, user);
}
catch (error) {
console.log(`Signup error: ${error}`)
done(error)
}
}));
Node js route:
router.post(
'/signup',
function (req, res, next){ passport.authenticate('local-signup', { session: false }, async function (err, user, info) {
try {
await UserModel.findOneAndUpdate({email: req.body.email}, { firstName: req.body.firstName, lastName: req.body.lastName },
{new: true});
await req.login(
user, { session: false },
(err) => {
if (err) {
return next(err);
}
const payload = {
id: user._id, email: user.email
};
const token = jwt.sign(
payload,
process.env.JWT_TOKEN_SECRET);
console.log('JWT signed.');
res.status(200).json({
success: true,
token: `Bearer ${token}`,
user: {
id: user.id,
email: user.email,
firstName: user.firstName,
lastName: user.lastName
}
});
});
} catch (err) {
console.log('Passport Signup err: ' + err)
res.send('Sign up error: ' + err)
return next(err);
}
}
)(req, res, next)
})
In few words, I used "Model.findOneAndUpdate" inside the sign-up route to update the user's document with their first and last names.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.