问题
Is there a walkthrough tutorial for setting up PassportJS with PostgreSQL (i.e., replacing MongoDB with PostgreSQL)?
回答1:
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.
回答2:
Joe's answer was super helpful to me! In case anyone else runs into the following error:
TypeError: Converting circular structure to JSON
I found that modifying:
(username, password, done) => {
to include the req as such helped:
(req, email, password, done)
Cheers
回答3:
There are many ORM available what you can use for Postgres with nodeJS. E.g. Sequelize, CaminateJS etc. You can use any one of these as per your requirement and convenience.
And of course you can use passportJS with this. Some good articles what I found are
http://www.hamiltonchapman.com/blog/2014/3/25/user-accounts-using-sequelize-and-passport-in-nodejs
https://sarabinns.com/tag/passport-js-sequelize-postgresql/
http://anneblankert.blogspot.in/2015/06/node-authentication-migrate-from.html
来源:https://stackoverflow.com/questions/22078839/installing-passportjs-with-postgresql