Login_20250812112458.tsx 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. // entrypoints/popup/pages/Login.tsx
  2. import React, { useState } from 'react';
  3. import { useNavigate } from 'react-router-dom';
  4. import { Button, Input, Message, Form, Grid } from '@alifd/next';
  5. const { Row, Col } = Grid
  6. export default function Login({ setIsLoggedIn }: { setIsLoggedIn: (loggedIn: boolean) => void }) {
  7. const formRef = useRef<any>(null); // 创建 ref 引用
  8. const [username, setUsername] = useState('');
  9. const [password, setPassword] = useState('');
  10. const [loading, setLoading] = useState(false);
  11. const [errors, setErrors] = useState<{ username?: string, password?: 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 } = {};
  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. setErrors(newErrors);
  29. return Object.keys(newErrors).length === 0;
  30. };
  31. const evVerify = () => {
  32. console.log('username')
  33. fetch('https://user.landwu.com/api/user/verify', {
  34. method: 'POST',
  35. headers: {
  36. 'Content-Type': 'application/json',
  37. }
  38. }).then(resjson => {
  39. return resjson.json(); // 正确解析 Response 为 JSON 数据
  40. }).then(res => {
  41. const { data = {} } = res;
  42. const { data: info = {} } = data;
  43. const { key = "", img = "" } = info;
  44. setKeys(key)
  45. setValidImg(img)
  46. })
  47. }
  48. const handleLogin = (e: React.FormEvent) => {
  49. e.preventDefault();
  50. if (!validateForm()) {
  51. return;
  52. }
  53. setLoading(true);
  54. try {
  55. const values = formRef.current.getFieldValues();
  56. const { username, password, code } = values;
  57. const params = {
  58. username,
  59. password,
  60. code,
  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. Message.error(msg);
  79. setLoading(false);
  80. return false;
  81. }
  82. Message.success(msg);
  83. localStorage.setItem("access_token", token);
  84. localStorage.setItem('isLoggedIn', 'true');
  85. setIsLoggedIn(true);
  86. // 跳转到首页
  87. navigate('/');
  88. // Cookies.set("access_token", toCode(token));
  89. }).catch((e) => {
  90. console.log("catch")
  91. setLoading(false);
  92. });
  93. } catch (error) {
  94. console.error('登录请求失败:', error);
  95. Message.error('网络错误,请稍后重试');
  96. } finally {
  97. setLoading(false);
  98. }
  99. // 模拟登录请求
  100. // setTimeout(() => {
  101. // // 这里添加实际的登录逻辑
  102. // if (username && password) {
  103. // // 模拟登录成功
  104. // localStorage.setItem('isLoggedIn', 'true');
  105. // setIsLoggedIn(true);
  106. // // 跳转到首页
  107. // navigate('/');
  108. // Message.success('登录成功');
  109. // } else {
  110. // Message.error('登录失败,请检查用户名和密码');
  111. // }
  112. // setLoading(false);
  113. // }, 1000);
  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 onSubmit={handleLogin} ref={formRef}>
  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. setUsername(value);
  133. if (errors.username) {
  134. setErrors({ ...errors, username: undefined });
  135. }
  136. }}
  137. disabled={loading}
  138. />
  139. </Form.Item>
  140. <Form.Item
  141. label="密码"
  142. name="password"
  143. required
  144. help={errors.password}
  145. validateState={errors.password ? 'error' : undefined}
  146. >
  147. <Input
  148. htmlType="password"
  149. placeholder="请输入密码"
  150. value={password}
  151. onChange={(value) => {
  152. setPassword(value);
  153. if (errors.password) {
  154. setErrors({ ...errors, password: undefined });
  155. }
  156. }}
  157. disabled={loading}
  158. />
  159. </Form.Item>
  160. <Row>
  161. <Col span={16}>
  162. <Form.Item
  163. label="验证码"
  164. name="code"
  165. required
  166. >
  167. <Input
  168. size="large"
  169. />
  170. </Form.Item>
  171. </Col>
  172. <Col span={8}>
  173. <img
  174. src={validImg}
  175. style={{
  176. width: 82,
  177. height: 30,
  178. marginTop: 28
  179. }}
  180. onClick={evVerify}
  181. />
  182. </Col>
  183. </Row>
  184. <Form.Item>
  185. <Button
  186. type="primary"
  187. htmlType="submit"
  188. loading={loading}
  189. className="w-full"
  190. >
  191. {loading ? '登录中...' : '登录'}
  192. </Button>
  193. </Form.Item>
  194. </Form>
  195. <div className="mt-4 text-center text-sm text-gray-500">
  196. <p>忘记密码?请联系管理员</p>
  197. </div>
  198. </div>
  199. );
  200. }