首页 > 后端开发 > Golang > 正文

密码重置功能:使用 OTP 重置密码

碧海醫心
发布: 2024-10-07 13:34:02
转载
1295人浏览过

密码重置功能:使用 otp 重置密码

后端

2. 重置密码

转向下一个 api。

put 到 /api/reset-password, req -> otp, email, 新密码, res -> nocontent

// controllers/passwordreset.go
func resetpassword(c *fiber.ctx) error {
    type input struct {
        otp         string `json:"otp"`
        email       string `json:"email"`
        newpassword string `json:"new_password"`
    }

    var input input

    err := c.bodyparser(&input)
    if err != nil {
        return c.status(fiber.statusbadrequest).json(fiber.map{
            "error": "invalid data",
        })
    }

    // no input field should be empty
    if input.otp == "" || input.email == "" || input.newpassword == "" {
        return c.status(fiber.statusbadrequest).json(fiber.map{
            "error": "invalid data",
        })
    }

    // todo: check redis for otp and update password

    return c.sendstatus(fiber.statusnocontent)
}
登录后复制

为其添加路线

// routes/routes.go
api.put("/reset-password", controllers.resetpassword)
登录后复制

现在我需要两个函数:

  1. 验证otp -> 输入 = otp、电子邮件;输出 = 错误(如果有)
  2. updatepassword -> 输入 = 电子邮件、密码;输出 = 错误(如果有)
// utils/passwordreset.go
func verifyotp(otp string, email string, c context.context) (error, bool) {
    key := otpkeyprefix + email

    // get the value for the key
    value, err := config.redisclient.get(c, key).result()
    if err != nil {
        // the following states that the key was not found
        if err == redis.nil {
            return errors.new("otp expired / incorrect email"), false
        }

        // for other errors
        return err, true
    }

    // compare received otp's hash with value in redis
    err = bcrypt.comparehashandpassword([]byte(value), []byte(otp))
    if err != nil {
        return errors.new("incorrect otp"), false
    }

    // delete redis key to prevent abuse of otp
    err = config.redisclient.del(c, key).err()
    if err != nil {
        return err, true
    }

    return nil, false
}

func updatepassword(email string, password string, c context.context) error {
    users := config.db.collection("users")

    // hash the password
    hashedpassword, _ := bcrypt.generatefrompassword([]byte(password), 10)

    // update the password
    update := bson.m{
        "$set": bson.m{
            "password": hashedpassword,
        },
    }
    _, err := users.updatebyid(c, email, update)
    if err != nil {
        return err
    }

    return nil
}
登录后复制

现在我需要将它们放在控制器中。我使用verifyotp函数中的bool来表示错误是内部错误还是由于输入引起的。

// controllers/passwordreset.go
func resetpassword(c *fiber.ctx) error {
    type input struct {
        otp         string `json:"otp"`
        email       string `json:"email"`
        newpassword string `json:"new_password"`
    }

    var input input

    err := c.bodyparser(&input)
    if err != nil {
        return c.status(fiber.statusbadrequest).json(fiber.map{
            "error": "invalid data",
        })
    }

    // no input field should be empty
    if input.otp == "" || input.email == "" || input.newpassword == "" {
        return c.status(fiber.statusbadrequest).json(fiber.map{
            "error": "invalid data",
        })
    }

    // check redis for otp
    err, isinternalerr := utils.verifyotp(input.otp, input.email, c.context())
    if err != nil {
        var code int
        if isinternalerr {
            code = fiber.statusinternalservererror
        } else {
            code = fiber.statusunauthorized
        }

        return c.status(code).json(fiber.map{
            "error": err.error(),
        })
    }

    err = utils.updatepassword(input.email, input.newpassword, c.context())
    if err != nil {
        return c.status(fiber.statusinternalservererror).json(fiber.map{
            "error": err.error(),
        })
    }

    return c.sendstatus(fiber.statusnocontent)
}
登录后复制

api现已构建完成,可以使用以下curl命令进行测试

curl --location --request PUT 'localhost:3000/api/reset-password' \
--header 'Content-Type: application/json' \
--data-raw '{
    "email": "yashjaiswal.cse@gmail.com",
    "new_password": "tester123",
    "otp": "DM4RDNF07B"
}'
登录后复制

下一部分,我将从前端开始

以上就是密码重置功能:使用 OTP 重置密码的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号