login.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. import {
  2. ChangeDetectionStrategy,
  3. Component,
  4. ElementRef,
  5. OnDestroy,
  6. computed,
  7. inject,
  8. signal,
  9. viewChild,
  10. } from '@angular/core';
  11. import { ActivatedRoute, Router } from '@angular/router';
  12. import { FmodeApi } from '../../../core/api/fmode-api';
  13. import { DeviceService } from '../../../core/device.service';
  14. import { PaletteService } from '../../../core/palette.service';
  15. import { SessionService } from '../../../core/session.service';
  16. type Stage = 'phone' | 'code' | 'token';
  17. /**
  18. * 移动端登录(Demo 02 + SPEC FR-02)—— **真实接口**
  19. *
  20. * 三步两路(与 Demo 一致):
  21. * 手机号 → 验证码 → 登录;或「使用 Token 直接登录」
  22. *
  23. * 与 Demo 的差异(Demo 是静态演示,只校验格式):
  24. * · 「获取验证码」真实调用 `FmodeApi.sendMobileCode`
  25. * · 「登录」真实调用 `loginWithMobile` / `loginWithToken`,成功后写 `SessionService`
  26. * · `?token=` / `#token=` 自动登录并清地址栏(AC-02.2),与桌面登录页同口径
  27. * · 发送验证码后 60s 倒计时,期间禁点(防重复下发)
  28. *
  29. * AC:02.3 redirect 回跳(replaceUrl)· 02.6 明确错误文案 · 02.7 提交期间防并发
  30. */
  31. @Component({
  32. selector: 'app-mb-login-page',
  33. changeDetection: ChangeDetectionStrategy.OnPush,
  34. template: `
  35. <div class="m-login">
  36. <div class="m-brand">
  37. <p class="m-wordmark">fmode</p>
  38. <h1>{{ stage() === 'token' ? 'Token 登录' : '欢迎使用' }}</h1>
  39. <p class="m-brand-sub">人机共生中枢 · 登录后继续</p>
  40. </div>
  41. @switch (stage()) {
  42. @case ('phone') {
  43. <label class="m-field">
  44. <span class="m-prefix">+86</span>
  45. <input
  46. #phoneEl
  47. type="tel"
  48. inputmode="numeric"
  49. maxlength="11"
  50. autocomplete="tel-national"
  51. placeholder="请输入手机号"
  52. [value]="phone()"
  53. aria-label="手机号"
  54. (input)="onPhone($event)"
  55. />
  56. </label>
  57. <button type="button" class="m-btn m-btn--primary" [disabled]="!phoneValid() || busy()" (click)="sendCode()">
  58. {{ sending() ? '发送中…' : '获取验证码' }}
  59. </button>
  60. <button type="button" class="m-more" (click)="stage.set('token')">使用 Token 直接登录</button>
  61. }
  62. @case ('code') {
  63. <label class="m-field">
  64. <span class="m-prefix">+86 {{ maskedPhone() }}</span>
  65. <input
  66. #codeEl
  67. type="tel"
  68. inputmode="numeric"
  69. maxlength="6"
  70. autocomplete="one-time-code"
  71. placeholder="6 位验证码"
  72. [value]="code()"
  73. aria-label="验证码"
  74. (input)="onCode($event)"
  75. />
  76. <button type="button" class="m-get" [disabled]="countdown() > 0 || sending()" (click)="sendCode()">
  77. {{ countdown() > 0 ? countdown() + 's' : '重新发送' }}
  78. </button>
  79. </label>
  80. <button type="button" class="m-btn m-btn--primary" [disabled]="code().length !== 6 || busy()" (click)="submit()">
  81. {{ busy() ? '登录中…' : '登录' }}
  82. </button>
  83. <button type="button" class="m-more" (click)="backToPhone()">返回修改手机号</button>
  84. }
  85. @default {
  86. <label class="m-field">
  87. <input
  88. #tokenEl
  89. type="text"
  90. autocomplete="off"
  91. placeholder="粘贴 r: 开头的访问 Token"
  92. [value]="token()"
  93. aria-label="访问 Token"
  94. (input)="onToken($event)"
  95. />
  96. </label>
  97. <button type="button" class="m-btn m-btn--primary" [disabled]="!token().trim() || busy()" (click)="submit()">
  98. {{ busy() ? '登录中…' : '登录' }}
  99. </button>
  100. <button type="button" class="m-more" (click)="stage.set('phone')">返回手机号登录</button>
  101. }
  102. }
  103. @if (error()) {
  104. <p class="m-error" role="alert">
  105. <i class="fa-solid fa-circle-exclamation" aria-hidden="true"></i>
  106. {{ error() }}
  107. </p>
  108. }
  109. <label class="m-agree">
  110. <button
  111. type="button"
  112. class="m-cb"
  113. [class.on]="agreed()"
  114. role="checkbox"
  115. [attr.aria-checked]="agreed()"
  116. aria-label="同意协议"
  117. (click)="agreed.set(!agreed())"
  118. >
  119. @if (agreed()) {
  120. <i class="fa-solid fa-check" aria-hidden="true"></i>
  121. }
  122. </button>
  123. <span>
  124. 已阅读并同意<a href="#" (click)="blockLink($event)">服务协议</a>和<a href="#" (click)="blockLink($event)">隐私政策</a>
  125. </span>
  126. </label>
  127. </div>
  128. `,
  129. styles: [
  130. `
  131. :host {
  132. display: block;
  133. min-height: 100dvh;
  134. background: var(--canvas);
  135. }
  136. .m-login {
  137. display: flex;
  138. flex-direction: column;
  139. min-height: 100dvh;
  140. box-sizing: border-box;
  141. padding: calc(var(--mob-safe-top) + var(--sp-6)) var(--sp-6)
  142. calc(var(--mob-safe-bottom) + var(--sp-6));
  143. overflow-y: auto;
  144. }
  145. .m-brand {
  146. display: flex;
  147. flex: 1;
  148. flex-direction: column;
  149. align-items: center;
  150. justify-content: center;
  151. text-align: center;
  152. padding: var(--sp-8) 0 var(--sp-6);
  153. }
  154. .m-wordmark {
  155. margin: 0 0 var(--sp-2);
  156. color: var(--primary);
  157. font-size: var(--fs-42);
  158. font-weight: 700;
  159. letter-spacing: -0.02em;
  160. }
  161. .m-brand h1 {
  162. margin: var(--sp-3) 0 var(--sp-1);
  163. color: var(--ink);
  164. font-size: var(--fs-26);
  165. }
  166. .m-brand-sub {
  167. margin: 0;
  168. color: var(--muted);
  169. font-size: var(--fs-13);
  170. }
  171. .m-field {
  172. display: flex;
  173. align-items: center;
  174. gap: var(--sp-2);
  175. height: 52px;
  176. margin-bottom: var(--sp-3);
  177. padding: 0 var(--sp-4);
  178. box-sizing: border-box;
  179. border: 1px solid var(--edge);
  180. border-radius: var(--r-md);
  181. background: var(--surface);
  182. }
  183. .m-field input {
  184. flex: 1;
  185. min-width: 0;
  186. border: 0;
  187. outline: 0;
  188. background: transparent;
  189. color: var(--ink);
  190. font-size: var(--fs-17);
  191. }
  192. .m-prefix {
  193. flex: none;
  194. color: var(--ink-2);
  195. font-size: var(--fs-15);
  196. }
  197. .m-get {
  198. flex: none;
  199. border: 0;
  200. background: none;
  201. color: var(--primary);
  202. font: inherit;
  203. font-size: var(--fs-13);
  204. font-weight: 600;
  205. white-space: nowrap;
  206. cursor: pointer;
  207. }
  208. .m-get:disabled {
  209. color: var(--muted);
  210. cursor: not-allowed;
  211. }
  212. .m-btn {
  213. width: 100%;
  214. height: 52px;
  215. margin-bottom: var(--sp-3);
  216. border: 0;
  217. border-radius: var(--r-md);
  218. font: inherit;
  219. font-size: var(--fs-17);
  220. font-weight: 600;
  221. cursor: pointer;
  222. }
  223. .m-btn--primary {
  224. background: var(--primary);
  225. color: var(--primary-content);
  226. }
  227. .m-btn:disabled {
  228. opacity: 0.5;
  229. cursor: not-allowed;
  230. }
  231. .m-more {
  232. padding: var(--sp-3) 0;
  233. border: 0;
  234. background: none;
  235. color: var(--primary);
  236. font: inherit;
  237. font-size: var(--fs-13);
  238. cursor: pointer;
  239. }
  240. .m-error {
  241. display: flex;
  242. align-items: center;
  243. gap: var(--sp-2);
  244. margin: 0 0 var(--sp-3);
  245. padding: var(--sp-3);
  246. border-radius: var(--r-md);
  247. background: var(--danger-subtle);
  248. color: var(--danger);
  249. font-size: var(--fs-13);
  250. }
  251. .m-agree {
  252. display: flex;
  253. align-items: flex-start;
  254. justify-content: center;
  255. gap: var(--sp-2);
  256. margin-top: var(--sp-4);
  257. color: var(--muted);
  258. font-size: var(--fs-12);
  259. text-align: left;
  260. }
  261. .m-agree a {
  262. color: var(--primary);
  263. text-decoration: none;
  264. }
  265. .m-cb {
  266. display: grid;
  267. place-items: center;
  268. flex: none;
  269. width: 16px;
  270. height: 16px;
  271. margin-top: 2px;
  272. padding: 0;
  273. border: 1.5px solid var(--edge-strong);
  274. border-radius: var(--r-tag);
  275. background: none;
  276. color: var(--primary-content);
  277. font-size: var(--fs-9);
  278. cursor: pointer;
  279. }
  280. .m-cb.on {
  281. border-color: var(--primary);
  282. background: var(--primary);
  283. }
  284. `,
  285. ],
  286. })
  287. export class MbLoginPage implements OnDestroy {
  288. private readonly api = inject(FmodeApi);
  289. private readonly session = inject(SessionService);
  290. private readonly device = inject(DeviceService);
  291. private readonly palette = inject(PaletteService);
  292. private readonly router = inject(Router);
  293. private readonly route = inject(ActivatedRoute);
  294. protected readonly stage = signal<Stage>('phone');
  295. protected readonly phone = signal('');
  296. protected readonly code = signal('');
  297. protected readonly token = signal('');
  298. protected readonly agreed = signal(false);
  299. protected readonly error = signal<string | null>(null);
  300. protected readonly busy = signal(false);
  301. protected readonly sending = signal(false);
  302. protected readonly countdown = signal(0);
  303. protected readonly phoneValid = computed(() => /^1\d{10}$/.test(this.phone()));
  304. protected readonly maskedPhone = computed(() => {
  305. const p = this.phone();
  306. return `${p.slice(0, 3)}****${p.slice(7)}`;
  307. });
  308. private readonly phoneEl = viewChild<ElementRef<HTMLInputElement>>('phoneEl');
  309. private readonly codeEl = viewChild<ElementRef<HTMLInputElement>>('codeEl');
  310. private codeTimer: ReturnType<typeof setInterval> | null = null;
  311. constructor() {
  312. this.palette.init();
  313. void this.initFromUrl();
  314. }
  315. ngOnDestroy(): void {
  316. if (this.codeTimer) clearInterval(this.codeTimer);
  317. }
  318. protected onPhone(e: Event): void {
  319. const v = (e.target as HTMLInputElement).value.replace(/\D/g, '').slice(0, 11);
  320. this.phone.set(v);
  321. (e.target as HTMLInputElement).value = v;
  322. this.error.set(null);
  323. }
  324. protected onCode(e: Event): void {
  325. const v = (e.target as HTMLInputElement).value.replace(/\D/g, '').slice(0, 6);
  326. this.code.set(v);
  327. (e.target as HTMLInputElement).value = v;
  328. this.error.set(null);
  329. }
  330. protected onToken(e: Event): void {
  331. this.token.set((e.target as HTMLInputElement).value);
  332. this.error.set(null);
  333. }
  334. protected backToPhone(): void {
  335. this.stage.set('phone');
  336. this.code.set('');
  337. this.error.set(null);
  338. this.focus(this.phoneEl());
  339. }
  340. /** 发送验证码:真实接口 + 60s 倒计时(Demo 无倒计时,此处按规范补齐防刷) */
  341. protected async sendCode(): Promise<void> {
  342. if (this.sending() || this.countdown() > 0 || this.busy()) return;
  343. this.error.set(null);
  344. if (!this.phoneValid()) {
  345. this.error.set('请输入正确的 11 位手机号');
  346. return;
  347. }
  348. this.sending.set(true);
  349. try {
  350. await this.api.sendMobileCode(this.phone());
  351. this.stage.set('code');
  352. this.startCountdown();
  353. this.focus(this.codeEl());
  354. } catch (e) {
  355. this.error.set(this.messageOf(e));
  356. } finally {
  357. this.sending.set(false);
  358. }
  359. }
  360. protected async submit(): Promise<void> {
  361. if (this.busy()) return;
  362. this.error.set(null);
  363. if (this.stage() === 'code' && this.code().length !== 6) {
  364. this.error.set('请输入 6 位验证码');
  365. return;
  366. }
  367. if (this.stage() === 'token' && !this.token().trim()) {
  368. this.error.set('请输入访问令牌');
  369. return;
  370. }
  371. if (!this.agreed()) {
  372. this.error.set('请先阅读并同意服务协议和隐私政策');
  373. return;
  374. }
  375. this.busy.set(true);
  376. try {
  377. const s =
  378. this.stage() === 'token'
  379. ? await this.api.loginWithToken(this.token().trim())
  380. : await this.api.loginWithMobile(this.phone(), this.code());
  381. this.session.setSession(s.token, s.me);
  382. this.clearTokenFromAddress();
  383. await this.afterLogin();
  384. } catch (e) {
  385. this.error.set(this.messageOf(e));
  386. } finally {
  387. this.busy.set(false);
  388. }
  389. }
  390. /** 协议链接:当前无独立协议页,阻止默认跳转而不伪造内容 */
  391. protected blockLink(e: Event): void {
  392. e.preventDefault();
  393. }
  394. private startCountdown(): void {
  395. this.countdown.set(60);
  396. if (this.codeTimer) clearInterval(this.codeTimer);
  397. this.codeTimer = setInterval(() => {
  398. const next = this.countdown() - 1;
  399. this.countdown.set(next);
  400. if (next <= 0 && this.codeTimer) {
  401. clearInterval(this.codeTimer);
  402. this.codeTimer = null;
  403. }
  404. }, 1000);
  405. }
  406. private focus(el: ElementRef<HTMLInputElement> | undefined): void {
  407. // 等下一帧再聚焦:当前 DOM 可能刚因 stage 切换重建
  408. setTimeout(() => el?.nativeElement.focus(), 0);
  409. }
  410. /** 已登录直接进入(地址带 token 时仍走 initFromUrl,可能要换身份) */
  411. private redirectIfLoggedIn(): boolean {
  412. const urlToken = this.route.snapshot.queryParamMap.get('token');
  413. if (this.session.isLoggedIn() && !urlToken) {
  414. void this.afterLogin();
  415. return true;
  416. }
  417. return false;
  418. }
  419. /** AC-02.2:`?token=` / `#token=` 自动登录并清地址栏 */
  420. private async initFromUrl(): Promise<void> {
  421. if (this.redirectIfLoggedIn()) return;
  422. const hash = typeof location !== 'undefined' ? location.hash : '';
  423. const query = this.route.snapshot.queryParamMap;
  424. const urlToken = query.get('token') ?? /^#token=(.+)$/.exec(hash)?.[1] ?? '';
  425. if (!urlToken) return;
  426. this.busy.set(true);
  427. this.agreed.set(true);
  428. try {
  429. const s = await this.api.loginWithToken(decodeURIComponent(urlToken));
  430. this.session.setSession(s.token, s.me);
  431. this.clearTokenFromAddress();
  432. await this.afterLogin();
  433. } catch (e) {
  434. this.error.set(this.messageOf(e));
  435. } finally {
  436. this.busy.set(false);
  437. }
  438. }
  439. private clearTokenFromAddress(): void {
  440. if (typeof history === 'undefined') return;
  441. const url = new URL(location.href);
  442. url.hash = '';
  443. url.searchParams.delete('token');
  444. history.replaceState({}, '', url.toString());
  445. }
  446. /** AC-02.3:按 redirect 回跳,且 replaceUrl */
  447. private async afterLogin(): Promise<void> {
  448. const redirect = this.route.snapshot.queryParamMap.get('redirect');
  449. const target = redirect && redirect.startsWith('/') ? redirect : '/mobile/messages';
  450. await this.router.navigateByUrl(this.device.normalize(target), { replaceUrl: true });
  451. }
  452. private messageOf(e: unknown): string {
  453. return e instanceof Error && e.message ? e.message : '登录失败,请稍后重试';
  454. }
  455. }