Login_20250814133550.tsx 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. const userinfo_str = JSON.stringify(userinfo);
  93. localStorage.setItem('userinfo', userinfo_str);
  94. CustomMessage.success(msg);
  95. localStorage.setItem("access_token", token);
  96. localStorage.setItem('isLoggedIn', 'true');
  97. setLoading(false);
  98. setIsLoggedIn(true);
  99. // 跳转到首页
  100. navigate('/');
  101. }
  102. }).catch(err => {
  103. setLoading(false);
  104. })
  105. }).catch((e) => {
  106. console.log("catch")
  107. setLoading(false);
  108. });
  109. } catch (error) {
  110. console.error('登录请求失败:', error);
  111. CustomMessage.error('网络错误,请稍后重试');
  112. } finally {
  113. setLoading(false);
  114. }
  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>
  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. if (typeof value === 'string') {
  134. setUsername(value);
  135. } else {
  136. setUsername(String(value));
  137. }
  138. if (errors.username) {
  139. setErrors({ ...errors, username: undefined });
  140. }
  141. }}
  142. disabled={loading}
  143. />
  144. </Form.Item>
  145. <Form.Item
  146. label="密码"
  147. name="password"
  148. required
  149. help={errors.password}
  150. validateState={errors.password ? 'error' : undefined}
  151. >
  152. <Input
  153. htmlType="password"
  154. placeholder="请输入密码"
  155. value={password}
  156. onChange={(value) => {
  157. if (typeof value === 'string') {
  158. setPassword(value);
  159. } else {
  160. setPassword(String(value));
  161. }
  162. if (errors.password) {
  163. setErrors({ ...errors, password: undefined });
  164. }
  165. }}
  166. disabled={loading}
  167. />
  168. </Form.Item>
  169. <Row>
  170. <Col span={16}>
  171. <Form.Item
  172. label="验证码"
  173. name="code"
  174. required
  175. help={errors.code}
  176. validateState={errors.code ? 'error' : undefined}
  177. >
  178. <Input
  179. size="large"
  180. placeholder="请输入验证码"
  181. value={code}
  182. onChange={(value) => {
  183. if (typeof value === 'string') {
  184. setCode(value);
  185. } else {
  186. setCode(String(value));
  187. }
  188. if (errors.code) {
  189. setErrors({ ...errors, code: undefined });
  190. }
  191. }}
  192. disabled={loading}
  193. />
  194. </Form.Item>
  195. </Col>
  196. <Col span={8}>
  197. <img
  198. src={validImg}
  199. style={{
  200. width: 82,
  201. height: 28,
  202. marginTop: 28,
  203. cursor: 'pointer',
  204. }}
  205. onClick={evVerify}
  206. />
  207. </Col>
  208. </Row>
  209. <Form.Item>
  210. <Form.Submit
  211. type="primary"
  212. validate
  213. loading={loading}
  214. onClick={handleLogin}
  215. className="w-full"
  216. style={{ marginRight: 8 }}
  217. >
  218. {loading ? '登录中...' : '登录'}
  219. </Form.Submit>
  220. </Form.Item>
  221. </Form>
  222. <div className="mt-4 text-center text-sm text-gray-500">
  223. <p>忘记密码?请联系管理员</p>
  224. </div>
  225. </div>
  226. );
  227. }