Passport JS 本地策略允许使用电子邮件和用户名登录
Passport JS localstrategy to allow login with both email and username
我想让用户能够使用用户名和电子邮件登录。我见过类似的问题,但我认为它不适用于我的案例,现在我仍然对如何使其有效感到困惑。
我将 passport js 用于中间件,将 node js 用于后端。
这是我处理电子邮件登录的护照中间件配置:
passport.use(
"login",
new localStrategy(
{ usernameField: "email", passwordField: "password" },
async (email, password, done) => {
try {
// Find the user associated with this email provided by the user
const connection = getTypeORMConn();
const userRepo = connection.getRepository(User);
const user = await userRepo
.createQueryBuilder("user")
.select(["user.id"])
.addSelect("user.email")
.addSelect("user.passwordHash")
.addSelect("user.isVerified")
.where("user.email = :email", { email })
.getOne();
if (!user) {
return done(null, false, {
message: "User email not found (401-email)",
});
}
return done(null, user, { message: "Log in successfull" });
} catch (error) {
return done(error);
}
}
)
);
非常感谢!
您只需要检查用户是否存在于数据库中,并带有电子邮件或用户名
.where("user.email = :email OR user.username = :email", { email })
我想让用户能够使用用户名和电子邮件登录。我见过类似的问题,但我认为它不适用于我的案例,现在我仍然对如何使其有效感到困惑。 我将 passport js 用于中间件,将 node js 用于后端。
这是我处理电子邮件登录的护照中间件配置:
passport.use(
"login",
new localStrategy(
{ usernameField: "email", passwordField: "password" },
async (email, password, done) => {
try {
// Find the user associated with this email provided by the user
const connection = getTypeORMConn();
const userRepo = connection.getRepository(User);
const user = await userRepo
.createQueryBuilder("user")
.select(["user.id"])
.addSelect("user.email")
.addSelect("user.passwordHash")
.addSelect("user.isVerified")
.where("user.email = :email", { email })
.getOne();
if (!user) {
return done(null, false, {
message: "User email not found (401-email)",
});
}
return done(null, user, { message: "Log in successfull" });
} catch (error) {
return done(error);
}
}
)
);
非常感谢!
您只需要检查用户是否存在于数据库中,并带有电子邮件或用户名
.where("user.email = :email OR user.username = :email", { email })