【问题标题】:How to implement the change password API in typescript with jwt?如何使用 jwt 在 typescript 中实现更改密码 API?
【发布时间】:2021-09-02 02:19:20
【问题描述】:

我创建了登录 api 并在其中实现了 jwt。现在我正在尝试使用带有 cookie 或本地存储的 jwt 身份验证来实现 change_password。我试过但无法做到这一点。任何人都可以帮助我更改密码 api,并且我还附上了我的登录 API。

 export let login=async(req:Request,resp:Response)=>{

 var {email , password} = req.body;
 try{

    const user=await User.findOne({email}).lean();

    if(!user){
        return resp.json({message:"user not found"})
    }

    if(await bcryptjs.compare(password,user.password)){
        const token=jwt.sign(
            {
                id:user._id,
                username:user.email
            },config.token.secret)
        
        return resp.json({status:'ok',data:token})
    }

    return resp.json({status:'error',data:'comming soon'})
       
 }catch(error){
     console.log(error);
 }
}

【问题讨论】:

    标签: javascript node.js typescript express jwt


    【解决方案1】:

    您可以为更改密码创建不同的路径,并且可以有多种方法来执行此操作。让我们保持简单。

    您可以询问用户用户名和现有密码以及新密码。检查现有密码是否与数据库中的密码匹配,并对新密码进行哈希处理并保存。

    app.post('/passwordChange', (req, res) => {
         const {username, password, newPassword} = req.body;
         const user = User.findOne({username});
         //check the password matches and then update the User with new password
    
         const matched = await bcryptjs.compare(password,user.password);
        
         if (matched) {
             User.updateOne({}) // go your things
         }
         else {
            // do tell your to update correct password 
         }
         
    })
    

    可以有多种简单和复杂的方法来实现它。以上代码为伪代码,修改后在代码中使用即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-26
      • 1970-01-01
      • 2023-03-23
      • 2017-02-24
      • 2020-01-21
      • 1970-01-01
      • 2020-05-13
      • 1970-01-01
      相关资源
      最近更新 更多