讲师中心 微信公众号
AI工具推荐 视频效率加速

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

冬强君_1478

冬强君_1478

发布时间:2024-10-07 13:34:02

|

1591人浏览过

|

来源于dev.to

转载

密码重置功能:使用 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来表示错误是内部错误还是由于输入引起的。

Redis Skill - 高性能缓存管理
Redis Skill - 高性能缓存管理

Redis 缓存和数据结构管理技能。通过自然语言操作 Redis,支持 String、Hash、List、Set、ZSet、Stream 等数据结构操作。当用户提到 Redis、缓存、消息队列、会话存储时使用此技能。

下载
// 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"
}'

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

热门AI工具

更多
Loomy
Loomy Hot

一款AI工具,主要用于科大讯飞发布的桌面级 AI 助理,比 OpenClaw 更易用、更安全!,适合需要提升相关任务效率的用户。

咔片AIPPT

一款在线AI演示文稿制作工具,可根据主题和内容需求辅助生成PPT结构与页面,提高演示材料制作效率。

AionClaw
AionClaw Hot

AionClaw是一款面向办公、创作和编程任务的AI桌面智能体。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

切问学术

切问学术是一款AI论文写作工具,复旦大学NLP团队推出的AI学术智能体。

Seko
Seko Hot

一款AI视频创作工具,主要用于商汤科技推出的创编一体的AI短视频创作Agent,适合需要提升相关任务效率的用户。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

墨刀AI
墨刀AI Hot

一款AI图像与设计工具,主要用于产品经理的专属智能体,适合需要提升相关任务效率的用户。

相关专题

更多
curl_exec
curl_exec

curl_exec函数是PHP cURL函数列表中的一种,它的功能是执行一个cURL会话。给大家总结了一下php curl_exec函数的一些用法实例,这个函数应该在初始化一个cURL会话并且全部的选项都被设置后被调用。他的返回值成功时返回TRUE, 或者在失败时返回FALSE。

3363

2023.06.14

linux常见下载安装工具
linux常见下载安装工具

linux常见下载安装工具有APT、YUM、DNF、Snapcraft、Flatpak、AppImage、Wget、Curl等。想了解更多linux常见下载安装工具相关内容,可以阅读本专题下面的文章。

715

2023.10.30

curl_exec
curl_exec

curl_exec函数是PHP cURL函数列表中的一种,它的功能是执行一个cURL会话。给大家总结了一下php curl_exec函数的一些用法实例,这个函数应该在初始化一个cURL会话并且全部的选项都被设置后被调用。他的返回值成功时返回TRUE, 或者在失败时返回FALSE。

3363

2023.06.14

linux常见下载安装工具
linux常见下载安装工具

linux常见下载安装工具有APT、YUM、DNF、Snapcraft、Flatpak、AppImage、Wget、Curl等。想了解更多linux常见下载安装工具相关内容,可以阅读本专题下面的文章。

715

2023.10.30

Buffalo框架数据库开发全教程
Buffalo框架数据库开发全教程

本专题围绕Buffalo框架数据库开发,讲解database.yml多环境配置、soda与fizz迁移生成回滚、模型结构体标签、增删改查与条件查询、一对多与多对多关联、数据校验、回调钩子、事务处理及原生SQL执行能力。

20

2026.09.23

Buffalo框架路由与请求处理实操指南
Buffalo框架路由与请求处理实操指南

本专题讲解Buffalo框架路由与请求处理机制,涵盖路由注册与分组、资源路由、Handler编写规范、Context上下文方法、参数绑定、中间件编写挂载、Session与Cookie读写、Flash消息及错误页面定制方法。

0

2026.09.23

Buffalo框架零基础入门教程
Buffalo框架零基础入门教程

本专题整理Buffalo框架入门内容,涵盖Go环境准备、buffalo CLI安装、新项目生成、目录结构说明、dev热加载启动、数据库连接配置与常见报错排查,帮助新手按约定优于配置的思路跑通第一个Buffalo框架应用。

0

2026.09.23

Conan创建软件包配方指南
Conan创建软件包配方指南

本专题介绍通过conanfile.py创建软件包的方法,讲解包名、版本、依赖和构建设置等基础信息,以及source、build、package、package_info等常用方法的作用及编写思路。

0

2026.09.22

Conan二进制包配置指南
Conan二进制包配置指南

本专题介绍Conan根据操作系统、编译器、架构和构建类型生成二进制包的方法,讲解Profile、Settings、Options及Package ID的作用,帮助管理不同平台和编译环境下的包版本。

20

2026.09.22

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
phpEnv手册
phpEnv手册

共0课时 | 0人学习

进程与SOCKET
进程与SOCKET

共6课时 | 0.5万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn