| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616 |
- import {
- ChangeDetectionStrategy,
- Component,
- ElementRef,
- OnDestroy,
- computed,
- inject,
- signal,
- viewChild,
- } from '@angular/core';
- import { ActivatedRoute, Router } from '@angular/router';
- import { FmodeApi } from '../../../core/api/fmode-api';
- import { Me } from '../../../core/api/models';
- import { DeviceService } from '../../../core/device.service';
- import { PaletteService } from '../../../core/palette.service';
- import { SessionService } from '../../../core/session.service';
- import { queryHasOrg } from '../../../core/org.guard';
- type Stage = 'phone' | 'code' | 'token' | 'password';
- /**
- * 移动端登录(Demo 02 + SPEC FR-02)—— **真实接口**
- *
- * 三步两路(与 Demo 一致):
- * 手机号 → 验证码 → 登录;或「使用 Token 直接登录」
- *
- * 与 Demo 的差异(Demo 是静态演示,只校验格式):
- * · 「获取验证码」真实调用 `FmodeApi.sendMobileCode`
- * · 「登录」真实调用 `loginWithMobile` / `loginWithToken`,成功后写 `SessionService`
- * · `?token=` / `#token=` 自动登录并清地址栏(AC-02.2),与桌面登录页同口径
- * · 发送验证码后 60s 倒计时,期间禁点(防重复下发)
- *
- * AC:02.3 redirect 回跳(replaceUrl)· 02.6 明确错误文案 · 02.7 提交期间防并发
- */
- @Component({
- selector: 'app-mb-login-page',
- changeDetection: ChangeDetectionStrategy.OnPush,
- template: `
- <div class="m-login">
- <div class="m-brand">
- <p class="m-wordmark">fmode</p>
- <h1>{{ stage() === 'token' ? 'Token 登录' : '欢迎使用' }}</h1>
- <p class="m-brand-sub">人机共生中枢 · 登录后继续</p>
- </div>
- @switch (stage()) {
- @case ('phone') {
- <label class="m-field">
- <span class="m-prefix">+86</span>
- <input
- #phoneEl
- type="tel"
- inputmode="numeric"
- maxlength="11"
- autocomplete="tel-national"
- placeholder="请输入手机号"
- [value]="phone()"
- aria-label="手机号"
- (input)="onPhone($event)"
- />
- </label>
- <button type="button" class="m-btn m-btn--primary" [disabled]="!phoneValid() || busy()" (click)="sendCode()">
- {{ sending() ? '发送中…' : '获取验证码' }}
- </button>
- <button type="button" class="m-more" (click)="stage.set('password')">使用账号密码登录</button>
- <button type="button" class="m-more" (click)="stage.set('token')">使用 Token 直接登录</button>
- }
- @case ('password') {
- <!--
- 账号密码登录(2026-11-12):康师傅账套 27 个账号主要走这里。
- -->
- <label class="m-field">
- <input
- #userEl
- type="text"
- autocomplete="username"
- placeholder="请输入账号"
- [value]="username()"
- aria-label="账号"
- (input)="onUsername($event)"
- />
- </label>
- <label class="m-field">
- <input
- #pwdEl
- [type]="showPassword() ? 'text' : 'password'"
- autocomplete="current-password"
- placeholder="请输入密码"
- [value]="password()"
- aria-label="密码"
- (input)="onPassword($event)"
- />
- </label>
- <button type="button" class="m-btn m-btn--primary" [disabled]="!passwordStageValid() || busy()" (click)="submitPassword()">
- {{ busy() ? '登录中…' : '登 录' }}
- </button>
- <button type="button" class="m-more" (click)="stage.set('phone')">使用手机验证码登录</button>
- }
- @case ('code') {
- <label class="m-field">
- <span class="m-prefix">+86 {{ maskedPhone() }}</span>
- <input
- #codeEl
- type="tel"
- inputmode="numeric"
- maxlength="6"
- autocomplete="one-time-code"
- placeholder="6 位验证码"
- [value]="code()"
- aria-label="验证码"
- (input)="onCode($event)"
- />
- <button type="button" class="m-get" [disabled]="countdown() > 0 || sending()" (click)="sendCode()">
- {{ countdown() > 0 ? countdown() + 's' : '重新发送' }}
- </button>
- </label>
- <button type="button" class="m-btn m-btn--primary" [disabled]="code().length !== 6 || busy()" (click)="submit()">
- {{ busy() ? '登录中…' : '登录' }}
- </button>
- <button type="button" class="m-more" (click)="backToPhone()">返回修改手机号</button>
- }
- @default {
- <label class="m-field">
- <input
- #tokenEl
- type="text"
- autocomplete="off"
- placeholder="粘贴 r: 开头的访问 Token"
- [value]="token()"
- aria-label="访问 Token"
- (input)="onToken($event)"
- />
- </label>
- <button type="button" class="m-btn m-btn--primary" [disabled]="!token().trim() || busy()" (click)="submit()">
- {{ busy() ? '登录中…' : '登录' }}
- </button>
- <button type="button" class="m-more" (click)="stage.set('phone')">返回手机号登录</button>
- }
- }
- @if (error()) {
- <p class="m-error" role="alert">
- <i class="fa-solid fa-circle-exclamation" aria-hidden="true"></i>
- {{ error() }}
- </p>
- }
- <label class="m-agree">
- <button
- type="button"
- class="m-cb"
- [class.on]="agreed()"
- role="checkbox"
- [attr.aria-checked]="agreed()"
- aria-label="同意协议"
- (click)="agreed.set(!agreed())"
- >
- @if (agreed()) {
- <i class="fa-solid fa-check" aria-hidden="true"></i>
- }
- </button>
- <span>
- 已阅读并同意<a href="#" (click)="blockLink($event)">服务协议</a>和<a href="#" (click)="blockLink($event)">隐私政策</a>
- </span>
- </label>
- </div>
- `,
- styles: [
- `
- :host {
- display: block;
- min-height: 100dvh;
- background: var(--canvas);
- }
- .m-login {
- display: flex;
- flex-direction: column;
- min-height: 100dvh;
- box-sizing: border-box;
- padding: calc(var(--mob-safe-top) + var(--sp-6)) var(--sp-6)
- calc(var(--mob-safe-bottom) + var(--sp-6));
- overflow-y: auto;
- }
- .m-brand {
- display: flex;
- flex: 1;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- text-align: center;
- padding: var(--sp-8) 0 var(--sp-6);
- }
- .m-wordmark {
- margin: 0 0 var(--sp-2);
- color: var(--primary);
- font-size: var(--fs-42);
- font-weight: 700;
- letter-spacing: -0.02em;
- }
- .m-brand h1 {
- margin: var(--sp-3) 0 var(--sp-1);
- color: var(--ink);
- font-size: var(--fs-26);
- }
- .m-brand-sub {
- margin: 0;
- color: var(--muted);
- font-size: var(--fs-13);
- }
- .m-field {
- display: flex;
- align-items: center;
- gap: var(--sp-2);
- height: 52px;
- margin-bottom: var(--sp-3);
- padding: 0 var(--sp-4);
- box-sizing: border-box;
- border: 1px solid var(--edge);
- border-radius: var(--r-md);
- background: var(--surface);
- }
- .m-field input {
- flex: 1;
- min-width: 0;
- border: 0;
- outline: 0;
- background: transparent;
- color: var(--ink);
- font-size: var(--fs-17);
- }
- .m-prefix {
- flex: none;
- color: var(--ink-2);
- font-size: var(--fs-15);
- }
- .m-get {
- flex: none;
- border: 0;
- background: none;
- color: var(--primary);
- font: inherit;
- font-size: var(--fs-13);
- font-weight: 600;
- white-space: nowrap;
- cursor: pointer;
- }
- .m-get:disabled {
- color: var(--muted);
- cursor: not-allowed;
- }
- .m-btn {
- width: 100%;
- height: 52px;
- margin-bottom: var(--sp-3);
- border: 0;
- border-radius: var(--r-md);
- font: inherit;
- font-size: var(--fs-17);
- font-weight: 600;
- cursor: pointer;
- }
- .m-btn--primary {
- background: var(--primary);
- color: var(--primary-content);
- }
- .m-btn:disabled {
- opacity: 0.5;
- cursor: not-allowed;
- }
- .m-more {
- padding: var(--sp-3) 0;
- border: 0;
- background: none;
- color: var(--primary);
- font: inherit;
- font-size: var(--fs-13);
- cursor: pointer;
- }
- .m-error {
- display: flex;
- align-items: center;
- gap: var(--sp-2);
- margin: 0 0 var(--sp-3);
- padding: var(--sp-3);
- border-radius: var(--r-md);
- background: var(--danger-subtle);
- color: var(--danger);
- font-size: var(--fs-13);
- }
- .m-agree {
- display: flex;
- align-items: flex-start;
- justify-content: center;
- gap: var(--sp-2);
- margin-top: var(--sp-4);
- color: var(--muted);
- font-size: var(--fs-12);
- text-align: left;
- }
- .m-agree a {
- color: var(--primary);
- text-decoration: none;
- }
- .m-cb {
- display: grid;
- place-items: center;
- flex: none;
- width: 16px;
- height: 16px;
- margin-top: 2px;
- padding: 0;
- border: 1.5px solid var(--edge-strong);
- border-radius: var(--r-tag);
- background: none;
- color: var(--primary-content);
- font-size: var(--fs-9);
- cursor: pointer;
- }
- .m-cb.on {
- border-color: var(--primary);
- background: var(--primary);
- }
- `,
- ],
- })
- export class MbLoginPage implements OnDestroy {
- private readonly api = inject(FmodeApi);
- private readonly session = inject(SessionService);
- private readonly device = inject(DeviceService);
- private readonly palette = inject(PaletteService);
- private readonly router = inject(Router);
- private readonly route = inject(ActivatedRoute);
- protected readonly stage = signal<Stage>('phone');
- protected readonly phone = signal('');
- protected readonly username = signal('');
- protected readonly password = signal('');
- protected readonly showPassword = signal(false);
- protected readonly code = signal('');
- protected readonly token = signal('');
- protected readonly agreed = signal(false);
- protected readonly error = signal<string | null>(null);
- protected readonly busy = signal(false);
- protected readonly sending = signal(false);
- protected readonly countdown = signal(0);
- protected readonly phoneValid = computed(() => /^1\d{10}$/.test(this.phone()));
- /** 账号密码页的提交条件(2026-11-12) */
- protected readonly passwordStageValid = computed(
- () => this.username().trim().length > 0 && this.password().length > 0,
- );
- protected readonly maskedPhone = computed(() => {
- const p = this.phone();
- return `${p.slice(0, 3)}****${p.slice(7)}`;
- });
- private readonly phoneEl = viewChild<ElementRef<HTMLInputElement>>('phoneEl');
- private readonly codeEl = viewChild<ElementRef<HTMLInputElement>>('codeEl');
- private codeTimer: ReturnType<typeof setInterval> | null = null;
- constructor() {
- this.palette.init();
- void this.initFromUrl();
- }
- ngOnDestroy(): void {
- if (this.codeTimer) clearInterval(this.codeTimer);
- }
- protected onPhone(e: Event): void {
- const v = (e.target as HTMLInputElement).value.replace(/\D/g, '').slice(0, 11);
- this.phone.set(v);
- (e.target as HTMLInputElement).value = v;
- this.error.set(null);
- }
- protected onCode(e: Event): void {
- const v = (e.target as HTMLInputElement).value.replace(/\D/g, '').slice(0, 6);
- this.code.set(v);
- (e.target as HTMLInputElement).value = v;
- this.error.set(null);
- }
- protected onToken(e: Event): void {
- this.token.set((e.target as HTMLInputElement).value);
- this.error.set(null);
- }
- protected backToPhone(): void {
- this.stage.set('phone');
- this.code.set('');
- this.error.set(null);
- /*
- * 🔴 返回手机号页时**停掉倒计时**(2026-11-18 用户实测 bug)。
- *
- * ## 现象
- *
- * 发完验证码 → 点「返回修改手机号」→ 再点「获取验证码」→ **没有任何反应**。
- *
- * ## 根因
- *
- * 这里没停倒计时,`countdown` 还在往下跑;而手机号页的按钮只判
- * `!phoneValid() || busy()`,看起来是**可点的**。
- * 点下去 `sendCode()` 第一行 `countdown() > 0` 直接 return、**不给任何提示** ——
- * 用户看到的就是「点了没反应」。
- *
- * ## 修法
- *
- * 返回即视为「放弃这次验证码」:停掉定时器、清零倒计时。
- * 用户重新点发送时是完整的新一轮,不会再被上一轮挡住。
- */
- this.stopCountdown();
- this.focus(this.phoneEl());
- }
- /** 停止倒计时并清零(返回 / 卸载 / 重发时调用) */
- private stopCountdown(): void {
- if (this.codeTimer) {
- clearInterval(this.codeTimer);
- this.codeTimer = null;
- }
- this.countdown.set(0);
- }
- /** 发送验证码:真实接口 + 60s 倒计时(Demo 无倒计时,此处按规范补齐防刷) */
- protected async sendCode(): Promise<void> {
- /*
- * 🔴 倒计时未结束时给出**明确提示**,不再静默返回(2026-11-18 用户实测)。
- *
- * 原来这里直接 `return` —— 用户点了按钮什么都没发生,
- * 分不清「是没点中」「是坏了」还是「在等冷却」。
- * 现在告诉他还剩几秒。
- */
- if (this.countdown() > 0) {
- this.error.set(`请等待 ${this.countdown()} 秒后再试`);
- return;
- }
- if (this.sending() || this.busy()) return;
- this.error.set(null);
- if (!this.phoneValid()) {
- this.error.set('请输入正确的 11 位手机号');
- return;
- }
- /*
- * 🔴 获取验证码前必须先勾选协议(2026-11-13 用户反馈)。
- *
- * 原先只有 `submit()` 检查,`sendCode()` 完全没管 ——
- * 用户不勾协议也能把验证码发出去,到了登录那步才被拦,
- * 体验上是「先给了希望再拒绝」。现在前置到发送前。
- */
- if (!this.agreed()) {
- this.error.set('请先阅读并同意《服务协议》和《隐私政策》');
- return;
- }
- this.sending.set(true);
- try {
- await this.api.sendMobileCode(this.phone());
- this.stage.set('code');
- this.startCountdown();
- this.focus(this.codeEl());
- } catch (e) {
- this.error.set(this.messageOf(e));
- } finally {
- this.sending.set(false);
- }
- }
- protected async submit(): Promise<void> {
- if (this.busy()) return;
- this.error.set(null);
- if (this.stage() === 'code' && this.code().length !== 6) {
- this.error.set('请输入 6 位验证码');
- return;
- }
- if (this.stage() === 'token' && !this.token().trim()) {
- this.error.set('请输入访问令牌');
- return;
- }
- if (!this.agreed()) {
- this.error.set('请先阅读并同意服务协议和隐私政策');
- return;
- }
- this.busy.set(true);
- try {
- const s =
- this.stage() === 'token'
- ? await this.api.loginWithToken(this.token().trim())
- : this.stage() === 'password'
- ? await this.api.loginWithPassword(this.username(), this.password())
- : await this.api.loginWithMobile(this.phone(), this.code());
- await this.persistSession(s.token, s.me);
- this.clearTokenFromAddress();
- await this.afterLogin();
- } catch (e) {
- this.error.set(this.messageOf(e));
- } finally {
- this.busy.set(false);
- }
- }
- /** 账号密码页独立提交(协议勾选约束与手机号页一致) */
- protected async submitPassword(): Promise<void> {
- if (this.busy()) return;
- this.error.set(null);
- if (!this.passwordStageValid()) {
- this.error.set('请输入账号和密码');
- return;
- }
- if (!this.agreed()) {
- this.error.set('请先阅读并同意服务协议和隐私政策');
- return;
- }
- await this.submit();
- }
- protected onUsername(e: Event): void {
- this.username.set((e.target as HTMLInputElement).value.trim());
- this.error.set(null);
- }
- protected onPassword(e: Event): void {
- this.password.set((e.target as HTMLInputElement).value);
- this.error.set(null);
- }
- /**
- * 写入登录态并补取 session 过期时间(2026-11-12)。
- * 取不到不阻断登录(退化为「不过期」)。
- */
- private async persistSession(token: string, me: Me): Promise<void> {
- this.session.setSession(token, me);
- const expiresAt = await this.api.fetchSessionExpiry(token).catch(() => null);
- if (expiresAt) this.session.setExpiresAt(expiresAt);
- }
- /** 协议链接:当前无独立协议页,阻止默认跳转而不伪造内容 */
- protected blockLink(e: Event): void {
- e.preventDefault();
- }
- private startCountdown(): void {
- this.countdown.set(60);
- if (this.codeTimer) clearInterval(this.codeTimer);
- this.codeTimer = setInterval(() => {
- const next = this.countdown() - 1;
- this.countdown.set(next);
- if (next <= 0 && this.codeTimer) {
- clearInterval(this.codeTimer);
- this.codeTimer = null;
- }
- }, 1000);
- }
- private focus(el: ElementRef<HTMLInputElement> | undefined): void {
- // 等下一帧再聚焦:当前 DOM 可能刚因 stage 切换重建
- setTimeout(() => el?.nativeElement.focus(), 0);
- }
- /** 已登录直接进入(地址带 token 时仍走 initFromUrl,可能要换身份) */
- private redirectIfLoggedIn(): boolean {
- const urlToken = this.route.snapshot.queryParamMap.get('token');
- if (this.session.isLoggedIn() && !urlToken) {
- void this.afterLogin();
- return true;
- }
- return false;
- }
- /** AC-02.2:`?token=` / `#token=` 自动登录并清地址栏 */
- private async initFromUrl(): Promise<void> {
- if (this.redirectIfLoggedIn()) return;
- const hash = typeof location !== 'undefined' ? location.hash : '';
- const query = this.route.snapshot.queryParamMap;
- const urlToken = query.get('token') ?? /^#token=(.+)$/.exec(hash)?.[1] ?? '';
- if (!urlToken) return;
- this.busy.set(true);
- this.agreed.set(true);
- try {
- const s = await this.api.loginWithToken(decodeURIComponent(urlToken));
- this.session.setSession(s.token, s.me);
- this.clearTokenFromAddress();
- await this.afterLogin();
- } catch (e) {
- this.error.set(this.messageOf(e));
- } finally {
- this.busy.set(false);
- }
- }
- private clearTokenFromAddress(): void {
- if (typeof history === 'undefined') return;
- const url = new URL(location.href);
- url.hash = '';
- url.searchParams.delete('token');
- history.replaceState({}, '', url.toString());
- }
- /** AC-02.3:按 redirect 回跳,且 replaceUrl */
- private async afterLogin(): Promise<void> {
- // 无组织用户先停在等待页(2026-11-10,与 orgGuard 同源判定)
- if (!(await queryHasOrg(this.api))) {
- await this.router.navigateByUrl('/pending', { replaceUrl: true });
- return;
- }
- const redirect = this.route.snapshot.queryParamMap.get('redirect');
- const target = redirect && redirect.startsWith('/') ? redirect : '/mobile/messages';
- await this.router.navigateByUrl(this.device.normalize(target), { replaceUrl: true });
- }
- private messageOf(e: unknown): string {
- return e instanceof Error && e.message ? e.message : '登录失败,请稍后重试';
- }
- }
|