83 lines
3.1 KiB
TypeScript
83 lines
3.1 KiB
TypeScript
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
|
|
import { Injectable, computed, inject, signal } from '@angular/core';
|
|
import { CanActivateFn, Router } from '@angular/router';
|
|
import { firstValueFrom } from 'rxjs';
|
|
import { ApiConfiguration } from '../api/api-configuration';
|
|
import type { Domain } from '../api/models/domain';
|
|
|
|
/** Who is signed in, and the domains the app shows them. */
|
|
export interface User {
|
|
id: string;
|
|
email: string;
|
|
name: string;
|
|
is_superuser: boolean;
|
|
domains: Domain[];
|
|
}
|
|
|
|
/** The web app's sign-in (the API's fastapi-users, a session cookie). It decides only what
|
|
* the app shows: the API answers without a session. */
|
|
@Injectable({ providedIn: 'root' })
|
|
export class Auth {
|
|
private readonly http = inject(HttpClient);
|
|
private readonly root = inject(ApiConfiguration).rootUrl;
|
|
/** undefined: not asked yet; null: nobody signed in. */
|
|
private readonly current = signal<User | null | undefined>(undefined);
|
|
readonly user = this.current.asReadonly();
|
|
readonly signedIn = computed(() => !!this.current());
|
|
|
|
/** Whether the signed-in user may see the domain (an administrator sees every one). */
|
|
canSee(domain: string): boolean {
|
|
const u = this.current();
|
|
return !!u && (u.is_superuser || u.domains.includes(domain as Domain));
|
|
}
|
|
|
|
async load(): Promise<User | null> {
|
|
try {
|
|
this.current.set(await firstValueFrom(this.http.get<User>(`${this.root}/users/me`)));
|
|
} catch {
|
|
this.current.set(null);
|
|
}
|
|
return this.current() ?? null;
|
|
}
|
|
|
|
/** Signs in; a wrong user or password comes back as words for the form. */
|
|
async login(email: string, password: string): Promise<string | null> {
|
|
const body = new HttpParams().set('username', email.trim()).set('password', password);
|
|
try {
|
|
await firstValueFrom(this.http.post(`${this.root}/auth/login`, body));
|
|
} catch (e) {
|
|
if (e instanceof HttpErrorResponse && e.status === 400) {
|
|
return 'Usuario o contraseña incorrectos.';
|
|
}
|
|
return 'No hay conexión con la plataforma. Intente de nuevo.';
|
|
}
|
|
await this.load();
|
|
return null;
|
|
}
|
|
|
|
async logout(): Promise<void> {
|
|
try {
|
|
await firstValueFrom(this.http.post(`${this.root}/auth/logout`, null));
|
|
} finally {
|
|
this.current.set(null);
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Pages show only to someone signed in; the others go to the sign-in page and come back. */
|
|
export const signedIn: CanActivateFn = async (_route, state) => {
|
|
const auth = inject(Auth);
|
|
const router = inject(Router); // before any await: inject works only in the guard's first turn
|
|
const user = auth.user() === undefined ? await auth.load() : auth.user();
|
|
return user ? true : router.createUrlTree(['/login'], { queryParams: { next: state.url } });
|
|
};
|
|
|
|
/** A domain's pages show only to whom may see it. */
|
|
export const domainAllowed: CanActivateFn = (route) => {
|
|
const auth = inject(Auth);
|
|
const domain = route.paramMap.get('domain');
|
|
if (!domain || auth.canSee(domain)) return true;
|
|
const first = auth.user()?.domains[0];
|
|
return inject(Router).createUrlTree(first ? ['/indicadores', first] : ['/login']);
|
|
};
|