Login_20250812145658.tsx 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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 = (values: any) => {
  49. setLoading(true);
  50. if (!validateForm()) return
  51. try {
  52. console.log(values, "values")
  53. const params = {
  54. ...values,
  55. key: keys
  56. }
  57. // 发送登录请求
  58. fetch('https://user.landwu.com/api/user/login', {
  59. method: 'POST',
  60. headers: {
  61. 'Content-Type': 'application/json',
  62. },
  63. body: JSON.stringify(params),
  64. }).then(response => response.json()).then(res => {
  65. const { msg = "", token = "", code } = res;
  66. if (!code) {
  67. setLoading(false);
  68. return false;
  69. }
  70. if (code == -1) {
  71. evVerify()
  72. Message.error(msg);
  73. setLoading(false);
  74. return false;
  75. }
  76. Message.success(msg);
  77. localStorage.setItem("access_token", token);
  78. localStorage.setItem('isLoggedIn', 'true');
  79. setIsLoggedIn(true);
  80. // 跳转到首页
  81. navigate('/');
  82. // Cookies.set("access_token", toCode(token));
  83. }).catch((e) => {
  84. console.log("catch")
  85. setLoading(false);
  86. });
  87. } catch (error) {
  88. console.error('登录请求失败:', error);
  89. Message.error('网络错误,请稍后重试');
  90. } finally {
  91. setLoading(false);
  92. }
  93. // 模拟登录请求
  94. // setTimeout(() => {
  95. // // 这里添加实际的登录逻辑
  96. // if (username && password) {
  97. // // 模拟登录成功
  98. // localStorage.setItem('isLoggedIn', 'true');
  99. // setIsLoggedIn(true);
  100. // // 跳转到首页
  101. // navigate('/');
  102. // Message.success('登录成功');
  103. // } else {
  104. // Message.error('登录失败,请检查用户名和密码');
  105. // }
  106. // setLoading(false);
  107. // }, 1000);
  108. };
  109. return (
  110. <div className="bg-gray-50 p-4">
  111. <div className="text-center mb-6">
  112. <h1 className="text-2xl font-bold text-gray-800">登录</h1>
  113. </div>
  114. <Form>
  115. <Form.Item
  116. label="用户名"
  117. name="username"
  118. required
  119. help={errors.username}
  120. validateState={errors.username ? 'error' : undefined}
  121. >
  122. <Input
  123. placeholder="请输入用户名"
  124. value={username}
  125. onChange={(value) => {
  126. setUsername(value);
  127. if (errors.username) {
  128. setErrors({ ...errors, username: undefined });
  129. }
  130. }}
  131. disabled={loading}
  132. />
  133. </Form.Item>
  134. <Form.Item
  135. label="密码"
  136. name="password"
  137. required
  138. help={errors.password}
  139. validateState={errors.password ? 'error' : undefined}
  140. >
  141. <Input
  142. htmlType="password"
  143. placeholder="请输入密码"
  144. value={password}
  145. onChange={(value) => {
  146. setPassword(value);
  147. if (errors.password) {
  148. setErrors({ ...errors, password: undefined });
  149. }
  150. }}
  151. disabled={loading}
  152. />
  153. </Form.Item>
  154. <Row>
  155. <Col span={16}>
  156. <Form.Item
  157. label="验证码"
  158. name="code"
  159. required
  160. >
  161. <Input
  162. size="large"
  163. />
  164. </Form.Item>
  165. </Col>
  166. <Col span={8}>
  167. <img
  168. src={validImg}
  169. style={{
  170. width: 82,
  171. height: 30,
  172. marginTop: 28
  173. }}
  174. onClick={evVerify}
  175. />
  176. </Col>
  177. </Row>
  178. <Form.Item>
  179. <Form.Submit
  180. type="primary"
  181. validate
  182. loading={loading}
  183. onClick={handleLogin}
  184. className="w-full"
  185. style={{ marginRight: 8 }}
  186. >
  187. {loading ? '登录中...' : '登录'}
  188. </Form.Submit>
  189. </Form.Item>
  190. </Form>
  191. <div className="mt-4 text-center text-sm text-gray-500">
  192. <p>忘记密码?请联系管理员</p>
  193. </div>
  194. </div>
  195. );
  196. }