I am needing some assistance with how to use passport.authenticate() when the username has been encrypted using the NPM bcryptjs library.
For example, when I create a user I encrypt the username before using passport.js to create and save the user to MongoDB. Then in my route to log in, I pass in passport.authenticate("local") as the middleware which does all checking against the username and password.
In this scenario the username is actually the encrypted string, is there a way to use the passport.authenticate to check against the passed in username and an encrypted string?
Pieces of my code that make up the registration and login route.
userParam.username = bcrypt.hashSync(userParam.username);
userModel.create(new userModel(userParam), userParam.password , (error) => {
if (error) {
response.Error = error;
return Promise.resolve(response);
}
});
//Save user
passport.authenticate('local')(req, res, function () {
req.session.save((error) => {
if (error) {
response.Error = error;
return Promise.resolve(error);
}
});
});
Login route.
app.get('/api/user/login', passport.authenticate('local'), function (req, res) {
req.session.save((err) => {
if (err) {
return res.json({ message: "Failed to sign in", err });
}
res.json({ status: "Signed In", authenticated: req.isAuthenticated(), user: req.user, session: req.session });
});
});
Update: I was able to dig deeper on the documentation for passport.js and I found that the passport.authenticate() was handled by the instance of passport.use(new LocalStrategy(...)). In that method, I was able to add my own custom logic to handle checking against an encrypted username.
Before I was just using
passport.use(new LocalStrategy(User.authenticate()));
And I was able to update for my use case performing the following....
passport.use(new LocalStrategy(
async function(username, password, done) {
let allUsers = await User.find({});
if(username.length == 7) {
for(var i = 0; i < allUsers.length; i++) {
if (bcrypt.compareSync(username, allUsers[i].username)) {
username = allUsers[i].username ;
break;
}
}
}
User.findOne({ username }, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!password) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
```
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.