【图文并茂】ant design pro 如何优雅奇妙地添加修改密码的功能

news2024/9/30 17:36:36

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
如上图所示,我们要加这样的一个功能,如何做呢?

首先要写好前端页面,再对接好后端,然后我们要判断当前密码是否正确,如果正确才能新密码修改好。

前端页面

src/pages/account/change-password/index.tsx

import { ProFormText, ProForm } from '@ant-design/pro-components';
import React, { useState } from 'react';
import { Alert, Button, Form, message } from 'antd';
import { updateItem } from '@/services/ant-design-pro/api';
import { useIntl } from '@umijs/max';

const ChangePassword: React.FC = () => {
  const [form] = Form.useForm();
  const [content, setContent] = useState<string | undefined>(undefined);
  const intl = useIntl();

  return (
    <div style={{ padding: 20 }}>
      <ProForm
        style={{ backgroundColor: 'white', padding: 20 }}
        form={form}
        onFinish={async (values) => {
          console.log('values', values);
          try {
            await updateItem('/auth/profile', values);
            message.success(intl.formatMessage({ id: 'password.changed.successfully' }));
            form.resetFields();
            setContent(undefined);
          } catch (err: any) {
            console.dir(err);
            setContent(err.response.data.message || err.message);
          }
        }}
        submitter={{
          render: (props) => {
            console.log(props);
            return [
              <Button type="primary" key="submit" onClick={() => props.form?.submit?.()}>
                {intl.formatMessage({ id: 'submit' })}
              </Button>,
            ];
          },
        }}
      >
        {content && (
          <Alert
            style={{
              marginBottom: 24,
              width: 330,
            }}
            message={content}
            type="error"
            showIcon
          />
        )}
        <ProFormText.Password
          name="currentPassword"
          label={intl.formatMessage({ id: 'current.password' })}
          width="md"
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'please.enter' }),
            },
          ]}
        />
        <ProFormText.Password
          name="password"
          label={intl.formatMessage({ id: 'new.password' })}
          width="md"
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'enter_password' }),
            },
          ]}
        />
        <ProFormText.Password
          name="confirmPassword"
          label={intl.formatMessage({ id: 'confirm.password' })}
          width="md"
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'please.enter' }),
            },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(
                  new Error(intl.formatMessage({ id: 'passwords.must.match' })),
                );
              },
            }),
          ]}
        />
      </ProForm>
    </div>
  );
};

export default ChangePassword;

这个比较简单,

const [content, setContent] = useState<string | undefined>(undefined);

这里是设置错误信息用的。

onFinish={async (values) => {
          console.log('values', values);
          try {
            await updateItem('/auth/profile', values);
            message.success(intl.formatMessage({ id: 'password.changed.successfully' }));
            form.resetFields();
            setContent(undefined);
          } catch (err: any) {
            console.dir(err);
            setContent(err.response.data.message || err.message);
          }
        }}

这里是处理提交逻辑的。

await updateItem('/auth/profile', values);

这边发了一个请求

后端

在这里插入图片描述

const updateUserProfile = handleAsync(async (req: RequestCustom, res: Response) => {
  const { password, name, email, currentPassword, confirmPassword } = req.body;
  const userId = req.user?._id;

  if (!userId) {
    res.status(401);
    throw new Error('User not authenticated');
  }

  if (confirmPassword && confirmPassword !== password) {
    res.status(400);
    throw new Error('Passwords do not match');
  }

  const user = await User.findById(userId);

  if (!user) {
    res.status(404);
    throw new Error('User not found');
  }

  // 验证当前密码
  if (currentPassword && !(await bcrypt.compare(currentPassword, user.password))) {
    res.status(400);
    throw new Error('Current password is incorrect');
  }

  // 如果提供了新密码,则加密它
  let hashPassword = user.password;
  if (password) {
    const salt = await bcrypt.genSalt(10);
    hashPassword = await bcrypt.hash(password, salt);
  }

  const updatedUser = await User.findByIdAndUpdate(userId, {
    name: name || user.name,
    email: email || user.email,
    password: hashPassword,
  }, { new: true });

  res.json({
    success: true,
    name: updatedUser?.name,
    email: updatedUser?.email,
    token: generateToken(updatedUser!.id), // 注意: 请确保 generateToken 可以接受用户的 id 类型
  });
});

