Преглед на файлове

Preserve fresh admin sessions after password changes

彭峰 преди 13 часа
родител
ревизия
fae79e2496

+ 8 - 1
projects/xiaoshu-admin/src/app/admin-session.service.spec.ts

@@ -63,6 +63,13 @@ describe('AdminSessionService', () => {
     expect(JSON.parse(localStorage.getItem(ADMIN_SESSION_KEY)!).sessionToken).toBe('legacy');
   });
 
+  it('does not restore a stale tab session after another tab logged out', () => {
+    localStorage.setItem(ADMIN_SESSION_KEY, 'null');
+    sessionStorage.setItem(ADMIN_SESSION_KEY, JSON.stringify({ objectId: 'admin-1', sessionToken: 'old' }));
+    expect(TestBed.inject(AdminSessionService).session()).toBeNull();
+    expect(sessionStorage.getItem(ADMIN_SESSION_KEY)).toBeNull();
+  });
+
   it('ignores failure from an older session and never revokes the new one', () => {
     localStorage.setItem(ADMIN_SESSION_KEY, JSON.stringify({objectId:'admin-1',sessionToken:'new'}));
     const service=TestBed.inject(AdminSessionService);
@@ -76,7 +83,7 @@ describe('AdminSessionService', () => {
     localStorage.setItem(ADMIN_SESSION_KEY, JSON.stringify({objectId:'admin-1',sessionToken:'expired'}));
     const service=TestBed.inject(AdminSessionService);
     service.invalidateSession('expired');service.invalidateSession('expired');
-    expect(service.session()).toBeNull();expect(localStorage.getItem(ADMIN_SESSION_KEY)).toBeNull();
+    expect(service.session()).toBeNull();expect(localStorage.getItem(ADMIN_SESSION_KEY)).toBe('null');
     expect(sessionStorage.getItem(ADMIN_SESSION_KEY)).toBeNull();expect(router.navigate).toHaveBeenCalledTimes(1);
     http.expectNone(`${CLOUD_FUNCTION_BASE_URL}/xiaoshu/admin/gateway`);
   });

+ 40 - 28
projects/xiaoshu-admin/src/app/admin-session.service.ts

@@ -1,7 +1,7 @@
 import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
 import { computed, DestroyRef, inject, Injectable, signal } from '@angular/core';
 import { Router } from '@angular/router';
-import { firstValueFrom, timeout } from 'rxjs';
+import { catchError, firstValueFrom, throwError, timeout } from 'rxjs';
 import { ADMIN_PARSE_URL, ADMIN_SESSION_KEY, CLOUD_FUNCTION_BASE_URL, PARSE_APP_ID } from './admin.constants';
 import { AdminIdentity, AdminSession } from './admin.models';
 
@@ -9,7 +9,7 @@ import { AdminIdentity, AdminSession } from './admin.models';
 export class AdminSessionService {
   private readonly http = inject(HttpClient);
   private readonly router = inject(Router);
-  private readonly sessionChecks = new Map<string, Promise<void>>();
+  private readonly sessionChecks = new Map<string, Promise<boolean>>();
   private sharedStorageWritable = false;
   private readonly state = signal<AdminSession | null>(this.restore());
 
@@ -36,7 +36,16 @@ export class AdminSessionService {
       `${CLOUD_FUNCTION_BASE_URL}/xiaoshu/app/gateway`,
       { params: { action: 'user_login_passwd', name: username.trim(), passwd: password } },
       { headers },
-    ).pipe(timeout(20000)));
+    ).pipe(
+      timeout({ first: 20000, with: () => throwError(() => new Error('登录服务暂时不可用,请稍后重试。')) }),
+      catchError(error => {
+        if (!(error instanceof HttpErrorResponse)) return throwError(() => error);
+        const message = error.status === 0 || error.status >= 500
+          ? '登录服务暂时不可用,请稍后重试。'
+          : error.error?.retmsg || error.error?.message || '登录失败,请核对账号和密码。';
+        return throwError(() => new Error(message));
+      }),
+    ));
     if (envelope.retcode === -1 || !envelope.result) throw new Error(envelope.retmsg || '登录失败');
     const result = envelope.result;
     const session: AdminSession = {
@@ -55,11 +64,10 @@ export class AdminSessionService {
     return session;
   }
 
-  applyIdentity(identity: AdminIdentity): void {
-    const previousToken = this.state()?.sessionToken;
+  applyIdentity(identity: AdminIdentity, requestToken = this.state()?.sessionToken): boolean {
     this.syncSharedSession();
     const current = this.state();
-    if (!current || current.sessionToken !== previousToken || current.objectId !== identity.objectId) return;
+    if (!current || current.sessionToken !== requestToken || current.objectId !== identity.objectId) return false;
     const session: AdminSession = {
       ...current,
       displayName: identity.displayName,
@@ -73,25 +81,23 @@ export class AdminSessionService {
     };
     this.persist(session);
     this.state.set(session);
+    return true;
   }
 
-  logout(redirect = true): void {
-    const sessionToken = this.state()?.sessionToken ?? '';
-    this.persist(null);
-    this.state.set(null);
-    if (sessionToken) {
+  logout(redirect = true, sessionToken = this.state()?.sessionToken): void {
+    if (sessionToken && this.invalidateSession(sessionToken, false)) {
       this.http.post(`${CLOUD_FUNCTION_BASE_URL}/xiaoshu/admin/gateway`, {
         token: sessionToken,
         params: { operation: 'logout', sessionToken },
       }).subscribe({ error: () => undefined });
     }
-    if (redirect) this.redirectToLogin();
+    if (redirect && (!sessionToken || !this.state())) this.redirectToLogin();
   }
 
   /** Confirm with Parse before turning one gateway failure into a global logout. */
-  verifySessionAfterFailure(token: string): Promise<void> {
+  verifySessionAfterFailure(token: string): Promise<boolean> {
     this.syncSharedSession();
-    if (this.state()?.sessionToken !== token) return Promise.resolve();
+    if (this.state()?.sessionToken !== token) return Promise.resolve(false);
     const pending = this.sessionChecks.get(token);
     if (pending) return pending;
     const check = this.checkSession(token).finally(() => this.sessionChecks.delete(token));
@@ -99,28 +105,32 @@ export class AdminSessionService {
     return check;
   }
 
-  private async checkSession(token: string): Promise<void> {
+  private async checkSession(token: string): Promise<boolean> {
     try {
       const user = await firstValueFrom(this.http.get<{ objectId: string; isDisabled?: boolean; isDeleted?: boolean }>(
         `${ADMIN_PARSE_URL}/users/me`, { headers: { 'X-Parse-Application-Id': PARSE_APP_ID, 'X-Parse-Session-Token': token } },
       ).pipe(timeout(10000)));
-      // A proxy may return an unexpected success body; only a real user is evidence.
-      if (typeof user?.objectId === 'string' && user.objectId && this.state()?.sessionToken === token &&
-        (user.objectId !== this.state()?.objectId || user.isDisabled === true || user.isDeleted === true)) this.invalidateSession(token);
+      this.syncSharedSession();
+      const current = this.state();
+      if (typeof user?.objectId !== 'string' || !user.objectId || current?.sessionToken !== token) return false;
+      if (user.objectId === current.objectId && user.isDisabled !== true && user.isDeleted !== true) return true;
+      this.invalidateSession(token);
     } catch (error) {
       if (error instanceof HttpErrorResponse && [400, 401].includes(error.status) && Number(error.error?.code) === 209) this.invalidateSession(token);
       // An HTTP 401 alone can come from a proxy, not Parse's session validator.
     }
+    return false;
   }
 
   /** A late response for an older login must never clear a newer session. */
-  invalidateSession(requestToken: string): void {
+  invalidateSession(requestToken: string, redirect = true): boolean {
     // A newer login may already be stored even though its storage event has not run.
-    this.syncSharedSession();
-    if (!requestToken || this.state()?.sessionToken !== requestToken) return;
+    this.syncSharedSession(redirect);
+    if (!requestToken || this.state()?.sessionToken !== requestToken) return false;
     this.persist(null);
     this.state.set(null);
-    this.redirectToLogin();
+    if (redirect) this.redirectToLogin();
+    return true;
   }
 
   private redirectToLogin(): void {
@@ -137,7 +147,7 @@ export class AdminSessionService {
     } catch { return null; }
   }
 
-  private syncSharedSession(): void {
+  private syncSharedSession(redirect = true): void {
     if (!this.sharedStorageWritable) return;
     let next: AdminSession | null;
     try { next = this.decode(localStorage.getItem(ADMIN_SESSION_KEY)); }
@@ -145,6 +155,7 @@ export class AdminSessionService {
     const previous = this.state();
     this.state.set(next);
     this.writeTabSession(next);
+    if (!redirect) return;
     if (previous && !next) this.redirectToLogin();
     else if (previous && next && previous.objectId !== next.objectId) void this.router.navigate(['/admin/dashboard']);
   }
@@ -158,17 +169,18 @@ export class AdminSessionService {
 
   private persist(session: AdminSession | null): void {
     try {
-      if (session) localStorage.setItem(ADMIN_SESSION_KEY, JSON.stringify(session));
-      else localStorage.removeItem(ADMIN_SESSION_KEY);
+      // A stored null prevents another tab from restoring a revoked session on reload.
+      localStorage.setItem(ADMIN_SESSION_KEY, JSON.stringify(session));
       this.sharedStorageWritable = true;
     } catch { this.sharedStorageWritable = false; /* Fall back to the current tab. */ }
     this.writeTabSession(session);
   }
 
   private restore(): AdminSession | null {
-    let session: AdminSession | null = null;
-    try { session = this.decode(localStorage.getItem(ADMIN_SESSION_KEY)); } catch { /* restricted storage */ }
-    if (!session) {
+    let sharedValue: string | null = null;
+    try { sharedValue = localStorage.getItem(ADMIN_SESSION_KEY); } catch { /* restricted storage */ }
+    let session = this.decode(sharedValue);
+    if (!session && sharedValue !== 'null') {
       try { session = this.decode(sessionStorage.getItem(ADMIN_SESSION_KEY)); } catch { /* restricted storage */ }
     }
     this.persist(session);

+ 35 - 0
projects/xiaoshu-admin/src/app/cloud-functions.service.spec.ts

@@ -39,6 +39,41 @@ describe('CloudFunctionsService', () => {
     request.flush({ success: true, data: { page: 1, pageSize: 20, total: 0, items: [] } });
     await expectAsync(pending).toBeResolvedTo({ page: 1, pageSize: 20, total: 0, items: [] });
   });
+  it('retries identity metadata once when Parse confirms the gateway rejected a valid session', fakeAsync(() => {
+    const url = CLOUD_FUNCTION_BASE_URL + '/xiaoshu/admin/gateway';
+    const sessions = TestBed.inject(AdminSessionService);
+    (sessions.verifySessionAfterFailure as jasmine.Spy).and.resolveTo(true);
+    let outcome: unknown;
+    service.admin('meta').then(value => outcome = value, error => outcome = error);
+
+    http.expectOne(url).flush({ message: '无效的 sessionToken' }, { status: 401, statusText: 'Unauthorized' });
+    tick(600);
+    expect(sessions.verifySessionAfterFailure).toHaveBeenCalledOnceWith('r:admin-session');
+    http.expectOne(url).flush({ success: true, data: { identity: { objectId: 'admin' } } });
+    tick();
+    expect(outcome).toEqual({ identity: { objectId: 'admin' } });
+  }));
+
+  it('does not retry authentication when Parse cannot confirm the session', fakeAsync(() => {
+    const url = CLOUD_FUNCTION_BASE_URL + '/xiaoshu/admin/gateway';
+    let failure: unknown;
+    service.admin('meta').catch(error => failure = error);
+    http.expectOne(url).flush({ message: '无效的 sessionToken' }, { status: 401, statusText: 'Unauthorized' });
+    tick(800);
+    http.expectNone(url);
+    expect(failure).toBeDefined();
+  }));
+
+  it('does not replay a password change when its response is lost', fakeAsync(() => {
+    const url = CLOUD_FUNCTION_BASE_URL + '/xiaoshu/admin/gateway';
+    let failure: Error | undefined;
+    service.admin('changeOwnPassword').catch(error => failure = error);
+    http.expectOne(url).flush({ message: 'unavailable' }, { status: 503, statusText: 'Service Unavailable' });
+    tick(800);
+    http.expectNone(url);
+    expect(failure?.message).toContain('结果待核对');
+  }));
+
   it('does not log out an authenticated user for a forbidden account-management action', async () => {
     const pending=service.admin('operatorAccounts/list');
     const assertion=expectAsync(pending).toBeRejected();

+ 20 - 6
projects/xiaoshu-admin/src/app/cloud-functions.service.ts

@@ -2,7 +2,7 @@ import { isTransientGatewayReadError } from '../../../shared/gateway-read-error'
 import { RequestScheduler, stableRequestJson } from '../../../shared/request-scheduler';
 import { HttpClient, HttpErrorResponse } from '@angular/common/http';
 import { inject, Injectable } from '@angular/core';
-import { firstValueFrom, Subject, timeout, throwError, retry, timer, mergeMap, of, Observable, tap } from 'rxjs';
+import { firstValueFrom, from, Subject, timeout, throwError, retry, timer, mergeMap, of, Observable, tap } from 'rxjs';
 import { CLOUD_FUNCTION_BASE_URL } from './admin.constants';
 import { AdminSessionService } from './admin-session.service';
 import { CloudEnvelope, LegacyCloudEnvelope } from './admin.models';
@@ -27,7 +27,7 @@ export class CloudFunctionsService {
     if (!token) throw new CloudFunctionError('管理员会话已失效', 401);
     try {
       const envelope = await this.request<CloudEnvelope<T>>('xiaoshu/admin/gateway', token,
-        { ...params, operation }, false);
+        { ...params, operation }, operation === 'meta');
       if (!envelope.success) { await this.handleAuthenticationFailure(token, 0, envelope); throw new CloudFunctionError(envelope.message || envelope.error || '云函数执行失败'); }
       if (this.isMutation(operation)) this.announceDataChange();
       return envelope.data;
@@ -36,12 +36,20 @@ export class CloudFunctionsService {
       if (error instanceof HttpErrorResponse) {
         const payload = error.error as { error?: string; message?: string } | null;
         await this.handleAuthenticationFailure(token, error.status, payload);
+        if (operation === 'meta' && this.isAmbiguousSessionRejection(error) && this.sessions.session()?.sessionToken === token) {
+          throw new CloudFunctionError('管理员身份暂未校验成功,请稍后重试。', error.status);
+        }
         throw new CloudFunctionError(payload?.message || payload?.error || error.message, error.status, payload);
       }
       throw new CloudFunctionError(error instanceof Error ? error.message : '未知云函数错误');
     }
   }
 
+  private isAmbiguousSessionRejection(error: HttpErrorResponse): boolean {
+    const body = error.error as { code?: number; error?: string; message?: string } | null;
+    return error.status === 401 && body?.code == null && (body?.message || body?.error) === '无效的 sessionToken';
+  }
+
   // Explicitly allow only reads. Unknown operations and all submissions must never replay.
   private isReadOperation(operation: string): boolean {
     return /^ops\/(?:payroll\/(?:overview|list|coaches|detail|export|review-rewards)|lessons\/(?:list|detail|export\/(?:status|download))|users\/(?:list|detail|notes|audit|credit-preview|credit-accounts|credit-ledger|credit-status)|schedule\/calendar|live\/versions|dashboard\/(?:summary|schedule-trend)|coaches\/(?:list|detail)|stores\/(?:list|detail)|coach-availability\/list|learning-reports\/(?:list|detail)|vocabulary\/(?:tree|list)|teaching-rules\/list|pay-rates\/list|appointments\/(?:preflight|list))$/.test(operation);
@@ -66,10 +74,16 @@ export class CloudFunctionsService {
           const vocabularyRead = operation === 'ops/vocabulary/tree' || operation === 'ops/vocabulary/list';
           const transient = error instanceof HttpErrorResponse && ([0, 502, 503, 504].includes(error.status)
             || (vocabularyRead && isTransientGatewayReadError(error.status, error.error)));
-          // A timeout may leave work running on the server; do not add another slow request.
-          if (!readOnly || !transient || this.sessions.session()?.sessionToken !== token) return throwError(() => error);
-          const suggested=Number(error.error?.retryAfterMs);
-          return timer(Math.max(vocabularyRead ? 1200 : 400,Number.isFinite(suggested)?Math.min(10000,suggested):0)+Math.floor(Math.random()*100)).pipe(mergeMap(() => this.sessions.session()?.sessionToken === token ? of(0) : throwError(() => error)));
+          const ambiguousMeta = operation === 'meta' && error instanceof HttpErrorResponse && this.isAmbiguousSessionRejection(error);
+          // Never replay writes or an authentication failure that Parse cannot verify.
+          if (!readOnly || (!transient && !ambiguousMeta) || this.sessions.session()?.sessionToken !== token) return throwError(() => error);
+          const suggested = Number(error.error?.retryAfterMs);
+          const delay = Math.max(vocabularyRead ? 1200 : 400, Number.isFinite(suggested) ? Math.min(10000, suggested) : 0);
+          const stillCurrent = () => this.sessions.session()?.sessionToken === token;
+          return (ambiguousMeta ? from(this.sessions.verifySessionAfterFailure(token)) : of(true)).pipe(
+            mergeMap(valid => valid && stillCurrent() ? timer(delay + Math.floor(Math.random() * 100)) : throwError(() => error)),
+            mergeMap(() => stillCurrent() ? of(0) : throwError(() => error)),
+          );
         } }),
       ).pipe(tap(value=>{
         const envelope=value as {data?:{clientFetchedAt?:number};readCache?:{remainingMs:number}};

+ 37 - 4
projects/xiaoshu-admin/src/app/pages/admin-change-password.component.spec.ts

@@ -1,26 +1,37 @@
+import { provideHttpClient } from '@angular/common/http';
+import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
 import { TestBed } from '@angular/core/testing';
 import { Router } from '@angular/router';
+import { ADMIN_SESSION_KEY } from '../admin.constants';
 import { AdminSessionService } from '../admin-session.service';
 import { CloudFunctionsService } from '../cloud-functions.service';
 import { AdminChangePasswordComponent } from './admin-change-password.component';
 
 describe('AdminChangePasswordComponent', () => {
   const functions = { admin: jasmine.createSpy('admin') };
-  const sessions = { logout: jasmine.createSpy('logout') };
+  let sessions: AdminSessionService;
   const router = { navigate: jasmine.createSpy('navigate') };
   let component: AdminChangePasswordComponent;
 
   beforeEach(async () => {
-    functions.admin.calls.reset(); sessions.logout.calls.reset(); router.navigate.calls.reset(); router.navigate.and.resolveTo(true);
+    functions.admin.calls.reset(); router.navigate.calls.reset(); router.navigate.and.resolveTo(true);
+    localStorage.setItem(ADMIN_SESSION_KEY, JSON.stringify({ objectId: 'admin-user', sessionToken: 'old' }));
     await TestBed.configureTestingModule({
       imports: [AdminChangePasswordComponent],
       providers: [
         { provide: CloudFunctionsService, useValue: functions },
-        { provide: AdminSessionService, useValue: sessions },
+        provideHttpClient(), provideHttpClientTesting(),
         { provide: Router, useValue: router },
       ],
     }).compileComponents();
     component = TestBed.createComponent(AdminChangePasswordComponent).componentInstance;
+    sessions = TestBed.inject(AdminSessionService);
+  });
+
+  afterEach(() => {
+    TestBed.inject(HttpTestingController).verify();
+    localStorage.removeItem(ADMIN_SESSION_KEY);
+    sessionStorage.removeItem(ADMIN_SESSION_KEY);
   });
 
   it('rejects a mismatched confirmation before calling the cloud function', async () => {
@@ -32,6 +43,28 @@ describe('AdminChangePasswordComponent', () => {
   it('changes the current password and forces a fresh login', async () => {
     functions.admin.and.resolveTo({ objectId: 'admin-user', revokedSessions: 2, reauthenticationRequired: true }); component.oldPassword.set('CurrentPass123'); component.newPassword.set('NewPassword123'); component.confirmPassword.set('NewPassword123');
     await component.submit();
-    expect(functions.admin).toHaveBeenCalledWith('changeOwnPassword', { oldPassword: 'CurrentPass123', newPassword: 'NewPassword123' }); expect(sessions.logout).toHaveBeenCalledWith(false); expect(router.navigate).toHaveBeenCalledWith(['/admin/login'], { queryParams: { passwordChanged: '1' } });
+    expect(functions.admin).toHaveBeenCalledWith('changeOwnPassword', { oldPassword: 'CurrentPass123', newPassword: 'NewPassword123' }); expect(sessions.session()).toBeNull(); expect(router.navigate).toHaveBeenCalledWith(['/admin/login'], { queryParams: { passwordChanged: '1' } });
   });
+
+  for (const receivedStorageEvent of [false, true]) {
+    it(`preserves a new login while a password change response was pending (storage event: ${receivedStorageEvent})`, async () => {
+      let finish!: () => void;
+      functions.admin.and.returnValue(new Promise<void>(resolve => { finish = resolve; }));
+      component.oldPassword.set('CurrentPass123');
+      component.newPassword.set('NewPassword123');
+      component.confirmPassword.set('NewPassword123');
+
+      const pending = component.submit();
+      localStorage.setItem(ADMIN_SESSION_KEY, JSON.stringify({ objectId: 'admin-user', sessionToken: 'fresh' }));
+      if (receivedStorageEvent) {
+        window.dispatchEvent(new StorageEvent('storage', { key: ADMIN_SESSION_KEY, storageArea: localStorage }));
+      }
+      finish();
+      await pending;
+
+      expect(sessions.session()?.sessionToken).toBe('fresh');
+      expect(JSON.parse(localStorage.getItem(ADMIN_SESSION_KEY)!).sessionToken).toBe('fresh');
+      expect(router.navigate).not.toHaveBeenCalledWith(['/admin/login'], jasmine.anything());
+    });
+  }
 });

+ 10 - 2
projects/xiaoshu-admin/src/app/pages/admin-change-password.component.ts

@@ -28,16 +28,24 @@ export class AdminChangePasswordComponent {
   constructor() { document.title = '修改密码 · 小树陪练管理后台'; }
 
   async submit(): Promise<void> {
+    if (this.loading()) return;
     this.error.set('');
     if (!this.oldPassword()) { this.error.set('请输入原密码'); return; }
     if (this.newPassword().length < 8 || this.newPassword().length > 72) { this.error.set('新密码长度应为 8 至 72 位'); return; }
     if (this.newPassword() !== this.confirmPassword()) { this.error.set('两次输入的新密码不一致'); return; }
     if (this.newPassword() === this.oldPassword()) { this.error.set('新密码不能与原密码相同'); return; }
+    const sessionToken = this.sessions.session()?.sessionToken;
+    if (!sessionToken) { this.error.set('登录已失效,请重新登录'); return; }
     this.loading.set(true);
     try {
       await this.functions.admin('changeOwnPassword', { oldPassword: this.oldPassword(), newPassword: this.newPassword() });
-      this.oldPassword.set(''); this.newPassword.set(''); this.confirmPassword.set(''); this.sessions.logout(false);
-      await this.router.navigate(['/admin/login'], { queryParams: { passwordChanged: '1' } });
+      this.oldPassword.set('');
+      this.newPassword.set('');
+      this.confirmPassword.set('');
+      // The server already revoked the old session during the password change.
+      this.sessions.invalidateSession(sessionToken, false);
+      if (this.sessions.session()) await this.router.navigate(['/admin/dashboard']);
+      else await this.router.navigate(['/admin/login'], { queryParams: { passwordChanged: '1' } });
     } catch (error) {
       this.oldPassword.set('');
       this.error.set(error instanceof Error ? error.message : '密码修改失败');

+ 1 - 1
projects/xiaoshu-admin/src/app/pages/admin-login.component.spec.ts

@@ -21,7 +21,7 @@ describe('AdminLoginComponent session handling',()=>{
   it('rejects a freshly logged-in account that has no admin permission',async()=>{
     functions.admin.and.rejectWith(new CloudFunctionError('需要管理员权限',403));
     const component=TestBed.runInInjectionContext(()=>new AdminLoginComponent());component.username='member';component.password='password';
-    await component.submit();expect(sessions.logout).toHaveBeenCalledOnceWith(false);
+    await component.submit();expect(sessions.logout).toHaveBeenCalledOnceWith(false, 'new');
   });
   it('does not revoke another successful login when an earlier password attempt fails',async()=>{
     sessions.login.and.rejectWith(new Error('密码错误'));

+ 12 - 7
projects/xiaoshu-admin/src/app/pages/admin-login.component.ts

@@ -34,6 +34,7 @@ export class AdminLoginComponent {
   constructor() { this.username = this.route.snapshot.queryParamMap.get('account')?.trim().slice(0,100) || ''; document.title = '后台登录 · 小树陪练'; if (this.route.snapshot.queryParamMap.get('passwordChanged') === '1') this.notice.set('密码已修改,所有旧会话均已注销,请使用新密码登录。'); }
 
   async submit(): Promise<void> {
+    if (this.loading()) return;
     if (!this.username.trim() || !this.password) {
       this.error.set('请输入管理员账号和密码');
       return;
@@ -42,19 +43,23 @@ export class AdminLoginComponent {
     this.error.set('');
     let attemptToken = '';
     try {
-      attemptToken = (await this.sessions.login(this.username, this.password)).sessionToken;
-      const returnUrl = this.sessions.session()?.passwordResetRequired ? '/admin/change-password' : this.route.snapshot.queryParamMap.get('returnUrl') || '/admin/dashboard';
-      if (this.sessions.session()?.isSuperAdmin && returnUrl.split('?')[0] === '/admin/dashboard') {
+      const session = await this.sessions.login(this.username, this.password);
+      attemptToken = session.sessionToken;
+      const meta = await this.functions.admin<{ identity: AdminIdentity }>('meta');
+      if (!this.sessions.applyIdentity(meta.identity, attemptToken)) return;
+      const returnUrl = this.sessions.session()?.passwordResetRequired
+        ? '/admin/change-password'
+        : this.route.snapshot.queryParamMap.get('returnUrl') || '/admin/dashboard';
+      if (meta.identity.isSuperAdmin && returnUrl.split('?')[0] === '/admin/dashboard') {
         void this.operations.dashboard().catch(() => undefined);
         void import('../layout/admin-shell.component');
         void import('./admin-dashboard.component');
       }
-      const meta = await this.functions.admin<{ identity: AdminIdentity }>('meta');
-      this.sessions.applyIdentity(meta.identity);
-      await this.router.navigateByUrl(meta.identity.operationsRole==='store-admin'&&!this.sessions.session()?.passwordResetRequired?'/admin/store-home':returnUrl);
+      await this.router.navigateByUrl(meta.identity.operationsRole === 'store-admin' && returnUrl !== '/admin/change-password'
+        ? '/admin/store-home' : returnUrl);
     } catch (error) {
       // Transient metadata/network failures must not revoke a successful login.
-      if (error instanceof CloudFunctionError && error.status === 403 && attemptToken && this.sessions.session()?.sessionToken === attemptToken) this.sessions.logout(false);
+      if (error instanceof CloudFunctionError && error.status === 403 && attemptToken) this.sessions.logout(false, attemptToken);
       this.error.set(error instanceof Error ? error.message : '登录失败');
     } finally {
       this.loading.set(false);