PassportJS 和使用 postgres 创建用户
PassportJS and user creation with 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 = ", 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);
});
});
}
)
);
这里的问题是,它实际上会检测用户是否已经在数据库中,但如果用户不存在,它不会创建用户名,而是跳过整个过程。
有解决此问题的想法吗?
谢谢
你在 nextTick
中的代码应该是这样的:
q.db.task(async t => {
const user = await t.oneOrNone('SELECT * FROM users WHERE email = ', email);
if (user) {
return false;
}
await t.none('INSERT INTO users(email, pass) VALUES(, )', [email, pass]);
return true;
})
.then(created => {
done(
null,
false,
req.flash('signupMessage', 'Created: ' + created)
);
})
.catch(error => {
console.log(error);
});
我一直在尝试将 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 = ", 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);
});
});
}
)
);
这里的问题是,它实际上会检测用户是否已经在数据库中,但如果用户不存在,它不会创建用户名,而是跳过整个过程。
有解决此问题的想法吗?
谢谢
你在 nextTick
中的代码应该是这样的:
q.db.task(async t => {
const user = await t.oneOrNone('SELECT * FROM users WHERE email = ', email);
if (user) {
return false;
}
await t.none('INSERT INTO users(email, pass) VALUES(, )', [email, pass]);
return true;
})
.then(created => {
done(
null,
false,
req.flash('signupMessage', 'Created: ' + created)
);
})
.catch(error => {
console.log(error);
});