Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Installing PassportJS with PostgreSQL

Is there a walkthrough tutorial for setting up PassportJS with PostgreSQL (i.e., replacing MongoDB with PostgreSQL)?

like image 790
user3340132 Avatar asked Feb 27 '14 19:02

user3340132


1 Answers

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.

like image 179
Joel Matias Avatar answered Oct 11 '22 10:10

Joel Matias