fix(admin-auth): reuse exact same QR/session API and component for admin login
Some checks failed
Architecture Governance / architecture (push) Has been cancelled
Some checks failed
Architecture Governance / architecture (push) Has been cancelled
- Removed invented adminAuthApiUrl endpoint and separate AdminLoginComponent.
Admin login now uses the exact same Telegram session backend
(TelegramSessionApiService, {authApiUrl}/users/sessions) and the exact
same TelegramLoginComponent (mode="customer" | "admin" input) as customer
login - only the storage (cookie/localStorage/signals) stays separate.
- Extracted the shared HTTP+normalization logic from AuthService into
TelegramSessionApiService so both AuthService and AdminAuthService call it
instead of duplicating request/parsing code.
- Documented the resulting backend gap in docs/Project-Editor.md: since the
session API has no concept of "admin", server-side role enforcement is
required when admin API calls are made - the frontend only decides where
to store the session, not whether the user is actually an admin.
This commit is contained in:
@@ -1,9 +1,7 @@
|
||||
import { Injectable, signal, computed } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable, of, catchError, map, tap } from 'rxjs';
|
||||
import { Injectable, signal, computed, inject } from '@angular/core';
|
||||
import { Observable, tap } from 'rxjs';
|
||||
import { AuthSession, AuthStatus, WebSessionStart } from '../models/auth.model';
|
||||
import { environment } from '../../environments/environment';
|
||||
import { generateGuid } from '../shared/util/guid.util';
|
||||
import { TelegramSessionApiService } from './telegram-session-api.service';
|
||||
|
||||
const WEB_SESSION_COOKIE = 'webSessionID';
|
||||
const WEB_SESSION_COOKIE_MAX_AGE_SECONDS = 60 * 60;
|
||||
@@ -12,6 +10,8 @@ const WEB_SESSION_COOKIE_MAX_AGE_SECONDS = 60 * 60;
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthService {
|
||||
private readonly api = inject(TelegramSessionApiService);
|
||||
|
||||
private sessionSignal = signal<AuthSession | null>(null);
|
||||
private statusSignal = signal<AuthStatus>('unknown');
|
||||
private showLoginSignal = signal(false);
|
||||
@@ -27,10 +27,9 @@ export class AuthService {
|
||||
/** Display name of authenticated user */
|
||||
readonly displayName = computed(() => this.sessionSignal()?.displayName ?? null);
|
||||
|
||||
private readonly authApiUrl = environment.authApiUrl;
|
||||
private sessionCheckTimer?: ReturnType<typeof setTimeout>;
|
||||
|
||||
constructor(private http: HttpClient) {
|
||||
constructor() {
|
||||
// On init, check existing session via cookie
|
||||
this.checkSession();
|
||||
}
|
||||
@@ -53,22 +52,14 @@ export class AuthService {
|
||||
});
|
||||
}
|
||||
|
||||
/** Check session without updating internal state (for polling) */
|
||||
/** Check session without updating internal state beyond activating on success (used for polling). */
|
||||
checkSessionOnce(webSessionID = this.getStoredWebSessionID()): Observable<AuthSession | null> {
|
||||
if (!webSessionID) {
|
||||
return of(null);
|
||||
}
|
||||
|
||||
return this.http.get<Record<string, unknown>>(
|
||||
`${this.authApiUrl}/users/sessions/${encodeURIComponent(webSessionID)}`
|
||||
).pipe(
|
||||
map(response => this.normalizeWebSession(response, webSessionID)),
|
||||
return this.api.checkSessionOnce(webSessionID).pipe(
|
||||
tap(session => {
|
||||
if (session?.active) {
|
||||
this.activateSession(session);
|
||||
}
|
||||
}),
|
||||
catchError(() => of(null))
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -84,39 +75,18 @@ export class AuthService {
|
||||
}
|
||||
|
||||
/** Generate the Telegram login URL for bot-based auth */
|
||||
getTelegramLoginUrl(webSessionID = generateGuid()): string {
|
||||
const botUsername = this.getTelegramBotUsername();
|
||||
return `https://t.me/${botUsername}?start=${encodeURIComponent(webSessionID)}`;
|
||||
getTelegramLoginUrl(webSessionID: string): string {
|
||||
return this.api.getBotLoginUrl(webSessionID);
|
||||
}
|
||||
|
||||
/** Generate a Telegram app deep link for mobile login without opening a browser tab. */
|
||||
getTelegramAppLoginUrl(webSessionID: string): string {
|
||||
const botUsername = this.getTelegramBotUsername();
|
||||
return `tg://resolve?domain=${encodeURIComponent(botUsername)}&start=${encodeURIComponent(webSessionID)}`;
|
||||
}
|
||||
|
||||
/** Get QR code data URL for Telegram login */
|
||||
getTelegramQrUrl(): string {
|
||||
return this.getTelegramLoginUrl();
|
||||
return this.api.getBotAppLoginUrl(webSessionID);
|
||||
}
|
||||
|
||||
/** Create a backend web session and return the Telegram start link for it. */
|
||||
createWebSession(): Observable<WebSessionStart> {
|
||||
const webSessionID = generateGuid();
|
||||
|
||||
return this.http.post<Record<string, unknown>>(
|
||||
`${this.authApiUrl}/users/sessions`,
|
||||
{ webSessionID },
|
||||
{ headers: { WebSessionID: webSessionID } }
|
||||
).pipe(
|
||||
map(response => {
|
||||
const responseWebSessionID = this.extractSessionId(response, webSessionID);
|
||||
return {
|
||||
webSessionID: responseWebSessionID,
|
||||
url: this.getTelegramLoginUrl(responseWebSessionID),
|
||||
};
|
||||
})
|
||||
);
|
||||
return this.api.createSession();
|
||||
}
|
||||
|
||||
/** Show login dialog (called when user tries to pay without being logged in) */
|
||||
@@ -138,11 +108,7 @@ export class AuthService {
|
||||
return;
|
||||
}
|
||||
|
||||
this.http.delete(`${this.authApiUrl}/users/sessions/${encodeURIComponent(webSessionID)}`, {
|
||||
headers: { WebSessionID: webSessionID }
|
||||
}).pipe(
|
||||
catchError(() => of(null))
|
||||
).subscribe(() => {
|
||||
this.api.logout(webSessionID).subscribe(() => {
|
||||
this.clearAuthState('unauthenticated');
|
||||
});
|
||||
}
|
||||
@@ -184,120 +150,6 @@ export class AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
private normalizeWebSession(response: Record<string, unknown> | null, fallbackSessionId: string): AuthSession | null {
|
||||
if (!response) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const user = this.asRecord(this.readFirst(response, ['user', 'User', 'telegramUser', 'TelegramUser'])) ?? response;
|
||||
const status = this.readFirst(response, [
|
||||
'status',
|
||||
'Status',
|
||||
'active',
|
||||
'Active',
|
||||
'loggedIn',
|
||||
'LoggedIn',
|
||||
'isLoggedIn',
|
||||
'IsLoggedIn',
|
||||
'authenticated',
|
||||
'Authenticated'
|
||||
]);
|
||||
const active = this.isActiveStatus(status);
|
||||
const sessionId = this.extractSessionId(response, fallbackSessionId);
|
||||
const username = this.readString(this.readFirst(user, ['username', 'Username']))
|
||||
?? this.readString(this.readFirst(response, ['username', 'Username']));
|
||||
const firstName = this.readString(this.readFirst(user, ['firstName', 'first_name', 'FirstName', 'First_name']));
|
||||
const lastName = this.readString(this.readFirst(user, ['lastName', 'last_name', 'LastName', 'Last_name']));
|
||||
const fullName = [firstName, lastName].filter(Boolean).join(' ');
|
||||
const explicitDisplayName = this.readString(this.readFirst(response, ['displayName', 'DisplayName', 'name', 'Name']))
|
||||
?? this.readString(this.readFirst(user, ['displayName', 'DisplayName', 'name', 'Name']))
|
||||
const displayName = explicitDisplayName ?? username ?? (fullName || 'Telegram User');
|
||||
const telegramUserId = this.readNumber(this.readFirst(user, ['userId','telegramUserId', 'telegramUserID', 'TelegramUserID', 'id', 'ID']))
|
||||
?? this.readNumber(this.readFirst(response, ['userId', 'telegramUserId', 'telegramUserID', 'TelegramUserID', 'userID', 'UserID', 'UserId']))
|
||||
?? null;
|
||||
const expiresAt = this.readString(this.readFirst(response, ['expiresAt', 'ExpiresAt', 'expires', 'Expires']))
|
||||
?? new Date(Date.now() + WEB_SESSION_COOKIE_MAX_AGE_SECONDS * 1000).toISOString();
|
||||
|
||||
return {
|
||||
sessionId,
|
||||
userId: telegramUserId,
|
||||
username,
|
||||
displayName,
|
||||
active,
|
||||
expires: expiresAt,
|
||||
};
|
||||
}
|
||||
|
||||
private extractSessionId(response: Record<string, unknown> | null, fallbackSessionId: string): string {
|
||||
if (!response) {
|
||||
return fallbackSessionId;
|
||||
}
|
||||
|
||||
return this.readString(this.readFirst(response, [
|
||||
'webSessionID',
|
||||
'WebSessionID',
|
||||
'webSessionId',
|
||||
'sessionID',
|
||||
'SessionID',
|
||||
'sessionId',
|
||||
'id',
|
||||
'ID'
|
||||
])) ?? fallbackSessionId;
|
||||
}
|
||||
|
||||
private readFirst(source: Record<string, unknown>, keys: string[]): unknown {
|
||||
for (const key of keys) {
|
||||
if (Object.prototype.hasOwnProperty.call(source, key)) {
|
||||
return source[key];
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private readString(value: unknown): string | null {
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (typeof value === 'number' || typeof value === 'bigint') {
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private readNumber(value: unknown): number | null {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (typeof value === 'string') {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: null;
|
||||
}
|
||||
|
||||
private isActiveStatus(status: unknown): boolean {
|
||||
if (status === true || status === 1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof status !== 'string') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return ['true', '1', 'active', 'authenticated', 'confirmed', 'success', 'logged_in'].includes(status.toLowerCase());
|
||||
}
|
||||
|
||||
private getStoredWebSessionID(): string | null {
|
||||
if (typeof document === 'undefined') {
|
||||
return null;
|
||||
@@ -334,8 +186,4 @@ export class AuthService {
|
||||
|
||||
document.cookie = `${WEB_SESSION_COOKIE}=; Max-Age=0; Path=/; SameSite=Lax`;
|
||||
}
|
||||
|
||||
private getTelegramBotUsername(): string {
|
||||
return (environment as Record<string, unknown>)['telegramBot'] as string || 'DexarSupport_bot';
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user