Login_20250814143240.tsx 9.4 KB

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