首页 > 解决方案 > PassportJS 和使用 postgres 创建用户

问题描述

我一直在尝试将 pg-promise 与 passportjs 一起使用,但我无法进行本地注册。我的登录效果很好。请看下面:

    passport.use(
      "local-signup",
      new LocalStrategy(
        {
          usernameField: "email",
          passwordField: "pass",
          passReqToCallback: true
        },
        (req, email, pass, done) => {
          process.nextTick(function() {
            q.db
              .one("select email from users where email = $1", email)
              .then(data => {
                if (data) {
                  return done(
                    null,
                    false,
                    req.flash("signupMessage", "User already exists")
                  );
                } else {
                  console.log("here!?");
                  q.db
                    .none(
                      "insert into users (email, pass)" +
                        `values (${email}, ${pass})`
                    )
                    .then(data => {
                      console.log("created?");
                    });
                }
              })
              .catch(err => {
                console.log(err);
              });
          });
        }
      )
    );

这里的问题是,它实际上检测用户是否已经在数据库中,但如果用户不存在,它不会创建用户名,而是跳过整个过程。

任何想法如何解决这个问题?

谢谢

标签: node.jspostgresqlpassport.jspg-promise

解决方案


你里面的代码nextTick应该是这样的:

q.db.task(async t => {
    const user = await t.oneOrNone('SELECT * FROM users WHERE email = $1', email);
    if (user) {
        return false;
    }
    await t.none('INSERT INTO users(email, pass) VALUES($1, $2)', [email, pass]);
    return true;
})
    .then(created => {
        done(
            null,
            false,
            req.flash('signupMessage', 'Created: ' + created)
        );
    })
    .catch(error => {
        console.log(error);
    });

推荐阅读