Login_20250814114411.tsx 8.8 KB

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