release: @marketplaces/auth 0.1.0 (built from main)
This commit is contained in:
7
dist/telegram/admin-auth-headers.interceptor.d.ts
vendored
Normal file
7
dist/telegram/admin-auth-headers.interceptor.d.ts
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
import { HttpInterceptorFn } from '@angular/common/http';
|
||||
/**
|
||||
* Attaches admin session/token headers only to admin API requests. Scoped to
|
||||
* admin-gated paths so it never touches customer requests and never reads
|
||||
* the customer AuthService's session.
|
||||
*/
|
||||
export declare const adminAuthHeadersInterceptor: HttpInterceptorFn;
|
||||
26
dist/telegram/admin-auth-headers.interceptor.js
vendored
Normal file
26
dist/telegram/admin-auth-headers.interceptor.js
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { AdminAuthService } from './admin-auth.service';
|
||||
/** Backend paths that require an active AdminWebSessionID. Adjust to match your API surface if consuming this outside marketplaces. */
|
||||
const ADMIN_GATED_PATH_SEGMENTS = ['/admin/', '/backoffice/', '/builder/', '/media/'];
|
||||
/**
|
||||
* Attaches admin session/token headers only to admin API requests. Scoped to
|
||||
* admin-gated paths so it never touches customer requests and never reads
|
||||
* the customer AuthService's session.
|
||||
*/
|
||||
export const adminAuthHeadersInterceptor = (req, next) => {
|
||||
const isAdminRequest = ADMIN_GATED_PATH_SEGMENTS.some(segment => req.url.includes(segment));
|
||||
if (!isAdminRequest) {
|
||||
return next(req);
|
||||
}
|
||||
const adminAuth = inject(AdminAuthService);
|
||||
const session = adminAuth.session();
|
||||
const token = adminAuth.getAdminToken();
|
||||
let headers = req.headers;
|
||||
if (session?.sessionId) {
|
||||
headers = headers.set('AdminWebSessionID', session.sessionId);
|
||||
}
|
||||
if (token) {
|
||||
headers = headers.set('Authorization', `Bearer ${token}`);
|
||||
}
|
||||
return next(req.clone({ headers }));
|
||||
};
|
||||
3
dist/telegram/admin-auth.guard.d.ts
vendored
Normal file
3
dist/telegram/admin-auth.guard.d.ts
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
import { CanActivateFn } from '@angular/router';
|
||||
/** Guards `/admin/**`-style routes. Never shares state with the customer auth guard/service. */
|
||||
export declare const adminAuthGuard: CanActivateFn;
|
||||
11
dist/telegram/admin-auth.guard.js
vendored
Normal file
11
dist/telegram/admin-auth.guard.js
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { AdminAuthService } from './admin-auth.service';
|
||||
/** Guards `/admin/**`-style routes. Never shares state with the customer auth guard/service. */
|
||||
export const adminAuthGuard = () => {
|
||||
const adminAuth = inject(AdminAuthService);
|
||||
if (adminAuth.isAuthenticated()) {
|
||||
return true;
|
||||
}
|
||||
adminAuth.requestLogin();
|
||||
return false;
|
||||
};
|
||||
44
dist/telegram/admin-auth.service.d.ts
vendored
Normal file
44
dist/telegram/admin-auth.service.d.ts
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
import { Observable } from 'rxjs';
|
||||
import { AdminAuthStatus, AuthSession, WebSessionStart } from './models/session.model';
|
||||
export declare class AdminAuthService {
|
||||
private readonly api;
|
||||
private readonly sessionSignal;
|
||||
private readonly statusSignal;
|
||||
private readonly showLoginSignal;
|
||||
readonly session: import("@angular/core").Signal<AuthSession | null>;
|
||||
readonly status: import("@angular/core").Signal<AdminAuthStatus>;
|
||||
readonly isAuthenticated: import("@angular/core").Signal<boolean>;
|
||||
readonly showLoginDialog: import("@angular/core").Signal<boolean>;
|
||||
readonly displayName: import("@angular/core").Signal<string | null>;
|
||||
private sessionCheckTimer?;
|
||||
constructor();
|
||||
checkSession(): void;
|
||||
/** Check session without mutating internal state beyond activating on success (used for polling). */
|
||||
checkSessionOnce(webSessionID?: string | null): Observable<AuthSession | null>;
|
||||
/** Create a backend web session - identical call to the customer login (TelegramSessionApiService.createSession). */
|
||||
createWebSession(): Observable<WebSessionStart>;
|
||||
getAdminAppLoginUrl(webSessionID: string): string;
|
||||
onLoginComplete(): void;
|
||||
requestLogin(): void;
|
||||
/**
|
||||
* Dev-only shortcut for local testing without a reachable Telegram/session
|
||||
* backend: fabricates a local session and activates it directly, skipping
|
||||
* the QR flow entirely. No-ops in production builds (checked via Angular's
|
||||
* isDevMode() at runtime, not just build-time, so it is safe even if this
|
||||
* code ships). Never call this from anywhere reachable in a production build.
|
||||
*/
|
||||
devBypassLogin(): void;
|
||||
hideLogin(): void;
|
||||
logout(): void;
|
||||
/** JWT pair storage, reserved for once the backend issues admin access/refresh tokens. Unused until then. */
|
||||
getAdminToken(): string | null;
|
||||
setAdminTokens(token: string, refreshToken: string): void;
|
||||
clearAdminTokens(): void;
|
||||
private activateSession;
|
||||
private clearAuthState;
|
||||
private scheduleSessionRefresh;
|
||||
private clearSessionRefresh;
|
||||
private getStoredAdminSessionID;
|
||||
private setStoredAdminSessionID;
|
||||
private clearStoredAdminSessionID;
|
||||
}
|
||||
188
dist/telegram/admin-auth.service.js
vendored
Normal file
188
dist/telegram/admin-auth.service.js
vendored
Normal file
@@ -0,0 +1,188 @@
|
||||
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
||||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
||||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
||||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
||||
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
||||
};
|
||||
import { Injectable, signal, computed, inject, isDevMode } from '@angular/core';
|
||||
import { tap } from 'rxjs';
|
||||
import { TelegramSessionApiService } from './telegram-session-api.service';
|
||||
/**
|
||||
* Admin login uses the exact same Telegram QR/session API as the customer
|
||||
* login (TelegramSessionApiService) - there is no separate admin backend
|
||||
* endpoint, and none should be invented client-side. Only the *storage* is
|
||||
* kept separate from AuthService, so an admin QR scan never authenticates
|
||||
* the customer session or vice versa: distinct cookie name, distinct
|
||||
* signals, distinct guard/interceptor.
|
||||
*
|
||||
* Since the session API itself has no concept of "admin", the frontend
|
||||
* cannot tell an admin Telegram session from a regular one. Actual admin
|
||||
* authorization must be enforced server-side when admin API calls are made
|
||||
* with the resulting session id - the frontend only decides where to
|
||||
* *store* the result.
|
||||
*/
|
||||
const ADMIN_SESSION_COOKIE = 'adminSessionID';
|
||||
const ADMIN_TOKEN_STORAGE_KEY = 'adminToken';
|
||||
const ADMIN_REFRESH_STORAGE_KEY = 'adminRefreshToken';
|
||||
const ADMIN_SESSION_COOKIE_MAX_AGE_SECONDS = 60 * 60;
|
||||
let AdminAuthService = class AdminAuthService {
|
||||
constructor() {
|
||||
this.api = inject(TelegramSessionApiService);
|
||||
this.sessionSignal = signal(null);
|
||||
this.statusSignal = signal('unknown');
|
||||
this.showLoginSignal = signal(false);
|
||||
this.session = this.sessionSignal.asReadonly();
|
||||
this.status = this.statusSignal.asReadonly();
|
||||
this.isAuthenticated = computed(() => this.statusSignal() === 'authenticated');
|
||||
this.showLoginDialog = this.showLoginSignal.asReadonly();
|
||||
this.displayName = computed(() => this.sessionSignal()?.displayName ?? null);
|
||||
this.checkSession();
|
||||
}
|
||||
checkSession() {
|
||||
const webSessionID = this.getStoredAdminSessionID();
|
||||
if (!webSessionID) {
|
||||
this.clearAuthState('unauthenticated');
|
||||
return;
|
||||
}
|
||||
this.statusSignal.set('checking');
|
||||
this.checkSessionOnce(webSessionID).subscribe(session => {
|
||||
if (!session?.active) {
|
||||
this.clearAuthState('unauthenticated');
|
||||
}
|
||||
});
|
||||
}
|
||||
/** Check session without mutating internal state beyond activating on success (used for polling). */
|
||||
checkSessionOnce(webSessionID = this.getStoredAdminSessionID()) {
|
||||
return this.api.checkSessionOnce(webSessionID).pipe(tap(session => {
|
||||
if (session?.active) {
|
||||
this.activateSession(session);
|
||||
}
|
||||
}));
|
||||
}
|
||||
/** Create a backend web session - identical call to the customer login (TelegramSessionApiService.createSession). */
|
||||
createWebSession() {
|
||||
return this.api.createSession();
|
||||
}
|
||||
getAdminAppLoginUrl(webSessionID) {
|
||||
return this.api.getBotAppLoginUrl(webSessionID);
|
||||
}
|
||||
onLoginComplete() {
|
||||
this.hideLogin();
|
||||
if (!this.isAuthenticated()) {
|
||||
this.checkSession();
|
||||
}
|
||||
}
|
||||
requestLogin() {
|
||||
this.showLoginSignal.set(true);
|
||||
}
|
||||
/**
|
||||
* Dev-only shortcut for local testing without a reachable Telegram/session
|
||||
* backend: fabricates a local session and activates it directly, skipping
|
||||
* the QR flow entirely. No-ops in production builds (checked via Angular's
|
||||
* isDevMode() at runtime, not just build-time, so it is safe even if this
|
||||
* code ships). Never call this from anywhere reachable in a production build.
|
||||
*/
|
||||
devBypassLogin() {
|
||||
if (!isDevMode()) {
|
||||
return;
|
||||
}
|
||||
this.hideLogin();
|
||||
this.activateSession({
|
||||
sessionId: `dev-bypass-${Date.now()}`,
|
||||
userId: 0,
|
||||
username: 'dev-admin',
|
||||
displayName: 'Dev Admin (local bypass)',
|
||||
active: true,
|
||||
expires: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
|
||||
});
|
||||
}
|
||||
hideLogin() {
|
||||
this.showLoginSignal.set(false);
|
||||
}
|
||||
logout() {
|
||||
const webSessionID = this.sessionSignal()?.sessionId || this.getStoredAdminSessionID();
|
||||
if (!webSessionID) {
|
||||
this.clearAuthState('unauthenticated');
|
||||
return;
|
||||
}
|
||||
this.api.logout(webSessionID).subscribe(() => this.clearAuthState('unauthenticated'));
|
||||
}
|
||||
/** JWT pair storage, reserved for once the backend issues admin access/refresh tokens. Unused until then. */
|
||||
getAdminToken() {
|
||||
return typeof localStorage === 'undefined' ? null : localStorage.getItem(ADMIN_TOKEN_STORAGE_KEY);
|
||||
}
|
||||
setAdminTokens(token, refreshToken) {
|
||||
if (typeof localStorage === 'undefined') {
|
||||
return;
|
||||
}
|
||||
localStorage.setItem(ADMIN_TOKEN_STORAGE_KEY, token);
|
||||
localStorage.setItem(ADMIN_REFRESH_STORAGE_KEY, refreshToken);
|
||||
}
|
||||
clearAdminTokens() {
|
||||
if (typeof localStorage === 'undefined') {
|
||||
return;
|
||||
}
|
||||
localStorage.removeItem(ADMIN_TOKEN_STORAGE_KEY);
|
||||
localStorage.removeItem(ADMIN_REFRESH_STORAGE_KEY);
|
||||
}
|
||||
activateSession(session) {
|
||||
this.sessionSignal.set(session);
|
||||
this.statusSignal.set('authenticated');
|
||||
this.setStoredAdminSessionID(session.sessionId);
|
||||
this.scheduleSessionRefresh(session.expires);
|
||||
}
|
||||
clearAuthState(status) {
|
||||
this.sessionSignal.set(null);
|
||||
this.statusSignal.set(status);
|
||||
this.clearStoredAdminSessionID();
|
||||
this.clearAdminTokens();
|
||||
this.clearSessionRefresh();
|
||||
}
|
||||
scheduleSessionRefresh(expiresAt) {
|
||||
this.clearSessionRefresh();
|
||||
const expiresMs = new Date(expiresAt).getTime();
|
||||
const nowMs = Date.now();
|
||||
const refreshIn = Number.isFinite(expiresMs)
|
||||
? Math.max(expiresMs - nowMs - 60_000, 30_000)
|
||||
: ADMIN_SESSION_COOKIE_MAX_AGE_SECONDS * 1000;
|
||||
this.sessionCheckTimer = setTimeout(() => this.checkSession(), refreshIn);
|
||||
}
|
||||
clearSessionRefresh() {
|
||||
if (this.sessionCheckTimer) {
|
||||
clearTimeout(this.sessionCheckTimer);
|
||||
this.sessionCheckTimer = undefined;
|
||||
}
|
||||
}
|
||||
getStoredAdminSessionID() {
|
||||
if (typeof document === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
const cookie = document.cookie.split('; ').find(row => row.startsWith(`${ADMIN_SESSION_COOKIE}=`));
|
||||
if (!cookie) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return decodeURIComponent(cookie.substring(ADMIN_SESSION_COOKIE.length + 1));
|
||||
}
|
||||
catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
setStoredAdminSessionID(webSessionID) {
|
||||
if (typeof document === 'undefined') {
|
||||
return;
|
||||
}
|
||||
const secure = typeof window !== 'undefined' && window.location.protocol === 'https:' ? '; Secure' : '';
|
||||
document.cookie = `${ADMIN_SESSION_COOKIE}=${encodeURIComponent(webSessionID)}; Max-Age=${ADMIN_SESSION_COOKIE_MAX_AGE_SECONDS}; Path=/; SameSite=Strict${secure}`;
|
||||
}
|
||||
clearStoredAdminSessionID() {
|
||||
if (typeof document === 'undefined') {
|
||||
return;
|
||||
}
|
||||
document.cookie = `${ADMIN_SESSION_COOKIE}=; Max-Age=0; Path=/; SameSite=Strict`;
|
||||
}
|
||||
};
|
||||
AdminAuthService = __decorate([
|
||||
Injectable({ providedIn: 'root' })
|
||||
], AdminAuthService);
|
||||
export { AdminAuthService };
|
||||
49
dist/telegram/auth.service.d.ts
vendored
Normal file
49
dist/telegram/auth.service.d.ts
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Observable } from 'rxjs';
|
||||
import { AuthSession, AuthStatus, WebSessionStart } from './models/session.model';
|
||||
/** Customer-facing Telegram QR/session auth. Distinct storage/state from AdminAuthService by design. */
|
||||
export declare class AuthService {
|
||||
private readonly api;
|
||||
private sessionSignal;
|
||||
private statusSignal;
|
||||
private showLoginSignal;
|
||||
/** Current auth session */
|
||||
readonly session: import("@angular/core").Signal<AuthSession | null>;
|
||||
/** Current auth status */
|
||||
readonly status: import("@angular/core").Signal<AuthStatus>;
|
||||
/** Whether user is fully authenticated */
|
||||
readonly isAuthenticated: import("@angular/core").Signal<boolean>;
|
||||
/** Whether to show login dialog */
|
||||
readonly showLoginDialog: import("@angular/core").Signal<boolean>;
|
||||
/** Display name of authenticated user */
|
||||
readonly displayName: import("@angular/core").Signal<string | null>;
|
||||
private sessionCheckTimer?;
|
||||
constructor();
|
||||
/** Check the current webSessionID cookie against the auth backend. */
|
||||
checkSession(): void;
|
||||
/** Check session without updating internal state beyond activating on success (used for polling). */
|
||||
checkSessionOnce(webSessionID?: string | null): Observable<AuthSession | null>;
|
||||
/**
|
||||
* Called after user completes Telegram login.
|
||||
*/
|
||||
onTelegramLoginComplete(): void;
|
||||
/** Generate the Telegram login URL for bot-based auth */
|
||||
getTelegramLoginUrl(webSessionID: string): string;
|
||||
/** Generate a Telegram app deep link for mobile login without opening a browser tab. */
|
||||
getTelegramAppLoginUrl(webSessionID: string): string;
|
||||
/** Create a backend web session and return the Telegram start link for it. */
|
||||
createWebSession(): Observable<WebSessionStart>;
|
||||
/** Show login dialog (called when user tries to pay without being logged in) */
|
||||
requestLogin(): void;
|
||||
/** Hide login dialog */
|
||||
hideLogin(): void;
|
||||
/** Logout — clears session on backend and locally */
|
||||
logout(): void;
|
||||
private activateSession;
|
||||
private clearAuthState;
|
||||
/** Schedule a session re-check before it expires */
|
||||
private scheduleSessionRefresh;
|
||||
private clearSessionRefresh;
|
||||
private getStoredWebSessionID;
|
||||
private setStoredWebSessionID;
|
||||
private clearStoredWebSessionID;
|
||||
}
|
||||
161
dist/telegram/auth.service.js
vendored
Normal file
161
dist/telegram/auth.service.js
vendored
Normal file
@@ -0,0 +1,161 @@
|
||||
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
||||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
||||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
||||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
||||
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
||||
};
|
||||
import { Injectable, signal, computed, inject } from '@angular/core';
|
||||
import { tap } from 'rxjs';
|
||||
import { TelegramSessionApiService } from './telegram-session-api.service';
|
||||
const WEB_SESSION_COOKIE = 'webSessionID';
|
||||
const WEB_SESSION_COOKIE_MAX_AGE_SECONDS = 60 * 60;
|
||||
/** Customer-facing Telegram QR/session auth. Distinct storage/state from AdminAuthService by design. */
|
||||
let AuthService = class AuthService {
|
||||
constructor() {
|
||||
this.api = inject(TelegramSessionApiService);
|
||||
this.sessionSignal = signal(null);
|
||||
this.statusSignal = signal('unknown');
|
||||
this.showLoginSignal = signal(false);
|
||||
/** Current auth session */
|
||||
this.session = this.sessionSignal.asReadonly();
|
||||
/** Current auth status */
|
||||
this.status = this.statusSignal.asReadonly();
|
||||
/** Whether user is fully authenticated */
|
||||
this.isAuthenticated = computed(() => this.statusSignal() === 'authenticated');
|
||||
/** Whether to show login dialog */
|
||||
this.showLoginDialog = this.showLoginSignal.asReadonly();
|
||||
/** Display name of authenticated user */
|
||||
this.displayName = computed(() => this.sessionSignal()?.displayName ?? null);
|
||||
// On init, check existing session via cookie
|
||||
this.checkSession();
|
||||
}
|
||||
/** Check the current webSessionID cookie against the auth backend. */
|
||||
checkSession() {
|
||||
const webSessionID = this.getStoredWebSessionID();
|
||||
if (!webSessionID) {
|
||||
this.clearAuthState('unauthenticated');
|
||||
return;
|
||||
}
|
||||
this.statusSignal.set('checking');
|
||||
this.checkSessionOnce(webSessionID).subscribe(session => {
|
||||
if (!session?.active) {
|
||||
this.clearAuthState('unauthenticated');
|
||||
}
|
||||
});
|
||||
}
|
||||
/** Check session without updating internal state beyond activating on success (used for polling). */
|
||||
checkSessionOnce(webSessionID = this.getStoredWebSessionID()) {
|
||||
return this.api.checkSessionOnce(webSessionID).pipe(tap(session => {
|
||||
if (session?.active) {
|
||||
this.activateSession(session);
|
||||
}
|
||||
}));
|
||||
}
|
||||
/**
|
||||
* Called after user completes Telegram login.
|
||||
*/
|
||||
onTelegramLoginComplete() {
|
||||
this.hideLogin();
|
||||
if (!this.isAuthenticated()) {
|
||||
this.checkSession();
|
||||
}
|
||||
}
|
||||
/** Generate the Telegram login URL for bot-based auth */
|
||||
getTelegramLoginUrl(webSessionID) {
|
||||
return this.api.getBotLoginUrl(webSessionID);
|
||||
}
|
||||
/** Generate a Telegram app deep link for mobile login without opening a browser tab. */
|
||||
getTelegramAppLoginUrl(webSessionID) {
|
||||
return this.api.getBotAppLoginUrl(webSessionID);
|
||||
}
|
||||
/** Create a backend web session and return the Telegram start link for it. */
|
||||
createWebSession() {
|
||||
return this.api.createSession();
|
||||
}
|
||||
/** Show login dialog (called when user tries to pay without being logged in) */
|
||||
requestLogin() {
|
||||
this.showLoginSignal.set(true);
|
||||
}
|
||||
/** Hide login dialog */
|
||||
hideLogin() {
|
||||
this.showLoginSignal.set(false);
|
||||
}
|
||||
/** Logout — clears session on backend and locally */
|
||||
logout() {
|
||||
const webSessionID = this.sessionSignal()?.sessionId || this.getStoredWebSessionID();
|
||||
if (!webSessionID) {
|
||||
this.clearAuthState('unauthenticated');
|
||||
return;
|
||||
}
|
||||
this.api.logout(webSessionID).subscribe(() => {
|
||||
this.clearAuthState('unauthenticated');
|
||||
});
|
||||
}
|
||||
activateSession(session) {
|
||||
this.sessionSignal.set(session);
|
||||
this.statusSignal.set('authenticated');
|
||||
this.setStoredWebSessionID(session.sessionId);
|
||||
this.scheduleSessionRefresh(session.expires);
|
||||
}
|
||||
clearAuthState(status) {
|
||||
this.sessionSignal.set(null);
|
||||
this.statusSignal.set(status);
|
||||
this.clearStoredWebSessionID();
|
||||
this.clearSessionRefresh();
|
||||
}
|
||||
/** Schedule a session re-check before it expires */
|
||||
scheduleSessionRefresh(expiresAt) {
|
||||
this.clearSessionRefresh();
|
||||
const expiresMs = new Date(expiresAt).getTime();
|
||||
const nowMs = Date.now();
|
||||
// Re-check 60 seconds before expiry, minimum 30s from now
|
||||
const refreshIn = Number.isFinite(expiresMs)
|
||||
? Math.max(expiresMs - nowMs - 60_000, 30_000)
|
||||
: WEB_SESSION_COOKIE_MAX_AGE_SECONDS * 1000;
|
||||
this.sessionCheckTimer = setTimeout(() => {
|
||||
this.checkSession();
|
||||
}, refreshIn);
|
||||
}
|
||||
clearSessionRefresh() {
|
||||
if (this.sessionCheckTimer) {
|
||||
clearTimeout(this.sessionCheckTimer);
|
||||
this.sessionCheckTimer = undefined;
|
||||
}
|
||||
}
|
||||
getStoredWebSessionID() {
|
||||
if (typeof document === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
const cookie = document.cookie
|
||||
.split('; ')
|
||||
.find(row => row.startsWith(`${WEB_SESSION_COOKIE}=`));
|
||||
if (!cookie) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return decodeURIComponent(cookie.substring(WEB_SESSION_COOKIE.length + 1));
|
||||
}
|
||||
catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
setStoredWebSessionID(webSessionID) {
|
||||
if (typeof document === 'undefined') {
|
||||
return;
|
||||
}
|
||||
const secure = typeof window !== 'undefined' && window.location.protocol === 'https:' ? '; Secure' : '';
|
||||
document.cookie = `${WEB_SESSION_COOKIE}=${encodeURIComponent(webSessionID)}; Max-Age=${WEB_SESSION_COOKIE_MAX_AGE_SECONDS}; Path=/; SameSite=Lax${secure}`;
|
||||
}
|
||||
clearStoredWebSessionID() {
|
||||
if (typeof document === 'undefined') {
|
||||
return;
|
||||
}
|
||||
document.cookie = `${WEB_SESSION_COOKIE}=; Max-Age=0; Path=/; SameSite=Lax`;
|
||||
}
|
||||
};
|
||||
AuthService = __decorate([
|
||||
Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
], AuthService);
|
||||
export { AuthService };
|
||||
14
dist/telegram/models/session.model.d.ts
vendored
Normal file
14
dist/telegram/models/session.model.d.ts
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
export interface AuthSession {
|
||||
sessionId: string;
|
||||
userId: number | null;
|
||||
username: string | null;
|
||||
displayName: string;
|
||||
active: boolean;
|
||||
expires: string;
|
||||
}
|
||||
export interface WebSessionStart {
|
||||
webSessionID: string;
|
||||
url: string;
|
||||
}
|
||||
export type AuthStatus = 'unknown' | 'checking' | 'authenticated' | 'expired' | 'unauthenticated';
|
||||
export type AdminAuthStatus = 'unknown' | 'checking' | 'authenticated' | 'expired' | 'unauthenticated';
|
||||
1
dist/telegram/models/session.model.js
vendored
Normal file
1
dist/telegram/models/session.model.js
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
28
dist/telegram/telegram-session-api.service.d.ts
vendored
Normal file
28
dist/telegram/telegram-session-api.service.d.ts
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
import { Observable } from 'rxjs';
|
||||
import { AuthSession, WebSessionStart } from './models/session.model';
|
||||
/**
|
||||
* The one Telegram QR/session API (`{authApiUrl}/users/sessions`). Customer
|
||||
* login (AuthService) and admin login (AdminAuthService) both call this same
|
||||
* service against this same endpoint - there is no separate admin backend.
|
||||
* This class only does the HTTP call + response normalization; it holds no
|
||||
* session state and writes no cookies, so each caller manages its own
|
||||
* storage/signals independently on top of it.
|
||||
*/
|
||||
export declare class TelegramSessionApiService {
|
||||
private readonly http;
|
||||
private readonly authApiUrl;
|
||||
private readonly telegramBotUsername;
|
||||
createSession(): Observable<WebSessionStart>;
|
||||
checkSessionOnce(webSessionID: string | null): Observable<AuthSession | null>;
|
||||
logout(webSessionID: string): Observable<unknown>;
|
||||
getBotLoginUrl(webSessionID: string): string;
|
||||
getBotAppLoginUrl(webSessionID: string): string;
|
||||
private getBotUsername;
|
||||
private normalizeWebSession;
|
||||
private extractSessionId;
|
||||
private readFirst;
|
||||
private readString;
|
||||
private readNumber;
|
||||
private asRecord;
|
||||
private isActiveStatus;
|
||||
}
|
||||
137
dist/telegram/telegram-session-api.service.js
vendored
Normal file
137
dist/telegram/telegram-session-api.service.js
vendored
Normal file
@@ -0,0 +1,137 @@
|
||||
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
||||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
||||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
||||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
||||
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
||||
};
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { of, catchError, map } from 'rxjs';
|
||||
import { AUTH_API_URL, TELEGRAM_BOT_USERNAME } from '../config';
|
||||
import { generateGuid } from '../util/guid.util';
|
||||
const SESSION_MAX_AGE_SECONDS = 60 * 60;
|
||||
const DEFAULT_TELEGRAM_BOT_USERNAME = 'DexarSupport_bot';
|
||||
/**
|
||||
* The one Telegram QR/session API (`{authApiUrl}/users/sessions`). Customer
|
||||
* login (AuthService) and admin login (AdminAuthService) both call this same
|
||||
* service against this same endpoint - there is no separate admin backend.
|
||||
* This class only does the HTTP call + response normalization; it holds no
|
||||
* session state and writes no cookies, so each caller manages its own
|
||||
* storage/signals independently on top of it.
|
||||
*/
|
||||
let TelegramSessionApiService = class TelegramSessionApiService {
|
||||
constructor() {
|
||||
this.http = inject(HttpClient);
|
||||
this.authApiUrl = inject(AUTH_API_URL);
|
||||
this.telegramBotUsername = inject(TELEGRAM_BOT_USERNAME, { optional: true });
|
||||
}
|
||||
createSession() {
|
||||
const webSessionID = generateGuid();
|
||||
return this.http.post(`${this.authApiUrl}/users/sessions`, { webSessionID }, { headers: { WebSessionID: webSessionID } }).pipe(map(response => {
|
||||
const responseWebSessionID = this.extractSessionId(response, webSessionID);
|
||||
return {
|
||||
webSessionID: responseWebSessionID,
|
||||
url: this.getBotLoginUrl(responseWebSessionID),
|
||||
};
|
||||
}));
|
||||
}
|
||||
checkSessionOnce(webSessionID) {
|
||||
if (!webSessionID) {
|
||||
return of(null);
|
||||
}
|
||||
return this.http.get(`${this.authApiUrl}/users/sessions/${encodeURIComponent(webSessionID)}`).pipe(map(response => this.normalizeWebSession(response, webSessionID)), catchError(() => of(null)));
|
||||
}
|
||||
logout(webSessionID) {
|
||||
return this.http.delete(`${this.authApiUrl}/users/sessions/${encodeURIComponent(webSessionID)}`, {
|
||||
headers: { WebSessionID: webSessionID }
|
||||
}).pipe(catchError(() => of(null)));
|
||||
}
|
||||
getBotLoginUrl(webSessionID) {
|
||||
return `https://t.me/${this.getBotUsername()}?start=${encodeURIComponent(webSessionID)}`;
|
||||
}
|
||||
getBotAppLoginUrl(webSessionID) {
|
||||
return `tg://resolve?domain=${encodeURIComponent(this.getBotUsername())}&start=${encodeURIComponent(webSessionID)}`;
|
||||
}
|
||||
getBotUsername() {
|
||||
return this.telegramBotUsername || DEFAULT_TELEGRAM_BOT_USERNAME;
|
||||
}
|
||||
normalizeWebSession(response, fallbackSessionId) {
|
||||
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() + SESSION_MAX_AGE_SECONDS * 1000).toISOString();
|
||||
return { sessionId, userId: telegramUserId, username, displayName, active, expires: expiresAt };
|
||||
}
|
||||
extractSessionId(response, fallbackSessionId) {
|
||||
if (!response) {
|
||||
return fallbackSessionId;
|
||||
}
|
||||
return this.readString(this.readFirst(response, [
|
||||
'webSessionID', 'WebSessionID', 'webSessionId', 'sessionID', 'SessionID', 'sessionId', 'id', 'ID'
|
||||
])) ?? fallbackSessionId;
|
||||
}
|
||||
readFirst(source, keys) {
|
||||
for (const key of keys) {
|
||||
if (Object.prototype.hasOwnProperty.call(source, key)) {
|
||||
return source[key];
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
readString(value) {
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === 'number' || typeof value === 'bigint') {
|
||||
return value.toString();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
readNumber(value) {
|
||||
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;
|
||||
}
|
||||
asRecord(value) {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||
? value
|
||||
: null;
|
||||
}
|
||||
isActiveStatus(status) {
|
||||
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());
|
||||
}
|
||||
};
|
||||
TelegramSessionApiService = __decorate([
|
||||
Injectable({ providedIn: 'root' })
|
||||
], TelegramSessionApiService);
|
||||
export { TelegramSessionApiService };
|
||||
Reference in New Issue
Block a user