|
@@ -1,7 +1,7 @@
|
|
|
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
|
|
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
|
|
|
import { computed, DestroyRef, inject, Injectable, signal } from '@angular/core';
|
|
import { computed, DestroyRef, inject, Injectable, signal } from '@angular/core';
|
|
|
import { Router } from '@angular/router';
|
|
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 { ADMIN_PARSE_URL, ADMIN_SESSION_KEY, CLOUD_FUNCTION_BASE_URL, PARSE_APP_ID } from './admin.constants';
|
|
|
import { AdminIdentity, AdminSession } from './admin.models';
|
|
import { AdminIdentity, AdminSession } from './admin.models';
|
|
|
|
|
|
|
@@ -9,7 +9,7 @@ import { AdminIdentity, AdminSession } from './admin.models';
|
|
|
export class AdminSessionService {
|
|
export class AdminSessionService {
|
|
|
private readonly http = inject(HttpClient);
|
|
private readonly http = inject(HttpClient);
|
|
|
private readonly router = inject(Router);
|
|
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 sharedStorageWritable = false;
|
|
|
private readonly state = signal<AdminSession | null>(this.restore());
|
|
private readonly state = signal<AdminSession | null>(this.restore());
|
|
|
|
|
|
|
@@ -36,7 +36,16 @@ export class AdminSessionService {
|
|
|
`${CLOUD_FUNCTION_BASE_URL}/xiaoshu/app/gateway`,
|
|
`${CLOUD_FUNCTION_BASE_URL}/xiaoshu/app/gateway`,
|
|
|
{ params: { action: 'user_login_passwd', name: username.trim(), passwd: password } },
|
|
{ params: { action: 'user_login_passwd', name: username.trim(), passwd: password } },
|
|
|
{ headers },
|
|
{ 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 || '登录失败');
|
|
if (envelope.retcode === -1 || !envelope.result) throw new Error(envelope.retmsg || '登录失败');
|
|
|
const result = envelope.result;
|
|
const result = envelope.result;
|
|
|
const session: AdminSession = {
|
|
const session: AdminSession = {
|
|
@@ -55,11 +64,10 @@ export class AdminSessionService {
|
|
|
return session;
|
|
return session;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- applyIdentity(identity: AdminIdentity): void {
|
|
|
|
|
- const previousToken = this.state()?.sessionToken;
|
|
|
|
|
|
|
+ applyIdentity(identity: AdminIdentity, requestToken = this.state()?.sessionToken): boolean {
|
|
|
this.syncSharedSession();
|
|
this.syncSharedSession();
|
|
|
const current = this.state();
|
|
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 = {
|
|
const session: AdminSession = {
|
|
|
...current,
|
|
...current,
|
|
|
displayName: identity.displayName,
|
|
displayName: identity.displayName,
|
|
@@ -73,25 +81,23 @@ export class AdminSessionService {
|
|
|
};
|
|
};
|
|
|
this.persist(session);
|
|
this.persist(session);
|
|
|
this.state.set(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`, {
|
|
this.http.post(`${CLOUD_FUNCTION_BASE_URL}/xiaoshu/admin/gateway`, {
|
|
|
token: sessionToken,
|
|
token: sessionToken,
|
|
|
params: { operation: 'logout', sessionToken },
|
|
params: { operation: 'logout', sessionToken },
|
|
|
}).subscribe({ error: () => undefined });
|
|
}).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. */
|
|
/** Confirm with Parse before turning one gateway failure into a global logout. */
|
|
|
- verifySessionAfterFailure(token: string): Promise<void> {
|
|
|
|
|
|
|
+ verifySessionAfterFailure(token: string): Promise<boolean> {
|
|
|
this.syncSharedSession();
|
|
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);
|
|
const pending = this.sessionChecks.get(token);
|
|
|
if (pending) return pending;
|
|
if (pending) return pending;
|
|
|
const check = this.checkSession(token).finally(() => this.sessionChecks.delete(token));
|
|
const check = this.checkSession(token).finally(() => this.sessionChecks.delete(token));
|
|
@@ -99,28 +105,32 @@ export class AdminSessionService {
|
|
|
return check;
|
|
return check;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- private async checkSession(token: string): Promise<void> {
|
|
|
|
|
|
|
+ private async checkSession(token: string): Promise<boolean> {
|
|
|
try {
|
|
try {
|
|
|
const user = await firstValueFrom(this.http.get<{ objectId: string; isDisabled?: boolean; isDeleted?: boolean }>(
|
|
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 } },
|
|
`${ADMIN_PARSE_URL}/users/me`, { headers: { 'X-Parse-Application-Id': PARSE_APP_ID, 'X-Parse-Session-Token': token } },
|
|
|
).pipe(timeout(10000)));
|
|
).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) {
|
|
} catch (error) {
|
|
|
if (error instanceof HttpErrorResponse && [400, 401].includes(error.status) && Number(error.error?.code) === 209) this.invalidateSession(token);
|
|
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.
|
|
// 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. */
|
|
/** 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.
|
|
// 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.persist(null);
|
|
|
this.state.set(null);
|
|
this.state.set(null);
|
|
|
- this.redirectToLogin();
|
|
|
|
|
|
|
+ if (redirect) this.redirectToLogin();
|
|
|
|
|
+ return true;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
private redirectToLogin(): void {
|
|
private redirectToLogin(): void {
|
|
@@ -137,7 +147,7 @@ export class AdminSessionService {
|
|
|
} catch { return null; }
|
|
} catch { return null; }
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- private syncSharedSession(): void {
|
|
|
|
|
|
|
+ private syncSharedSession(redirect = true): void {
|
|
|
if (!this.sharedStorageWritable) return;
|
|
if (!this.sharedStorageWritable) return;
|
|
|
let next: AdminSession | null;
|
|
let next: AdminSession | null;
|
|
|
try { next = this.decode(localStorage.getItem(ADMIN_SESSION_KEY)); }
|
|
try { next = this.decode(localStorage.getItem(ADMIN_SESSION_KEY)); }
|
|
@@ -145,6 +155,7 @@ export class AdminSessionService {
|
|
|
const previous = this.state();
|
|
const previous = this.state();
|
|
|
this.state.set(next);
|
|
this.state.set(next);
|
|
|
this.writeTabSession(next);
|
|
this.writeTabSession(next);
|
|
|
|
|
+ if (!redirect) return;
|
|
|
if (previous && !next) this.redirectToLogin();
|
|
if (previous && !next) this.redirectToLogin();
|
|
|
else if (previous && next && previous.objectId !== next.objectId) void this.router.navigate(['/admin/dashboard']);
|
|
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 {
|
|
private persist(session: AdminSession | null): void {
|
|
|
try {
|
|
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;
|
|
this.sharedStorageWritable = true;
|
|
|
} catch { this.sharedStorageWritable = false; /* Fall back to the current tab. */ }
|
|
} catch { this.sharedStorageWritable = false; /* Fall back to the current tab. */ }
|
|
|
this.writeTabSession(session);
|
|
this.writeTabSession(session);
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
private restore(): AdminSession | null {
|
|
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 */ }
|
|
try { session = this.decode(sessionStorage.getItem(ADMIN_SESSION_KEY)); } catch { /* restricted storage */ }
|
|
|
}
|
|
}
|
|
|
this.persist(session);
|
|
this.persist(session);
|