如何实现仅状态为active的用户登录?后端代码问题排查与修复
登录接口状态校验问题排查与修复
我正在开发一个管理后台,要求只有status: 'active'的激活账户才能登录。数据库中该字段值为"active",但后端代码运行时却返回错误提示**"Still Pending Account"**。
原后端登录接口代码
router.post('/login', async (req,res) =>{ try { const studentId = await User.findOne({studentId: req.body.studentId}) if(!studentId) return res.status(404).json("User is not yet accepted") const studentStatus = await User.findOne({status: 'active'}) if(studentStatus === 'active'){ const isPasswordCorrect = CryptoJS.AES.decrypt( studentId.password, process.env.PASSWORD_SEC ) const originalPassowrd = isPasswordCorrect.toString(CryptoJS.enc.Utf8) if(originalPassowrd !== req.body.password) return res.status(400).json("Incorrect password") const acessToken = jwt.sign({ id:studentId._id, isAdmin: studentId.isAdmin }, process.env.JWT_KEY, {expiresIn: "3d"}) const {password, ...others} = studentId._doc res.status(200).json({...others, acessToken}) }else{ return res.status(400).json("Still Pending Account") } } catch (error) { res.status(400).json({message:error.message}) } })
UserSchema定义
const UserSchema = new mongoose.Schema( { firstname: {type: String, required: true}, middlename: {type: String}, lastname: {type: String, required: true}, email: {type: String, required: true, unique: true}, department: {type: String, required: true}, password: {type:String, required: true}, studentId: {type:String,required:true,unique:true}, img: {type: String}, isAdmin: {type: Boolean,default: false}, status: {type:String, default: "active"}, } , {timestamps: true} )
我通过获取others.status的值并判断其是否等于'active'解决了该问题,修改后的代码如下:
修改后的登录接口代码
router.post('/login', async (req,res) =>{ try { const studentId = await User.findOne({studentId: req.body.studentId}) if(!studentId) return res.status(404).json("User is not yet accepted") const isPasswordCorrect = CryptoJS.AES.decrypt( studentId.password, process.env.PASSWORD_SEC ) const originalPassowrd = isPasswordCorrect.toString(CryptoJS.enc.Utf8) if(originalPassowrd !== req.body.password) return res.status(400).json("Incorrect password") const acessToken = jwt.sign({ id:studentId._id, isAdmin: studentId.isAdmin }, process.env.JWT_KEY, {expiresIn: "3d"}) const {password, ...others} = studentId._doc if(others.status === 'active'){ res.status(200).json({...others, acessToken}) } else{ res.status(404).json("Account still Pending") } } catch (error) { res.status(400).json({message:error.message}) } })
内容的提问来源于stack exchange,提问作者Stykgwar
相关产品推荐
相关产品推荐

