How to integrate the graphic verification code component into the Ant Design Pro login function

How to integrate the graphic verification code component into the Ant Design Pro login function

Preface:

This article only introduces the steps to integrate the graphic verification code component in the Ant Design Pro login function. For the server-side method, please refer to "Verification Code Function Based on OAuth2.0 Authorization System"

text:

In the Ant Design Pro template, the account and password login function part (as shown below) does not have a graphic verification code developed, so we need to implement this function ourselves. The login function here is actually a form submission, so we only need to develop a graphic verification code form control ourselves. The specific implementation is as follows.

1. Graphic verification code form control code CaptchaInput.tsx:

import React, {useState, useEffect} from 'react';
import {Input, message} from 'antd';
import {SafetyCertificateOutlined} from '@ant-design/icons';
import api from '@/utils/api';
import stringUtil from "@/utils/stringUtil";
import request from "@/utils/request";
import {useIntl} from "umi";
 
 
interface CaptchaInputValue {
  captchaCode?: string;
  captchaKey?: string;
}
 
interface CaptchaInputProps {
  value?: CaptchaInputValue;
  onChange?: (value: CaptchaInputValue) => void;
}
 
/**
 * Get verification code */
const getCaptcha = async () => {
  try {
    const data = await request(api.captcha);
    if (data.code === 1) {
      return data.data;
    }
  } catch (error) {
    message.error('Failed to obtain department tree, please try again');
    return [];
  }
  message.error('Failed to obtain department tree, please try again');
  return [];
}
 
const CaptchaInput: React.FC<CaptchaInputProps> = ({value = {}, onChange}) => {
 
  const intl = useIntl();
  const [captchaCode, setCaptchaCode] = useState<string>('');
  const [captchaKey, setCaptchaKey] = useState<string>('');
  const [imageData, setImageData] = useState<string>('');
 
  // trigger change const triggerChange = (changedValue: { captchaCode?: string; captchaKey?: string }) => {
    if (onChange) {
      onChange({captchaCode, captchaKey, ...value, ...changedValue});
    }
  };
 
  useEffect(() => {
    getCaptcha().then((data: any) => {
      setCaptchaKey(data.captchaKey);
      setImageData(data.image);
      triggerChange({captchaKey: data.captchaKey});
    })
  }, []);
 
 
  // Input box changes const onChangeInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    const code = e.target.value || '';
    if (stringUtil.isNotEmpty(code)) {
      setCaptchaCode(code);
    }
    triggerChange({captchaCode: code});
  }
 
  // Time type changes const onClickImage = () => {
    getCaptcha().then((data: any) => {
      setCaptchaKey(data.captchaKey);
      setImageData(data.image);
      triggerChange({captchaKey: data.captchaKey});
    })
  };
 
  return (
    <span>
       <Input.Group compact>
          <Input prefix={<SafetyCertificateOutlined style={{color: "#319cff"}}/>} placeholder={intl.formatMessage({
            id: 'pages.login.captcha.placeholder',
            defaultMessage: 'Please enter the verification code',
          })}
                 onChange={onChangeInput}
                 style={{width: '75%', marginRight: 5, padding: '6.5px 11px 6.5px 11px', verticalAlign: 'middle'}}/>
                   <img style={{width: '23%', height: '35px', verticalAlign: 'middle', padding: '0px 0px 0px 0px'}}
                        src={imageData} onClick={onClickImage}/>
       </Input.Group>
    </span>
  );
};
export default CaptchaInput;

2. Login page integration components:

import CaptchaInput from './components/CaptchaInput';
 
... ... 
 
  const handleSubmit = (values: LoginParamsType) => {
    const { dispatch } = props;
    values.client_id = "hanxiaozhang";
    values.client_secret = "hanxiaozhang";
    values.scope = "hanxiaozhang";
    values.grant_type = "password";
    values.captcha_key = values.captchaComp.captchaKey;
    values.captcha_code = values.captchaComp.captchaCode;
    delete values.captchaComp;
    dispatch({
      type: 'login/login',
      payload: {...values, type},
    });
  };
 
... ... 
 
            <Form.Item name="captchaComp" rules={[{
              validateTrigger: 'onBlur',
              validator: async (rule, value) => {
                // console.log(rule)
                if (stringUtil.isEmpty(value.captchaCode)) {
                  throw new Error('Please enter the verification code!');
                }
              }
            },]}>
              <CaptchaInput/>
            </Form.Item>
 
... ...

3. Use:

The effect after integration is as follows:

The above is the details of integrating the graphic verification code component in the Ant Design Pro login function. For more information about Ant Design Pro login, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • AntDesign Pro + .NET Core implements JWT-based login authentication function
  • A brief discussion on Ant Design Pro menu custom icon
  • Controllable filtering and sorting examples in Ant Design Pro
  • How to use ProTable in Ant Design Pro
  • Solve the problem that this.props.form.validateFields is not executed in ant Design
  • Implementation code for file download under Ant Design Pro

<<:  How to use binlog for data recovery in MySQL

>>:  Implementation of Docker building Maven+Tomcat basic image

Recommend

CentOS 7 set grub password and single user login example code

There are significant differences between centos7...

Teach you how to achieve vertical centering elegantly (recommended)

Preface There are many ways to center horizontall...

Difference between MySQL btree index and hash index

In MySQL, most indexes (such as PRIMARY KEY, UNIQ...

JS quickly master ES6 class usage

1. How to construct? Let's review the common ...

Introduction to ufw firewall in Linux

Let's take a look at ufw (Uncomplicated Firew...

Add and delete table information using javascript

Getting Started with JavaScript JavaScript is a l...

20 JavaScript tips to help you improve development efficiency

Table of contents 1. Declare and initialize array...

Summary of using the reduce() method in JS

Table of contents 1. Grammar 2. Examples 3. Other...

How to monitor mysql using zabbix

Zabbix deployment documentation After zabbix is ​...

Innodb system table space maintenance method

Environmental Description: There is a running MyS...

MySQL 8.0.20 installation and configuration tutorial under Win10

MySQL 8.0.20 installation and configuration super...

Detailed instructions for installing mysql5.7 database under centos7.2

The mysql on the server is installed with version...

Sample code for implementing rolling updates of services using Docker Swarm

1. What is Docker Swarm? Docker Swarm is a cluste...

Use simple jQuery + CSS to create a custom a tag title tooltip

Introduction Use simple jQuery+CSS to create a cus...