使用 PostgreSQL 安装 PassportJS [英] Installing PassportJS with PostgreSQL

查看:58
本文介绍了使用 PostgreSQL 安装 PassportJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有使用 PostgreSQL 设置 PassportJS 的演练教程(即,用 PostgreSQL 替换 MongoDB)?

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

推荐答案

嗯,这已经开放了一段时间,但因为我发现自己遇到了同样的问题,所以就这样吧.您唯一需要做的就是使用 Postgres 定义 localStrategy,如下所示:

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'});
      });
  }));

然后定义passport.serializeUser和passport.deserializeUser:

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`));
    })
  });

然后定义您的路线:

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.

这篇关于使用 PostgreSQL 安装 PassportJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