简体   繁体   中英

PassportJS and user creation with postgres

I've been trying to use pg-promise with passportjs, but I can't get to work local-signup. My login works well. Please see below:

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

The problem here is that, it actually detects if an user is already in the database, but if the user doesn't exists, it doesn't create the username, but instead, skips the whole process.

Any ideas how to fix this issue?

Thank you

Your code inside nextTick should be something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM