Login.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. import { encryptPassword } from '../utils/cryptots';
  2. import React, { useState, useEffect } from 'react';
  3. import { useNavigate, useSearchParams, Link, useLocation } from 'react-router-dom';
  4. import { authService } from '../services/authService';
  5. import { userApi } from '../services/userApi';
  6. import { Mail, Lock, GraduationCap, AlertCircle, CheckCircle2, Phone } from 'lucide-react';
  7. import { User, Loader2 } from '../icons/commonIcons';
  8. import { BrandingContext } from '../App';
  9. // 忘记密码弹窗(两步流程)
  10. const ForgotPasswordModal: React.FC<{ onClose: () => void }> = ({ onClose }) => {
  11. const [step, setStep] = useState<'verify' | 'reset'>('verify')
  12. const [phone, setPhone] = useState('')
  13. const [code, setCode] = useState('')
  14. const [newPwd, setNewPwd] = useState('')
  15. const [confirmPwd, setConfirmPwd] = useState('')
  16. const [sending, setSending] = useState(false)
  17. const [countdown, setCountdown] = useState(0)
  18. const [loading, setLoading] = useState(false)
  19. const [error, setError] = useState('')
  20. const [success, setSuccess] = useState(false)
  21. useEffect(() => {
  22. if (countdown <= 0) return
  23. const t = setTimeout(() => setCountdown(c => c - 1), 1000)
  24. return () => clearTimeout(t)
  25. }, [countdown])
  26. const handleSend = async () => {
  27. if (!phone || phone.length !== 11) { setError('请输入正确的手机号'); return }
  28. setSending(true); setError('')
  29. try {
  30. await userApi.sendSmsCode(phone, 'reset_password')
  31. setCountdown(60)
  32. } catch (e: any) { setError(e.message || '发送失败') }
  33. finally { setSending(false) }
  34. }
  35. // 第一步:验证手机号+验证码
  36. const handleVerify = async (e: React.FormEvent) => {
  37. e.preventDefault()
  38. if (!phone || !code) { setError('请填写手机号和验证码'); return }
  39. setLoading(true); setError('')
  40. try {
  41. await userApi.verifySmsCode(phone, code)
  42. setStep('reset')
  43. } catch (e: any) { setError(e.message || '验证失败') }
  44. finally { setLoading(false) }
  45. }
  46. // 第二步:设置新密码
  47. const handleReset = async (e: React.FormEvent) => {
  48. e.preventDefault()
  49. if (!newPwd || !confirmPwd) { setError('请填写新密码'); return }
  50. if (newPwd !== confirmPwd) { setError('两次密码不一致'); return }
  51. if (newPwd.length < 6) { setError('密码至少6位'); return }
  52. setLoading(true); setError('')
  53. try {
  54. await userApi.resetPasswordByPhone(phone, code, encryptPassword(newPwd))
  55. setSuccess(true)
  56. } catch (e: any) { setError(e.message || '修改失败') }
  57. finally { setLoading(false) }
  58. }
  59. return (
  60. <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
  61. <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
  62. <h3 className="text-lg font-bold text-gray-900 mb-4">忘记密码</h3>
  63. {success ? (
  64. <div className="text-center py-6">
  65. <CheckCircle2 className="w-12 h-12 text-green-500 mx-auto mb-3" />
  66. <p className="text-gray-700 font-medium">密码修改成功</p>
  67. <button onClick={onClose} className="mt-4 px-6 py-2 bg-blue-600 text-white rounded-lg text-sm font-bold hover:bg-blue-700">去登录</button>
  68. </div>
  69. ) : step === 'verify' ? (
  70. <form onSubmit={handleVerify} className="space-y-4">
  71. {error && <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-600">{error}</div>}
  72. <div>
  73. <label className="block text-sm font-bold text-gray-700 mb-1">手机号</label>
  74. <input type="tel" value={phone} onChange={e => setPhone(e.target.value)} maxLength={11}
  75. placeholder="请输入注册时的手机号" autoComplete="off"
  76. className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500" required />
  77. </div>
  78. <div>
  79. <label className="block text-sm font-bold text-gray-700 mb-1">验证码</label>
  80. <div className="flex gap-2">
  81. <input type="text" value={code} onChange={e => setCode(e.target.value)} maxLength={6}
  82. placeholder="请输入验证码" autoComplete="one-time-code"
  83. className="flex-1 px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500" required />
  84. <button type="button" onClick={handleSend} disabled={sending || countdown > 0}
  85. className="px-4 py-3 bg-blue-600 text-white rounded-xl text-sm font-bold hover:bg-blue-700 disabled:opacity-50 whitespace-nowrap">
  86. {sending ? '发送中...' : countdown > 0 ? `${countdown}s` : '获取验证码'}
  87. </button>
  88. </div>
  89. </div>
  90. <div className="flex gap-3 pt-2">
  91. <button type="button" onClick={onClose} className="flex-1 py-2.5 bg-gray-100 text-gray-700 rounded-xl font-medium hover:bg-gray-200">取消</button>
  92. <button type="submit" disabled={loading}
  93. className="flex-1 py-2.5 bg-blue-600 text-white rounded-xl font-bold hover:bg-blue-700 disabled:opacity-50">
  94. {loading ? '验证中...' : '下一步'}
  95. </button>
  96. </div>
  97. </form>
  98. ) : (
  99. <form onSubmit={handleReset} className="space-y-4">
  100. {error && <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-600">{error}</div>}
  101. <div>
  102. <label className="block text-sm font-bold text-gray-700 mb-1">新密码</label>
  103. <input type="password" value={newPwd} onChange={e => setNewPwd(e.target.value)}
  104. placeholder="请输入新密码(至少6位)" autoComplete="new-password"
  105. className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500" required />
  106. </div>
  107. <div>
  108. <label className="block text-sm font-bold text-gray-700 mb-1">确认新密码</label>
  109. <input type="password" value={confirmPwd} onChange={e => setConfirmPwd(e.target.value)}
  110. placeholder="请再次输入新密码" autoComplete="new-password"
  111. className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500" required />
  112. </div>
  113. <div className="flex gap-3 pt-2">
  114. <button type="button" onClick={() => { setStep('verify'); setError('') }}
  115. className="flex-1 py-2.5 bg-gray-100 text-gray-700 rounded-xl font-medium hover:bg-gray-200">上一步</button>
  116. <button type="submit" disabled={loading}
  117. className="flex-1 py-2.5 bg-blue-600 text-white rounded-xl font-bold hover:bg-blue-700 disabled:opacity-50 flex items-center justify-center gap-2">
  118. {loading ? <><Loader2 className="w-4 h-4 animate-spin" />修改中...</> : '确认修改'}
  119. </button>
  120. </div>
  121. </form>
  122. )}
  123. </div>
  124. </div>
  125. )
  126. }
  127. type LoginType = 'normal' | 'school' | 'phone';
  128. interface LocationState {
  129. from?: {
  130. pathname: string;
  131. };
  132. }
  133. const Login: React.FC = () => {
  134. const navigate = useNavigate();
  135. const location = useLocation();
  136. const branding = React.useContext(BrandingContext);
  137. const [searchParams, setSearchParams] = useSearchParams();
  138. const [loginType, setLoginType] = useState<LoginType>('normal');
  139. const [username, setUsername] = useState('');
  140. const [password, setPassword] = useState('');
  141. const [schoolEmail, setSchoolEmail] = useState('');
  142. const [phoneNum, setPhoneNum] = useState('');
  143. const [smsCode, setSmsCode] = useState('');
  144. const [smsSending, setSmsSending] = useState(false);
  145. const [smsCountdown, setSmsCountdown] = useState(0);
  146. const [loading, setLoading] = useState(false);
  147. const [error, setError] = useState<string | null>(null);
  148. const [ssoLoading, setSsoLoading] = useState(false);
  149. const [forgotOpen, setForgotOpen] = useState(false);
  150. useEffect(() => {
  151. if (smsCountdown <= 0) return;
  152. const timer = setTimeout(() => setSmsCountdown(c => c - 1), 1000);
  153. return () => clearTimeout(timer);
  154. }, [smsCountdown]);
  155. const handleSendSms = async () => {
  156. if (!phoneNum || phoneNum.length !== 11) { setError('请输入正确的手机号'); return; }
  157. setSmsSending(true); setError(null);
  158. try {
  159. await userApi.sendSmsCode(phoneNum, 'login');
  160. setSmsCountdown(60);
  161. } catch (e: any) { setError(e.message || '发送失败'); }
  162. finally { setSmsSending(false); }
  163. };
  164. // 获取登录前想要访问的页面
  165. const from = (location.state as LocationState)?.from?.pathname || '/';
  166. // 检测SSO token并自动登录
  167. useEffect(() => {
  168. const ssoToken = searchParams.get('sso_token');
  169. if (ssoToken) {
  170. handleSSOLogin(ssoToken);
  171. }
  172. }, []);
  173. const handleSSOLogin = async (ssoToken: string) => {
  174. setSsoLoading(true);
  175. setError(null);
  176. try {
  177. const response = await authService.ssoLogin(ssoToken);
  178. if (response.code === 200) {
  179. // 登录成功,清除URL参数并跳转到原来想访问的页面
  180. setSearchParams({});
  181. navigate(from, { replace: true });
  182. } else {
  183. setError(response.message || 'SSO登录失败');
  184. // 清除无效的token参数
  185. setSearchParams({});
  186. }
  187. } catch (err) {
  188. setError(err instanceof Error ? err.message : 'SSO登录失败,请稍后重试');
  189. setSearchParams({});
  190. } finally {
  191. setSsoLoading(false);
  192. }
  193. };
  194. const handleLogin = async (e: React.FormEvent) => {
  195. e.preventDefault();
  196. setError(null);
  197. setLoading(true);
  198. try {
  199. if (loginType === 'phone') {
  200. // 手机号+验证码登录
  201. const apiResp = await userApi.loginByPhone(phoneNum, smsCode);
  202. authService.setToken(apiResp.access_token, {
  203. id: apiResp.user.id,
  204. nickname: apiResp.user.nickname,
  205. phone: apiResp.user.phone || undefined,
  206. email: apiResp.user.email || undefined,
  207. avatar: apiResp.user.avatar || undefined,
  208. registrationDate: apiResp.user.registration_date,
  209. });
  210. navigate(from, { replace: true });
  211. return;
  212. }
  213. const loginUsername = loginType === 'school' ? schoolEmail : username;
  214. const encryptedPassword = encryptPassword(password);
  215. const response = await authService.login(loginUsername, encryptedPassword);
  216. if (response.code === 200) {
  217. navigate(from, { replace: true });
  218. } else {
  219. setError(response.message || '登录失败,请检查账号密码');
  220. }
  221. } catch (err) {
  222. setError(err instanceof Error ? err.message : '登录失败,请稍后重试');
  223. } finally {
  224. setLoading(false);
  225. }
  226. };
  227. return (
  228. <>
  229. <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 via-white to-indigo-50 px-4">
  230. <div className="w-full max-w-md">
  231. <div className="bg-white rounded-2xl shadow-2xl border border-gray-100 p-8">
  232. {/* Logo/标题 */}
  233. <div className="text-center mb-8">
  234. <div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-blue-600 to-indigo-600 rounded-2xl mb-4 overflow-hidden">
  235. {branding.system_logo
  236. ? <img src={branding.system_logo} alt="logo" className="w-full h-full object-contain" />
  237. : <GraduationCap className="w-8 h-8 text-white" />}
  238. </div>
  239. <h1 className="text-2xl font-bold text-gray-900 mb-2">欢迎登录{branding.system_name}</h1>
  240. <p className="text-sm text-gray-500">{branding.system_name} AI模型服务平台</p>
  241. </div>
  242. {/* SSO登录提示 */}
  243. {ssoLoading && (
  244. <div className="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-xl flex items-center gap-3">
  245. <Loader2 className="w-5 h-5 text-blue-600 animate-spin flex-shrink-0" />
  246. <div className="flex-1">
  247. <p className="text-sm font-bold text-blue-900">正在通过学校账户一键登录...</p>
  248. <p className="text-xs text-blue-600 mt-1">请稍候,正在验证您的身份</p>
  249. </div>
  250. </div>
  251. )}
  252. {/* 登录方式切换 */}
  253. {!ssoLoading && (
  254. <div className="flex bg-gray-100 rounded-xl p-1 mb-6">
  255. <button type="button" onClick={() => { setLoginType('normal'); setError(null); }}
  256. className={`flex-1 py-2 px-2 rounded-lg text-sm font-bold transition-all ${loginType === 'normal' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}>
  257. <div className="flex items-center justify-center gap-1">
  258. <User className="w-4 h-4" /><span>账号密码</span>
  259. </div>
  260. </button>
  261. <button type="button" onClick={() => { setLoginType('phone'); setError(null); }}
  262. className={`flex-1 py-2 px-2 rounded-lg text-sm font-bold transition-all ${loginType === 'phone' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}>
  263. <div className="flex items-center justify-center gap-1">
  264. <Phone className="w-4 h-4" /><span>手机验证码</span>
  265. </div>
  266. </button>
  267. </div>
  268. )}
  269. {/* 错误提示 */}
  270. {error && (
  271. <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg flex items-center gap-2">
  272. <AlertCircle className="w-4 h-4 text-red-500 flex-shrink-0" />
  273. <p className="text-sm text-red-600">{error}</p>
  274. </div>
  275. )}
  276. {/* 登录表单 */}
  277. {!ssoLoading && (
  278. <form onSubmit={handleLogin} className="space-y-4">
  279. {loginType === 'phone' ? (
  280. <>
  281. <div>
  282. <label className="block text-sm font-bold text-gray-700 mb-2">手机号</label>
  283. <div className="relative">
  284. <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
  285. <input type="tel" value={phoneNum} onChange={(e) => setPhoneNum(e.target.value)}
  286. placeholder="请输入手机号" maxLength={11}
  287. className="w-full pl-10 pr-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all" required />
  288. </div>
  289. </div>
  290. <div>
  291. <label className="block text-sm font-bold text-gray-700 mb-2">验证码</label>
  292. <div className="flex gap-2">
  293. <input type="text" value={smsCode} onChange={(e) => setSmsCode(e.target.value)}
  294. placeholder="请输入验证码" maxLength={6}
  295. className="flex-1 px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all" required />
  296. <button type="button" onClick={handleSendSms} disabled={smsSending || smsCountdown > 0}
  297. className="px-4 py-3 bg-blue-600 text-white rounded-xl text-sm font-bold hover:bg-blue-700 disabled:opacity-50 whitespace-nowrap">
  298. {smsSending ? '发送中...' : smsCountdown > 0 ? `${smsCountdown}s` : '获取验证码'}
  299. </button>
  300. </div>
  301. </div>
  302. </>
  303. ) : loginType === 'school' ? (
  304. <div>
  305. <label className="block text-sm font-bold text-gray-700 mb-2">学校邮箱 / 学号</label>
  306. <div className="relative">
  307. <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
  308. <input type="text" value={schoolEmail} onChange={(e) => setSchoolEmail(e.target.value)}
  309. placeholder="请输入学校邮箱或学号"
  310. className="w-full pl-10 pr-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all" required />
  311. </div>
  312. <p className="mt-1 text-xs text-gray-400">支持学校邮箱(如:student@university.edu)或学号登录</p>
  313. </div>
  314. ) : (
  315. <div>
  316. <label className="block text-sm font-bold text-gray-700 mb-2">用户名 / 手机号</label>
  317. <div className="relative">
  318. <User className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
  319. <input type="text" value={username} onChange={(e) => setUsername(e.target.value)}
  320. placeholder="请输入用户名或手机号"
  321. className="w-full pl-10 pr-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all" required />
  322. </div>
  323. </div>
  324. )}
  325. {loginType !== 'phone' && (
  326. <div>
  327. <label className="block text-sm font-bold text-gray-700 mb-2">密码</label>
  328. <div className="relative">
  329. <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
  330. <input type="password" value={password} onChange={(e) => setPassword(e.target.value)}
  331. placeholder="请输入密码"
  332. className="w-full pl-10 pr-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
  333. required />
  334. </div>
  335. </div>
  336. )}
  337. <div className="flex items-center justify-between text-sm">
  338. <label className="flex items-center gap-2 cursor-pointer">
  339. <input
  340. type="checkbox"
  341. className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
  342. />
  343. <span className="text-gray-600">记住我</span>
  344. </label>
  345. <button
  346. type="button"
  347. onClick={() => setForgotOpen(true)}
  348. className="text-blue-600 hover:text-blue-700 font-medium"
  349. >
  350. 忘记密码?
  351. </button>
  352. </div>
  353. <button
  354. type="submit"
  355. disabled={loading}
  356. className="w-full py-3 bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-xl font-bold shadow-lg hover:shadow-xl hover:from-blue-700 hover:to-indigo-700 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
  357. >
  358. {loading ? (
  359. <>
  360. <Loader2 className="w-5 h-5 animate-spin" />
  361. <span>登录中...</span>
  362. </>
  363. ) : (
  364. <span>登录</span>
  365. )}
  366. </button>
  367. </form>
  368. )}
  369. {/* 其他登录方式 */}
  370. {!ssoLoading && (
  371. <div className="mt-6">
  372. <div className="relative">
  373. <div className="absolute inset-0 flex items-center">
  374. <div className="w-full border-t border-gray-200"></div>
  375. </div>
  376. <div className="relative flex justify-center text-xs">
  377. <span className="bg-white px-4 text-gray-400">或</span>
  378. </div>
  379. </div>
  380. <div className="mt-4 text-center">
  381. <p className="text-sm text-gray-600">
  382. 还没有账号?{' '}
  383. <Link
  384. to="/register"
  385. className="text-blue-600 hover:text-blue-700 font-bold"
  386. >
  387. 立即注册
  388. </Link>
  389. </p>
  390. </div>
  391. </div>
  392. )}
  393. </div>
  394. {/* 底部说明 */}
  395. {!ssoLoading && (
  396. <div className="mt-6 text-center text-xs text-gray-400">
  397. </div>
  398. )}
  399. </div>
  400. </div>
  401. {forgotOpen && <ForgotPasswordModal onClose={() => setForgotOpen(false)} />}
  402. </>
  403. );
  404. };
  405. export default Login;