都有注释,应该能看明白。

完结。


  • 获取 ant design pro & nodejs & typescript 多角色权限动态菜单管理系统源码*
  • 我正在做的程序员赚钱副业 - Shopify 真实案例技术赚钱营销课视频教程

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2066137.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【直观表格】常见神经网络计算复杂度对比 ——从时间复杂度和空间复杂度角度剖析

常见神经网络计算复杂度对比 ——从时间复杂度和空间复杂度角度剖析 【表格】常见神经网络计算复杂度对比 神经网络类型时间复杂度空间复杂度关键参数备注多层感知机&#xff08;MLP&#xff09; O ( n ⋅ d ⋅ h ) O(n \cdot d \cdot h) O(n⋅d⋅h) O ( d ⋅ h h ) O(d \c…

helm安装jenkins保姆级别

一、创建nfs服务器 这一步跳过、自行百度 注意&#xff1a;要给共享目录赋予权限chmod一下&#xff0c;不然到时候容器没办法在目录里面创建文件&#xff0c;初始化时候会报错误代码2 二、添加Jenkins的Helm仓库 helm repo add jenkinsci https://charts.jenkins.io helm re…

护眼台灯真的有用吗?学生护眼台灯十大牌子推荐

在当前近视患者剧增&#xff0c;我们发现近视还与青光眼的发生有关联&#xff0c;这是一种可能导致永久性视力丧失的眼病。青光眼通常是由于眼内压力过高造成的视神经损伤。高度近视患者的眼球结构变化可能增加眼压&#xff0c;从而提高患青光眼的风险。预防近视变得非常重要&a…

html js弹幕功能

效果如上 html <!DOCTYPE html> <html><head><meta charset"utf-8" /><title></title><script charset"utf-8" src"https://unpkg.com/vue2.6.14/dist/vue.min.js" type"text/javascript">…

[C语言]-基础知识点梳理-编译、链接、预处理

前言 各位师傅大家好&#xff0c;我是qmx_07,今天来给大家讲解以下程序运行会经历哪些事情 翻译环境和运⾏环境 在ANSIC的任何⼀种实现中&#xff0c;存在两个不同的环境 第1种是翻译环境&#xff0c;在这个环境中源代码被转换为可执⾏的机器指令&#xff08;⼆进制指令&a…

[FSCTF 2023]ez_php2

[FSCTF 2023]ez_php2 点开之后是一段php代码&#xff1a; <?php highlight_file(__file__); Class Rd{public $ending;public $cl;public $poc;public function __destruct(){echo "All matters have concluded";die($this->ending);}public function __call…

django宿舍管理系统 ---附源码98595

目 录 摘要 1 绪论 1.1 研究背景与意义 1.2 国内外研究现状 1.3论文结构与章节安排 2 宿舍管理系统系统分析 2.1 可行性分析 2.2 系统流程分析 2.2.1 数据增加流程 2.2.2 数据修改流程 2.2.3 数据删除流程 2.3 系统功能分析 2.3.1 功能性分析 2.3.2 非功能性分析…

vue vite创建项目步骤

