在我的專案中,我有不同的角色(賣家/用戶/管理員),我想檢查角色并重定向到特定的頁面,如果他們是賣家,例如:
。我很糾結如何在登錄前檢查Mongo DB中的角色。我的登錄頁面是基本的電子郵件-密碼和提交按鈕。
對于我的注冊,一切都很好,它使用了正確的模型并將其發布在DB中。
以下是我的一些代碼:
(客戶模型)
userSchema.statics。 login = async function (email, password, role) {
const user = await this.findOne({ email })。
if (user) {
const auth = await bcrypt.compare(password, user.password)。
if (auth) {
return 用戶。
}
throw Error("incorrect password") 。
}
throw Error("incorrect email")。
};
const ClientModel = mongoose.model("client", userSchema, "uses")。
登錄控制器:
module。 exports.clientSignIn = async (req, res) => {
const { email, password } = req.body;
try {
const user = await LoginModel.login(email, password)。
const token = createToken(user._id)。
res.cookie("jwt"/span>, token, { httpOnly: true, maxAge })。
res.redirect('/success') 。
} catch (err) {
console.log(err.message)。
}
};
提前感謝您的幫助,如果您需要更多的資訊,請隨時提出
。uj5u.com熱心網友回復:
遵循@EAzevedo的建議。
我只是改變了我的控制器
module。 exports.clientSignIn = async (req, res) => {
const { email, password } = req.body;
try {
const user = await LoginModel.login(email, password);
const token = createToken(user._id)。
res.cookie("jwt"/span>, token, { httpOnly: true, maxAge })。)
if (user.role == "client") {
res.redirect("/success") 。
} else if (user.role == "technicien") {
res.redirect("/success-technicien") 。
} else if (user.role == "superuser" ) {
res.redirect("/success-admin") 。
};
} catch (err) {
const errors = signInErrors(err)。
res.status(200).json({ errors }) 。
}
};
uj5u.com熱心網友回復:
當你得到用戶時,你應該有角色欄位。 然后檢查哪個角色登錄并將他重定向到他需要的地方
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/331068.html
標籤:
