login.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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 { Me } from '../../../core/api/models';
  14. import { DeviceService } from '../../../core/device.service';
  15. import { PaletteService } from '../../../core/palette.service';
  16. import { SessionService } from '../../../core/session.service';
  17. import { queryHasOrg } from '../../../core/org.guard';
  18. type Stage = 'phone' | 'code' | 'token' | 'password';
  19. /**
  20. * 移动端登录(Demo 02 + SPEC FR-02)—— **真实接口**
  21. *
  22. * 三步两路(与 Demo 一致):
  23. * 手机号 → 验证码 → 登录;或「使用 Token 直接登录」
  24. *
  25. * 与 Demo 的差异(Demo 是静态演示,只校验格式):
  26. * · 「获取验证码」真实调用 `FmodeApi.sendMobileCode`
  27. * · 「登录」真实调用 `loginWithMobile` / `loginWithToken`,成功后写 `SessionService`
  28. * · `?token=` / `#token=` 自动登录并清地址栏(AC-02.2),与桌面登录页同口径
  29. * · 发送验证码后 60s 倒计时,期间禁点(防重复下发)
  30. *
  31. * AC:02.3 redirect 回跳(replaceUrl)· 02.6 明确错误文案 · 02.7 提交期间防并发
  32. */
  33. @Component({
  34. selector: 'app-mb-login-page',
  35. changeDetection: ChangeDetectionStrategy.OnPush,
  36. template: `
  37. <div class="m-login">
  38. <div class="m-brand">
  39. <p class="m-wordmark">fmode</p>
  40. <h1>{{ stage() === 'token' ? 'Token 登录' : '欢迎使用' }}</h1>
  41. <p class="m-brand-sub">人机共生中枢 · 登录后继续</p>
  42. </div>
  43. @switch (stage()) {
  44. @case ('phone') {
  45. <label class="m-field">
  46. <span class="m-prefix">+86</span>
  47. <input
  48. #phoneEl
  49. type="tel"
  50. inputmode="numeric"
  51. maxlength="11"
  52. autocomplete="tel-national"
  53. placeholder="请输入手机号"
  54. [value]="phone()"
  55. aria-label="手机号"
  56. (input)="onPhone($event)"
  57. />
  58. </label>
  59. <button type="button" class="m-btn m-btn--primary" [disabled]="!phoneValid() || busy()" (click)="sendCode()">
  60. {{ sending() ? '发送中…' : '获取验证码' }}
  61. </button>
  62. <button type="button" class="m-more" (click)="stage.set('password')">使用账号密码登录</button>
  63. <button type="button" class="m-more" (click)="stage.set('token')">使用 Token 直接登录</button>
  64. }
  65. @case ('password') {
  66. <!--
  67. 账号密码登录(2026-11-12):康师傅账套 27 个账号主要走这里。
  68. -->
  69. <label class="m-field">
  70. <input
  71. #userEl
  72. type="text"
  73. autocomplete="username"
  74. placeholder="请输入账号"
  75. [value]="username()"
  76. aria-label="账号"
  77. (input)="onUsername($event)"
  78. />
  79. </label>
  80. <label class="m-field">
  81. <input
  82. #pwdEl
  83. [type]="showPassword() ? 'text' : 'password'"
  84. autocomplete="current-password"
  85. placeholder="请输入密码"
  86. [value]="password()"
  87. aria-label="密码"
  88. (input)="onPassword($event)"
  89. />
  90. </label>
  91. <button type="button" class="m-btn m-btn--primary" [disabled]="!passwordStageValid() || busy()" (click)="submitPassword()">
  92. {{ busy() ? '登录中…' : '登 录' }}
  93. </button>
  94. <button type="button" class="m-more" (click)="stage.set('phone')">使用手机验证码登录</button>
  95. }
  96. @case ('code') {
  97. <label class="m-field">
  98. <span class="m-prefix">+86 {{ maskedPhone() }}</span>
  99. <input
  100. #codeEl
  101. type="tel"
  102. inputmode="numeric"
  103. maxlength="6"
  104. autocomplete="one-time-code"
  105. placeholder="6 位验证码"
  106. [value]="code()"
  107. aria-label="验证码"
  108. (input)="onCode($event)"
  109. />
  110. <button type="button" class="m-get" [disabled]="countdown() > 0 || sending()" (click)="sendCode()">
  111. {{ countdown() > 0 ? countdown() + 's' : '重新发送' }}
  112. </button>
  113. </label>
  114. <button type="button" class="m-btn m-btn--primary" [disabled]="code().length !== 6 || busy()" (click)="submit()">
  115. {{ busy() ? '登录中…' : '登录' }}
  116. </button>
  117. <button type="button" class="m-more" (click)="backToPhone()">返回修改手机号</button>
  118. }
  119. @default {
  120. <label class="m-field">
  121. <input
  122. #tokenEl
  123. type="text"
  124. autocomplete="off"
  125. placeholder="粘贴 r: 开头的访问 Token"
  126. [value]="token()"
  127. aria-label="访问 Token"
  128. (input)="onToken($event)"
  129. />
  130. </label>
  131. <button type="button" class="m-btn m-btn--primary" [disabled]="!token().trim() || busy()" (click)="submit()">
  132. {{ busy() ? '登录中…' : '登录' }}
  133. </button>
  134. <button type="button" class="m-more" (click)="stage.set('phone')">返回手机号登录</button>
  135. }
  136. }
  137. @if (error()) {
  138. <p class="m-error" role="alert">
  139. <i class="fa-solid fa-circle-exclamation" aria-hidden="true"></i>
  140. {{ error() }}
  141. </p>
  142. }
  143. <label class="m-agree">
  144. <button
  145. type="button"
  146. class="m-cb"
  147. [class.on]="agreed()"
  148. role="checkbox"
  149. [attr.aria-checked]="agreed()"
  150. aria-label="同意协议"
  151. (click)="agreed.set(!agreed())"
  152. >
  153. @if (agreed()) {
  154. <i class="fa-solid fa-check" aria-hidden="true"></i>
  155. }
  156. </button>
  157. <span>
  158. 已阅读并同意<a href="#" (click)="blockLink($event)">服务协议</a>和<a href="#" (click)="blockLink($event)">隐私政策</a>
  159. </span>
  160. </label>
  161. </div>
  162. `,
  163. styles: [
  164. `
  165. :host {
  166. display: block;
  167. min-height: 100dvh;
  168. background: var(--canvas);
  169. }
  170. .m-login {
  171. display: flex;
  172. flex-direction: column;
  173. min-height: 100dvh;
  174. box-sizing: border-box;
  175. padding: calc(var(--mob-safe-top) + var(--sp-6)) var(--sp-6)
  176. calc(var(--mob-safe-bottom) + var(--sp-6));
  177. overflow-y: auto;
  178. }
  179. .m-brand {
  180. display: flex;
  181. flex: 1;
  182. flex-direction: column;
  183. align-items: center;
  184. justify-content: center;
  185. text-align: center;
  186. padding: var(--sp-8) 0 var(--sp-6);
  187. }
  188. .m-wordmark {
  189. margin: 0 0 var(--sp-2);
  190. color: var(--primary);
  191. font-size: var(--fs-42);
  192. font-weight: 700;
  193. letter-spacing: -0.02em;
  194. }
  195. .m-brand h1 {
  196. margin: var(--sp-3) 0 var(--sp-1);
  197. color: var(--ink);
  198. font-size: var(--fs-26);
  199. }
  200. .m-brand-sub {
  201. margin: 0;
  202. color: var(--muted);
  203. font-size: var(--fs-13);
  204. }
  205. .m-field {
  206. display: flex;
  207. align-items: center;
  208. gap: var(--sp-2);
  209. height: 52px;
  210. margin-bottom: var(--sp-3);
  211. padding: 0 var(--sp-4);
  212. box-sizing: border-box;
  213. border: 1px solid var(--edge);
  214. border-radius: var(--r-md);
  215. background: var(--surface);
  216. }
  217. .m-field input {
  218. flex: 1;
  219. min-width: 0;
  220. border: 0;
  221. outline: 0;
  222. background: transparent;
  223. color: var(--ink);
  224. font-size: var(--fs-17);
  225. }
  226. .m-prefix {
  227. flex: none;
  228. color: var(--ink-2);
  229. font-size: var(--fs-15);
  230. }
  231. .m-get {
  232. flex: none;
  233. border: 0;
  234. background: none;
  235. color: var(--primary);
  236. font: inherit;
  237. font-size: var(--fs-13);
  238. font-weight: 600;
  239. white-space: nowrap;
  240. cursor: pointer;
  241. }
  242. .m-get:disabled {
  243. color: var(--muted);
  244. cursor: not-allowed;
  245. }
  246. .m-btn {
  247. width: 100%;
  248. height: 52px;
  249. margin-bottom: var(--sp-3);
  250. border: 0;
  251. border-radius: var(--r-md);
  252. font: inherit;
  253. font-size: var(--fs-17);
  254. font-weight: 600;
  255. cursor: pointer;
  256. }
  257. .m-btn--primary {
  258. background: var(--primary);
  259. color: var(--primary-content);
  260. }
  261. .m-btn:disabled {
  262. opacity: 0.5;
  263. cursor: not-allowed;
  264. }
  265. .m-more {
  266. padding: var(--sp-3) 0;
  267. border: 0;
  268. background: none;
  269. color: var(--primary);
  270. font: inherit;
  271. font-size: var(--fs-13);
  272. cursor: pointer;
  273. }
  274. .m-error {
  275. display: flex;
  276. align-items: center;
  277. gap: var(--sp-2);
  278. margin: 0 0 var(--sp-3);
  279. padding: var(--sp-3);
  280. border-radius: var(--r-md);
  281. background: var(--danger-subtle);
  282. color: var(--danger);
  283. font-size: var(--fs-13);
  284. }
  285. .m-agree {
  286. display: flex;
  287. align-items: flex-start;
  288. justify-content: center;
  289. gap: var(--sp-2);
  290. margin-top: var(--sp-4);
  291. color: var(--muted);
  292. font-size: var(--fs-12);
  293. text-align: left;
  294. }
  295. .m-agree a {
  296. color: var(--primary);
  297. text-decoration: none;
  298. }
  299. .m-cb {
  300. display: grid;
  301. place-items: center;
  302. flex: none;
  303. width: 16px;
  304. height: 16px;
  305. margin-top: 2px;
  306. padding: 0;
  307. border: 1.5px solid var(--edge-strong);
  308. border-radius: var(--r-tag);
  309. background: none;
  310. color: var(--primary-content);
  311. font-size: var(--fs-9);
  312. cursor: pointer;
  313. }
  314. .m-cb.on {
  315. border-color: var(--primary);
  316. background: var(--primary);
  317. }
  318. `,
  319. ],
  320. })
  321. export class MbLoginPage implements OnDestroy {
  322. private readonly api = inject(FmodeApi);
  323. private readonly session = inject(SessionService);
  324. private readonly device = inject(DeviceService);
  325. private readonly palette = inject(PaletteService);
  326. private readonly router = inject(Router);
  327. private readonly route = inject(ActivatedRoute);
  328. protected readonly stage = signal<Stage>('phone');
  329. protected readonly phone = signal('');
  330. protected readonly username = signal('');
  331. protected readonly password = signal('');
  332. protected readonly showPassword = signal(false);
  333. protected readonly code = signal('');
  334. protected readonly token = signal('');
  335. protected readonly agreed = signal(false);
  336. protected readonly error = signal<string | null>(null);
  337. protected readonly busy = signal(false);
  338. protected readonly sending = signal(false);
  339. protected readonly countdown = signal(0);
  340. protected readonly phoneValid = computed(() => /^1\d{10}$/.test(this.phone()));
  341. /** 账号密码页的提交条件(2026-11-12) */
  342. protected readonly passwordStageValid = computed(
  343. () => this.username().trim().length > 0 && this.password().length > 0,
  344. );
  345. protected readonly maskedPhone = computed(() => {
  346. const p = this.phone();
  347. return `${p.slice(0, 3)}****${p.slice(7)}`;
  348. });
  349. private readonly phoneEl = viewChild<ElementRef<HTMLInputElement>>('phoneEl');
  350. private readonly codeEl = viewChild<ElementRef<HTMLInputElement>>('codeEl');
  351. private codeTimer: ReturnType<typeof setInterval> | null = null;
  352. constructor() {
  353. this.palette.init();
  354. void this.initFromUrl();
  355. }
  356. ngOnDestroy(): void {
  357. if (this.codeTimer) clearInterval(this.codeTimer);
  358. }
  359. protected onPhone(e: Event): void {
  360. const v = (e.target as HTMLInputElement).value.replace(/\D/g, '').slice(0, 11);
  361. this.phone.set(v);
  362. (e.target as HTMLInputElement).value = v;
  363. this.error.set(null);
  364. }
  365. protected onCode(e: Event): void {
  366. const v = (e.target as HTMLInputElement).value.replace(/\D/g, '').slice(0, 6);
  367. this.code.set(v);
  368. (e.target as HTMLInputElement).value = v;
  369. this.error.set(null);
  370. }
  371. protected onToken(e: Event): void {
  372. this.token.set((e.target as HTMLInputElement).value);
  373. this.error.set(null);
  374. }
  375. protected backToPhone(): void {
  376. this.stage.set('phone');
  377. this.code.set('');
  378. this.error.set(null);
  379. /*
  380. * 🔴 返回手机号页时**停掉倒计时**(2026-11-18 用户实测 bug)。
  381. *
  382. * ## 现象
  383. *
  384. * 发完验证码 → 点「返回修改手机号」→ 再点「获取验证码」→ **没有任何反应**。
  385. *
  386. * ## 根因
  387. *
  388. * 这里没停倒计时,`countdown` 还在往下跑;而手机号页的按钮只判
  389. * `!phoneValid() || busy()`,看起来是**可点的**。
  390. * 点下去 `sendCode()` 第一行 `countdown() > 0` 直接 return、**不给任何提示** ——
  391. * 用户看到的就是「点了没反应」。
  392. *
  393. * ## 修法
  394. *
  395. * 返回即视为「放弃这次验证码」:停掉定时器、清零倒计时。
  396. * 用户重新点发送时是完整的新一轮,不会再被上一轮挡住。
  397. */
  398. this.stopCountdown();
  399. this.focus(this.phoneEl());
  400. }
  401. /** 停止倒计时并清零(返回 / 卸载 / 重发时调用) */
  402. private stopCountdown(): void {
  403. if (this.codeTimer) {
  404. clearInterval(this.codeTimer);
  405. this.codeTimer = null;
  406. }
  407. this.countdown.set(0);
  408. }
  409. /** 发送验证码:真实接口 + 60s 倒计时(Demo 无倒计时,此处按规范补齐防刷) */
  410. protected async sendCode(): Promise<void> {
  411. /*
  412. * 🔴 倒计时未结束时给出**明确提示**,不再静默返回(2026-11-18 用户实测)。
  413. *
  414. * 原来这里直接 `return` —— 用户点了按钮什么都没发生,
  415. * 分不清「是没点中」「是坏了」还是「在等冷却」。
  416. * 现在告诉他还剩几秒。
  417. */
  418. if (this.countdown() > 0) {
  419. this.error.set(`请等待 ${this.countdown()} 秒后再试`);
  420. return;
  421. }
  422. if (this.sending() || this.busy()) return;
  423. this.error.set(null);
  424. if (!this.phoneValid()) {
  425. this.error.set('请输入正确的 11 位手机号');
  426. return;
  427. }
  428. /*
  429. * 🔴 获取验证码前必须先勾选协议(2026-11-13 用户反馈)。
  430. *
  431. * 原先只有 `submit()` 检查,`sendCode()` 完全没管 ——
  432. * 用户不勾协议也能把验证码发出去,到了登录那步才被拦,
  433. * 体验上是「先给了希望再拒绝」。现在前置到发送前。
  434. */
  435. if (!this.agreed()) {
  436. this.error.set('请先阅读并同意《服务协议》和《隐私政策》');
  437. return;
  438. }
  439. this.sending.set(true);
  440. try {
  441. await this.api.sendMobileCode(this.phone());
  442. this.stage.set('code');
  443. this.startCountdown();
  444. this.focus(this.codeEl());
  445. } catch (e) {
  446. this.error.set(this.messageOf(e));
  447. } finally {
  448. this.sending.set(false);
  449. }
  450. }
  451. protected async submit(): Promise<void> {
  452. if (this.busy()) return;
  453. this.error.set(null);
  454. if (this.stage() === 'code' && this.code().length !== 6) {
  455. this.error.set('请输入 6 位验证码');
  456. return;
  457. }
  458. if (this.stage() === 'token' && !this.token().trim()) {
  459. this.error.set('请输入访问令牌');
  460. return;
  461. }
  462. if (!this.agreed()) {
  463. this.error.set('请先阅读并同意服务协议和隐私政策');
  464. return;
  465. }
  466. this.busy.set(true);
  467. try {
  468. const s =
  469. this.stage() === 'token'
  470. ? await this.api.loginWithToken(this.token().trim())
  471. : this.stage() === 'password'
  472. ? await this.api.loginWithPassword(this.username(), this.password())
  473. : await this.api.loginWithMobile(this.phone(), this.code());
  474. await this.persistSession(s.token, s.me);
  475. this.clearTokenFromAddress();
  476. await this.afterLogin();
  477. } catch (e) {
  478. this.error.set(this.messageOf(e));
  479. } finally {
  480. this.busy.set(false);
  481. }
  482. }
  483. /** 账号密码页独立提交(协议勾选约束与手机号页一致) */
  484. protected async submitPassword(): Promise<void> {
  485. if (this.busy()) return;
  486. this.error.set(null);
  487. if (!this.passwordStageValid()) {
  488. this.error.set('请输入账号和密码');
  489. return;
  490. }
  491. if (!this.agreed()) {
  492. this.error.set('请先阅读并同意服务协议和隐私政策');
  493. return;
  494. }
  495. await this.submit();
  496. }
  497. protected onUsername(e: Event): void {
  498. this.username.set((e.target as HTMLInputElement).value.trim());
  499. this.error.set(null);
  500. }
  501. protected onPassword(e: Event): void {
  502. this.password.set((e.target as HTMLInputElement).value);
  503. this.error.set(null);
  504. }
  505. /**
  506. * 写入登录态并补取 session 过期时间(2026-11-12)。
  507. * 取不到不阻断登录(退化为「不过期」)。
  508. */
  509. private async persistSession(token: string, me: Me): Promise<void> {
  510. this.session.setSession(token, me);
  511. const expiresAt = await this.api.fetchSessionExpiry(token).catch(() => null);
  512. if (expiresAt) this.session.setExpiresAt(expiresAt);
  513. }
  514. /** 协议链接:当前无独立协议页,阻止默认跳转而不伪造内容 */
  515. protected blockLink(e: Event): void {
  516. e.preventDefault();
  517. }
  518. private startCountdown(): void {
  519. this.countdown.set(60);
  520. if (this.codeTimer) clearInterval(this.codeTimer);
  521. this.codeTimer = setInterval(() => {
  522. const next = this.countdown() - 1;
  523. this.countdown.set(next);
  524. if (next <= 0 && this.codeTimer) {
  525. clearInterval(this.codeTimer);
  526. this.codeTimer = null;
  527. }
  528. }, 1000);
  529. }
  530. private focus(el: ElementRef<HTMLInputElement> | undefined): void {
  531. // 等下一帧再聚焦:当前 DOM 可能刚因 stage 切换重建
  532. setTimeout(() => el?.nativeElement.focus(), 0);
  533. }
  534. /** 已登录直接进入(地址带 token 时仍走 initFromUrl,可能要换身份) */
  535. private redirectIfLoggedIn(): boolean {
  536. const urlToken = this.route.snapshot.queryParamMap.get('token');
  537. if (this.session.isLoggedIn() && !urlToken) {
  538. void this.afterLogin();
  539. return true;
  540. }
  541. return false;
  542. }
  543. /** AC-02.2:`?token=` / `#token=` 自动登录并清地址栏 */
  544. private async initFromUrl(): Promise<void> {
  545. if (this.redirectIfLoggedIn()) return;
  546. const hash = typeof location !== 'undefined' ? location.hash : '';
  547. const query = this.route.snapshot.queryParamMap;
  548. const urlToken = query.get('token') ?? /^#token=(.+)$/.exec(hash)?.[1] ?? '';
  549. if (!urlToken) return;
  550. this.busy.set(true);
  551. this.agreed.set(true);
  552. try {
  553. const s = await this.api.loginWithToken(decodeURIComponent(urlToken));
  554. this.session.setSession(s.token, s.me);
  555. this.clearTokenFromAddress();
  556. await this.afterLogin();
  557. } catch (e) {
  558. this.error.set(this.messageOf(e));
  559. } finally {
  560. this.busy.set(false);
  561. }
  562. }
  563. private clearTokenFromAddress(): void {
  564. if (typeof history === 'undefined') return;
  565. const url = new URL(location.href);
  566. url.hash = '';
  567. url.searchParams.delete('token');
  568. history.replaceState({}, '', url.toString());
  569. }
  570. /** AC-02.3:按 redirect 回跳,且 replaceUrl */
  571. private async afterLogin(): Promise<void> {
  572. // 无组织用户先停在等待页(2026-11-10,与 orgGuard 同源判定)
  573. if (!(await queryHasOrg(this.api))) {
  574. await this.router.navigateByUrl('/pending', { replaceUrl: true });
  575. return;
  576. }
  577. const redirect = this.route.snapshot.queryParamMap.get('redirect');
  578. const target = redirect && redirect.startsWith('/') ? redirect : '/mobile/messages';
  579. await this.router.navigateByUrl(this.device.normalize(target), { replaceUrl: true });
  580. }
  581. private messageOf(e: unknown): string {
  582. return e instanceof Error && e.message ? e.message : '登录失败,请稍后重试';
  583. }
  584. }