1. 创建vue项目 node版本需18以上 不然报错 npm init vuelatest2. 项目配置 配置项目的icon配置项目的标题配置jsconfig.json 3. 项目目录结构划分 4.css样式的重置 npm install normalize.cssreset.css html {line-height: 1.2; }body, h1, h2, h3, h4, ul, li {padding…

aspose-words将tinymce中的换页符转换为word的换页符

aspose-words版本&#xff1a;21.1 java&#xff1a;1.8 tinymc&#xff1a;5.0.16 public void convertPageBreak() throws Exception{String sourceHtml "hello<!-- pagebreak -->world";sourceHtml sourceHtml.replaceAll("<!-- pagebreak -->…

鸿蒙崛起,前端/Java人才如何搭上这趟技术快车?

在科技飞速发展的今天&#xff0c;鸿蒙系统的崛起犹如一颗璀璨的新星&#xff0c;照亮了技术领域的新航道。对于前端和 Java 人才来说&#xff0c;这不仅仅是一个新的挑战&#xff0c;更是一次搭乘技术快车、实现职业飞跃的绝佳机遇。 一、鸿蒙崛起之势 鸿蒙系统自诞生以来&…

开放式耳机是什么意思?开放式对比入耳式耳机的音质更通透

开放式耳机是一种无需入耳的蓝牙耳机。它主要提供的是一种自然、开放的音频体验&#xff0c;并且无需封耳&#xff0c;能维持佩戴者对外界的感知和环境的联系。这种耳机并不需要深入耳道&#xff0c;但又能清晰听清耳机传来的内容&#xff0c;所以在佩戴方面会更加舒适。 开放…

告别本地硬件烦恼,一分钟教你用云端部署玩Stable Diffusion!

Stable diffusion有两种部署方式&#xff0c;分别是本地部署和云端部署。 本地部署需要把程序安装到自己的电脑上&#xff0c;因此对设备&#xff08;尤其是显卡显存&#xff09;要求比较高&#xff0c;但很多小伙伴反映自己设备不到位&#xff0c;升级设备费用成本过高&#…

【学习笔记】8、脉冲波形的变换与产生

本章简略记录。 8.1 单稳态触发器&#xff08;脉冲触发&#xff09; 单稳态触发器 应用于 &#xff1a;&#xff08;1&#xff09;脉冲整型&#xff08;2&#xff09;脉冲延时 &#xff08;3&#xff09;定时 单稳态触发器的工作特性&#xff1a; 没有触发脉冲作用时&#xf…

【EI会议征稿通知】 第四届航空航天、空气动力学与机电工程国际学术会议(AAME 2025)

第四届航空航天、空气动力学与机电工程国际学术会议&#xff08;AAME 2025&#xff09; 2025 4th International Conference on Aerospace, Aerodynamics and Mechatronics Engineering 会议将围绕“航天航空科学”、“空气动力学”、“机电工程”、“飞行器技术”等主题展开讨…

为什么制造企业智能化升级需要MES管理系统

在制造业的数字化转型浪潮中&#xff0c;MES管理系统的智能化升级扮演着至关重要的角色&#xff0c;它不仅重新定义了生产管理的边界&#xff0c;还为企业带来了前所未有的竞争力与可持续发展动力。本文将从数据赋能、人机深度融合、资源优化及生态协同四个维度&#xff0c;探讨…

ARM工作模式

ARM ARM架构ARM七个工作模式寄存器异常向量表存储格式&#xff08;内存大小端&#xff09;汇编指令 ARM架构 RAM&#xff1a;随机访问存储器 ROM&#xff1a;只读访问存储器 AHB&#xff1a;先进高速总线 APB&#xff1a;先进外设总线 USB&#xff1a;统一串行总线 norflash&am…

公司如何保护源代码不被员工泄漏?

保护源代码不被员工泄漏的方法&#xff1a; 1、验证&#xff1a;第三方身份验证&#xff0c;能减少账号泄密的风险&#xff1b; 2、法律保护&#xff1a;签署法律文件&#xff0c;可以一定程度上的防止员工主动泄密&#xff1b; 3、隔离控制&#xff1a;实施网络隔离&#x…

UV LED供电为什么要选择使用恒流驱动电源

LED为何一定要恒流供电? 在讨论此议题之前&#xff0c;什么是电源的恒流恒压&#xff1f; 什么是电源的恒流恒压   恒流&#xff0c;就是输出电流是恒定的&#xff0c;但电源电流却不是固定的&#xff0c;标称的电压只是安全上限&#xff1b;恒压&#xff0c;就是输出电压是…

TQRFSOC开发板47DR,100G光口自环测试

本实例将演示如何在RFSOC 47DR开发板上&#xff0c;实现100G光口自环测试。此测试使用光口自环模块实现硬件互联&#xff0c;FPGA中进行25Gbps收发校验&#xff0c;通过vivado的硬件管理器烧写比特流&#xff0c;查看传输误差与眼图。 开发板启动模式设置为JTAG模式&#xff0c…

不用再找了,国内无限制使用GPT 4o的方法【2024年9月 亲测好用】

都知道ChatGPT很强大&#xff0c;聊聊天、写论文、搞翻译、写代码、写文案、审合同等等&#xff0c;无所不能~ 那么到底怎么使用呢&#xff1f;其实很简单了&#xff0c;国内AI产品发展也很快&#xff0c;很多都很好用了~ 我一直在用&#xff0c;建议收藏下来~ 有最先进、最…