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

How to solve the Mysql transaction operation failure

How to solve the Mysql transaction operation fail...

JavaScript deshaking and throttling examples

Table of contents Stabilization Throttling: Anti-...

Summary of basic usage of CSS3 @media

//grammar: @media mediatype and | not | only (med...

Tips for using DIV container fixed height in IE6 and IE7

There are many differences between IE6 and IE7 in ...

Ubuntu compiles kernel modules, and the content is reflected in the system log

Table of contents 1.Linux login interface 2. Writ...

Summary of methods to include file contents in HTML files

In the forum, netizens often ask, can I read the ...

Detailed explanation of formatting numbers in MySQL

Recently, due to work needs, I need to format num...

The difference between clientWidth, offsetWidth, scrollWidth in JavaScript

1. Concept They are all attributes of Element, in...

Simple implementation method of two-way data binding in js project

Table of contents Preface Publish-Subscriber Patt...

Mybatis mysql delete in operation can only delete the first data method

Bugs As shown in the figure, I started to copy th...

Node script realizes automatic sign-in and lottery function

Table of contents 1. Introduction 2. Preparation ...