| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359 |
- // entrypoints/popup/pages/Login.tsx
- import React, { useState, useEffect, useRef } from 'react'; // 添加 useRef
- import { useNavigate } from 'react-router-dom';
- import { Input, Loading, Form, Grid } from '@alifd/next';
- const { Row, Col } = Grid
- import { CustomMessage } from '@/components/CustomMessage'
- import { useLoading } from '@/components/LoadingContext';
- import request from '@/components/utils/request'
- export default function Login({ setIsLoggedIn }: { setIsLoggedIn: (loggedIn: boolean) => void }) {
- const formRef = useRef<any>(null);
- const [username, setUsername] = useState('');
- const [password, setPassword] = useState('');
- const [invitationCode, setInvitationCode] = useState('');
- const [loading, setLoading] = useState(false);
- const [errors, setErrors] = useState<{ username?: string, password?: string, code?: string, invitationCode?: string }>({});
- const [keys, setKeys] = useState('');
- const [validImg, setValidImg] = useState('');
- const { showLoading, hideLoading } = useLoading();
- const navigate = useNavigate();
- // 添加验证码状态
- const [code, setCode] = useState('');
- useEffect(() => {
- evVerify()
- }, [])
- // 添加键盘事件监听
- useEffect(() => {
- const handleKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'Enter' && !loading) {
- handleLogin({ username, password, code, invitationCode });
- }
- };
- document.addEventListener('keydown', handleKeyDown);
- return () => {
- document.removeEventListener('keydown', handleKeyDown);
- };
- // 添加依赖项,确保每次状态更新时都重新绑定事件监听器
- }, [username, password, code, invitationCode, loading]);
- const validateForm = () => {
- const newErrors: { username?: string, password?: string, code?: string, invitationCode?: string } = {};
- if (!username.trim()) {
- newErrors.username = '请输入用户名';
- }
- if (!password) {
- newErrors.password = '请输入密码';
- } else if (password.length < 6) {
- newErrors.password = '密码长度至少为6位';
- }
- // 添加验证码校验
- if (!code.trim()) {
- newErrors.code = '请输入验证码';
- }
- // 添加邀请码校验
- // if (!invitationCode.trim()) {
- // newErrors.invitationCode = '请输入邀请码';
- // }
- setErrors(newErrors);
- return Object.keys(newErrors).length === 0;
- };
- // const evVerify = () => {
- // fetch('https://user.landwu.com/api/user/verify', {
- // method: 'POST',
- // headers: {
- // 'Content-Type': 'application/json',
- // }
- // }).then(resjson => {
- // return resjson.json();
- // }).then(res => {
- // const { data = {} } = res;
- // const { data: info = {} } = data;
- // const { key = "", img = "" } = info;
- // setKeys(key)
- // setValidImg(img)
- // })
- // }
- const evVerify = async () => {
- try {
- const res = await request.post('/user/verify');
- const { data = {} } = res;
- const { data: info = {} } = data;
- const { key = "", img = "" } = info;
- setKeys(key);
- setValidImg(img);
- } catch (error) {
- CustomMessage.error('获取验证码失败');
- }
- };
- const handleLogin = async (values: any) => {
- if (!validateForm()) return;
- try {
- showLoading('登录中...');
- const params = {
- ...values,
- key: keys
- };
- const res = await request.post('/user/login', params);
- const { msg = "", token = "", code } = res;
- if (!code) {
- hideLoading();
- return false;
- }
- if (code == -1) {
- evVerify();
- CustomMessage.error(msg);
- hideLoading();
- return false;
- }
- const profileRes = await request.post('/user/getProfile', {api_token: token});
- if (profileRes.code == 1) {
- const { data = {} } = profileRes;
- const { userinfo = {} } = data;
- const userinfo_str = JSON.stringify(userinfo);
- localStorage.setItem('userinfo', userinfo_str);
- CustomMessage.success(msg);
- localStorage.setItem("access_token", token);
- localStorage.setItem('isLoggedIn', 'true');
- setTimeout(() => {
- hideLoading();
- setIsLoggedIn(true);
- navigate('/');
- }, 100);
- }
- } catch (error) {
- console.error('登录请求失败:', error);
- CustomMessage.error('网络错误,请稍后重试');
- hideLoading();
- }
- };
- // const handleLogin = (values: any) => {
- // if (!validateForm()) return
- // try {
- // // setLoading(true);
- // showLoading('登录中...');
- // const params = {
- // ...values,
- // key: keys
- // }
- // // 发送登录请求
- // fetch('https://user.landwu.com/api/user/login', {
- // method: 'POST',
- // headers: {
- // 'Content-Type': 'application/json',
- // },
- // body: JSON.stringify(params),
- // }).then(response => response.json()).then(res => {
- // const { msg = "", token = "", code } = res;
- // if (!code) {
- // // setLoading(false);
- // hideLoading();
- // return false;
- // }
- // if (code == -1) {
- // evVerify()
- // CustomMessage.error(msg);
- // // setLoading(false);
- // hideLoading();
- // return false;
- // }
- // fetch('https://user.landwu.com/api/user/getProfile', {
- // method: 'POST',
- // headers: {
- // 'Content-Type': 'application/json',
- // },
- // body: JSON.stringify({ api_token: token }),
- // }).then(response => response.json()).then(res => {
- // if (res.code == 1) {
- // const { data = {} } = res;
- // const { userinfo = {} } = data;
- // const userinfo_str = JSON.stringify(userinfo);
- // localStorage.setItem('userinfo', userinfo_str);
- // CustomMessage.success(msg);
- // localStorage.setItem("access_token", token);
- // localStorage.setItem('isLoggedIn', 'true');
- // setTimeout(() => {
- // // setLoading(false);
- // hideLoading();
- // setIsLoggedIn(true);
- // // 跳转到首页
- // navigate('/');
- // }, 100)
- // }
- // }).catch(err => {
- // // setLoading(false);
- // hideLoading();
- // })
- // }).catch((e) => {
- // console.log("catch")
- // // setLoading(false);
- // hideLoading();
- // });
- // } catch (error) {
- // console.error('登录请求失败:', error);
- // CustomMessage.error('网络错误,请稍后重试');
- // hideLoading();
- // }
- // };
- return (
- <div className="bg-gray-50 p-4">
- <div className="text-center mb-6">
- <h1 className="text-2xl font-bold text-gray-800">登录</h1>
- </div>
- <Form>
- <Form.Item
- label="用户名"
- name="username"
- required
- help={errors.username}
- validateState={errors.username ? 'error' : undefined}
- >
- <Input
- placeholder="请输入用户名"
- value={username}
- onChange={(value) => {
- if (typeof value === 'string') {
- setUsername(value);
- } else {
- setUsername(String(value));
- }
- if (errors.username) {
- setErrors({ ...errors, username: undefined });
- }
- }}
- disabled={loading}
- />
- </Form.Item>
- <Form.Item
- label="密码"
- name="password"
- required
- help={errors.password}
- validateState={errors.password ? 'error' : undefined}
- >
- <Input
- htmlType="password"
- placeholder="请输入密码"
- value={password}
- onChange={(value) => {
- if (typeof value === 'string') {
- setPassword(value);
- } else {
- setPassword(String(value));
- }
- if (errors.password) {
- setErrors({ ...errors, password: undefined });
- }
- }}
- disabled={loading}
- />
- </Form.Item>
- <Form.Item
- label="邀请码"
- name="invitationCode"
- // required
- // help={errors.invitationCode}
- // validateState={errors.invitationCode ? 'error' : undefined}
- >
- <Input
- htmlType="invitationCode"
- placeholder="请输入邀请码"
- value={invitationCode}
- onChange={(value) => {
- if (typeof value === 'string') {
- setInvitationCode(value);
- } else {
- setInvitationCode(String(value));
- }
- // if (errors.invitationCode) {
- // setErrors({ ...errors, invitationCode: undefined });
- // }
- }}
- disabled={loading}
- />
- </Form.Item>
- <Row>
- <Col span={16}>
- <Form.Item
- label="验证码"
- name="code"
- required
- help={errors.code}
- validateState={errors.code ? 'error' : undefined}
- >
- <Input
- size="large"
- placeholder="请输入验证码"
- value={code}
- onChange={(value) => {
- if (typeof value === 'string') {
- setCode(value);
- } else {
- setCode(String(value));
- }
- if (errors.code) {
- setErrors({ ...errors, code: undefined });
- }
- }}
- disabled={loading}
- />
- </Form.Item>
- </Col>
- <Col span={8}>
- <img
- src={validImg}
- style={{
- width: 82,
- height: 28,
- marginTop: 28,
- cursor: 'pointer',
- }}
- onClick={evVerify}
- />
- </Col>
- </Row>
- <Form.Item>
- <Form.Submit
- type="primary"
- validate
- loading={loading}
- onClick={handleLogin}
- className="w-full"
- style={{ marginRight: 8 }}
- >
- {loading ? '登录中...' : '登录'}
- </Form.Submit>
- </Form.Item>
- </Form>
- <div className="mt-4 text-center text-sm text-gray-500">
- <p>忘记密码?请联系管理员</p>
- </div>
- </div>
- );
- }
|