Login_20250812143413.tsx 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. // entrypoints/popup/pages/Login.tsx
  2. import React, { useState, useEffect, useRef } from 'react';
  3. import { useNavigate } from 'react-router-dom';
  4. import { Button, Input, Message, Grid } from '@alifd/next';
  5. const { Row, Col } = Grid
  6. export default function Login({ setIsLoggedIn }: { setIsLoggedIn: (loggedIn: boolean) => void }) {
  7. const [username, setUsername] = useState('');
  8. const [password, setPassword] = useState('');
  9. const [code, setCode] = useState('');
  10. const [loading, setLoading] = useState(false);
  11. const [errors, setErrors] = useState<{ username?: string, password?: string, code?: string }>({});
  12. const [keys, setKeys] = useState('');
  13. const [validImg, setValidImg] = useState('');
  14. const navigate = useNavigate();
  15. useEffect(() => {
  16. evVerify()
  17. }, [])
  18. const validateForm = () => {
  19. const newErrors: { username?: string, password?: string, code?: string } = {};
  20. if (!username.trim()) {
  21. newErrors.username = '请输入用户名';
  22. }
  23. if (!password) {
  24. newErrors.password = '请输入密码';
  25. } else if (password.length < 6) {
  26. newErrors.password = '密码长度至少为6位';
  27. }
  28. if (!code.trim()) {
  29. newErrors.code = '请输入验证码';
  30. }
  31. setErrors(newErrors);
  32. return Object.keys(newErrors).length === 0;
  33. };
  34. const evVerify = () => {
  35. console.log('username')
  36. fetch('https://user.landwu.com/api/user/verify', {
  37. method: 'POST',
  38. headers: {
  39. 'Content-Type': 'application/json',
  40. }
  41. }).then(resjson => {
  42. return resjson.json(); // 正确解析 Response 为 JSON 数据
  43. }).then(res => {
  44. const { data = {} } = res;
  45. const { data: info = {} } = data;
  46. const { key = "", img = "" } = info;
  47. setKeys(key)
  48. setValidImg(img)
  49. })
  50. }
  51. const handleLogin = () => {
  52. if (!validateForm()) {
  53. return;
  54. }
  55. setLoading(true);
  56. try {
  57. console.log("values")
  58. const params = {
  59. username,
  60. password,
  61. code,
  62. key: keys
  63. }
  64. // 发送登录请求
  65. fetch('https://user.landwu.com/api/user/login', {
  66. method: 'POST',
  67. headers: {
  68. 'Content-Type': 'application/json',
  69. },
  70. body: JSON.stringify(params),
  71. }).then(response => response.json()).then(res => {
  72. const { msg = "", token = "", code } = res;
  73. if (!code) {
  74. setLoading(false);
  75. return false;
  76. }
  77. if (code == -1) {
  78. evVerify()
  79. Message.error(msg);
  80. setLoading(false);
  81. return false;
  82. }
  83. Message.success(msg);
  84. localStorage.setItem("access_token", token);
  85. localStorage.setItem('isLoggedIn', 'true');
  86. setIsLoggedIn(true);
  87. // 跳转到首页
  88. navigate('/');
  89. // Cookies.set("access_token", toCode(token));
  90. }).catch((e) => {
  91. console.log("catch")
  92. setLoading(false);
  93. });
  94. } catch (error) {
  95. console.error('登录请求失败:', error);
  96. Message.error('网络错误,请稍后重试');
  97. } finally {
  98. setLoading(false);
  99. }
  100. };
  101. const handleInputChange = (field: string, value: string) => {
  102. if (field === 'username') {
  103. setUsername(value);
  104. if (errors.username) {
  105. setErrors({ ...errors, username: undefined });
  106. }
  107. } else if (field === 'password') {
  108. setPassword(value);
  109. if (errors.password) {
  110. setErrors({ ...errors, password: undefined });
  111. }
  112. } else if (field === 'code') {
  113. setCode(value);
  114. if (errors.code) {
  115. setErrors({ ...errors, code: undefined });
  116. }
  117. }
  118. };
  119. return (
  120. <div className="bg-gray-50 p-4">
  121. <div className="text-center mb-6">
  122. <h1 className="text-2xl font-bold text-gray-800">登录</h1>
  123. </div>
  124. <div className="login-form">
  125. <div className="form-item mb-4">
  126. <label className="block text-sm font-medium text-gray-700 mb-1">用户名</label>
  127. <Input
  128. placeholder="请输入用户名"
  129. value={username}
  130. onChange={(value) => handleInputChange('username', value)}
  131. disabled={loading}
  132. />
  133. {errors.username && <div className="text-red-500 text-sm mt-1">{errors.username}</div>}
  134. </div>
  135. <div className="form-item mb-4">
  136. <label className="block text-sm font-medium text-gray-700 mb-1">密码</label>
  137. <Input
  138. htmlType="password"
  139. placeholder="请输入密码"
  140. value={password}
  141. onChange={(value) => handleInputChange('password', value)}
  142. disabled={loading}
  143. />
  144. {errors.password && <div className="text-red-500 text-sm mt-1">{errors.password}</div>}
  145. </div>
  146. <Row>
  147. <Col span={16}>
  148. <div className="form-item">
  149. <label className="block text-sm font-medium text-gray-700 mb-1">验证码</label>
  150. <Input
  151. size="large"
  152. placeholder="请输入验证码"
  153. value={code}
  154. onChange={(value) => handleInputChange('code', value)}
  155. disabled={loading}
  156. />
  157. {errors.code && <div className="text-red-500 text-sm mt-1">{errors.code}</div>}
  158. </div>
  159. </Col>
  160. <Col span={8}>
  161. <img
  162. src={validImg}
  163. style={{
  164. width: 82,
  165. height: 30,
  166. marginTop: 28,
  167. cursor: 'pointer'
  168. }}
  169. onClick={evVerify}
  170. alt="验证码"
  171. />
  172. </Col>
  173. </Row>
  174. <div className="form-item mt-6">
  175. <Button
  176. type="primary"
  177. loading={loading}
  178. onClick={handleLogin}
  179. className="w-full"
  180. >
  181. {loading ? '登录中...' : '登录'}
  182. </Button>
  183. </div>
  184. </div>
  185. <div className="mt-4 text-center text-sm text-gray-500">
  186. <p>忘记密码?请联系管理员</p>
  187. </div>
  188. </div>
  189. );
  190. }