Login_20250812112514.tsx 7.4 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. console.log(values,"values")
  57. const { username, password, code } = 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. // setTimeout(() => {
  102. // // 这里添加实际的登录逻辑
  103. // if (username && password) {
  104. // // 模拟登录成功
  105. // localStorage.setItem('isLoggedIn', 'true');
  106. // setIsLoggedIn(true);
  107. // // 跳转到首页
  108. // navigate('/');
  109. // Message.success('登录成功');
  110. // } else {
  111. // Message.error('登录失败,请检查用户名和密码');
  112. // }
  113. // setLoading(false);
  114. // }, 1000);
  115. };
  116. return (
  117. <div className="bg-gray-50 p-4">
  118. <div className="text-center mb-6">
  119. <h1 className="text-2xl font-bold text-gray-800">登录</h1>
  120. </div>
  121. <Form onSubmit={handleLogin} ref={formRef}>
  122. <Form.Item
  123. label="用户名"
  124. name="username"
  125. required
  126. help={errors.username}
  127. validateState={errors.username ? 'error' : undefined}
  128. >
  129. <Input
  130. placeholder="请输入用户名"
  131. value={username}
  132. onChange={(value) => {
  133. setUsername(value);
  134. if (errors.username) {
  135. setErrors({ ...errors, username: undefined });
  136. }
  137. }}
  138. disabled={loading}
  139. />
  140. </Form.Item>
  141. <Form.Item
  142. label="密码"
  143. name="password"
  144. required
  145. help={errors.password}
  146. validateState={errors.password ? 'error' : undefined}
  147. >
  148. <Input
  149. htmlType="password"
  150. placeholder="请输入密码"
  151. value={password}
  152. onChange={(value) => {
  153. setPassword(value);
  154. if (errors.password) {
  155. setErrors({ ...errors, password: undefined });
  156. }
  157. }}
  158. disabled={loading}
  159. />
  160. </Form.Item>
  161. <Row>
  162. <Col span={16}>
  163. <Form.Item
  164. label="验证码"
  165. name="code"
  166. required
  167. >
  168. <Input
  169. size="large"
  170. />
  171. </Form.Item>
  172. </Col>
  173. <Col span={8}>
  174. <img
  175. src={validImg}
  176. style={{
  177. width: 82,
  178. height: 30,
  179. marginTop: 28
  180. }}
  181. onClick={evVerify}
  182. />
  183. </Col>
  184. </Row>
  185. <Form.Item>
  186. <Button
  187. type="primary"
  188. htmlType="submit"
  189. loading={loading}
  190. className="w-full"
  191. >
  192. {loading ? '登录中...' : '登录'}
  193. </Button>
  194. </Form.Item>
  195. </Form>
  196. <div className="mt-4 text-center text-sm text-gray-500">
  197. <p>忘记密码?请联系管理员</p>
  198. </div>
  199. </div>
  200. );
  201. }