Is there a walkthrough tutorial for setting up PassportJS with PostgreSQL (i.e., replacing MongoDB with PostgreSQL)?
Well this is open for a while, but since I found myself with the same issue here it goes. The only thing you have to do is define the localStrategy with Postgres like so:
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'pass'
},
(username, password, done) => {
log.debug("Login process:", username);
return db.one("SELECT user_id, user_name, user_email, user_role " +
"FROM users " +
"WHERE user_email=$1 AND user_pass=$2", [username, password])
.then((result)=> {
return done(null, result);
})
.catch((err) => {
log.error("/login: " + err);
return done(null, false, {message:'Wrong user name or password'});
});
}));
and then define passport.serializeUser and passport.deserializeUser:
passport.serializeUser((user, done)=>{
log.debug("serialize ", user);
done(null, user.user_id);
});
passport.deserializeUser((id, done)=>{
log.debug("deserualize ", id);
db.one("SELECT user_id, user_name, user_email, user_role FROM users " +
"WHERE user_id = $1", [id])
.then((user)=>{
//log.debug("deserializeUser ", user);
done(null, user);
})
.catch((err)=>{
done(new Error(`User with the id ${id} does not exist`));
})
});
Then define your route:
app.post('/', passport.authenticate('local'), (req, resp)=>{
log.debug(req.user);
resp.send(req.user);
});
And it should be ready to go. Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With