feat(auth): login screen and domain-scoped navigation
Session login against /auth/*, with a guard on every route and an interceptor that returns to the login on 401. The header, the import workspace and both governance panels only offer the account's own domains (auth/dominios.ts), and a batch opens on the account's database. The sign-in screen follows the app's palette: logo above the title, the action button in the shared tokens, and no register or password-recovery rows.
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
|
||||
import { Injectable, computed, inject, signal } from '@angular/core';
|
||||
import { Observable, catchError, of, shareReplay, tap, throwError } from 'rxjs';
|
||||
|
||||
/** El usuario de la sesión, tal como lo devuelve `/auth/me` y `/auth/login`. */
|
||||
export interface Usuario {
|
||||
readonly usuario: string;
|
||||
readonly nombre: string;
|
||||
/** Dominios que esta cuenta puede ver: `cacu`, `cama`, `tea` (los tres para el administrador). */
|
||||
readonly dominios: readonly string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Única fuente de verdad de la sesión: el guard pregunta aquí si hay sesión y
|
||||
* el interceptor la limpia cuando el servidor responde 401.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AuthService {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly usuarioActual = signal<Usuario | null>(null);
|
||||
private consulta: Observable<Usuario | null> | null = null;
|
||||
|
||||
readonly usuario = this.usuarioActual.asReadonly();
|
||||
readonly autenticado = computed(() => this.usuarioActual() !== null);
|
||||
|
||||
/**
|
||||
* Si la cuenta puede ver ese dominio. Mientras la sesión no está resuelta no
|
||||
* se opina (devuelve `true`): los guards son los que deciden el acceso, y un
|
||||
* store construido antes de `/auth/me` no debe quedarse sin dominios.
|
||||
*/
|
||||
puedeVer(dominio: string): boolean {
|
||||
const sesion = this.usuarioActual();
|
||||
return sesion ? sesion.dominios.includes(dominio) : true;
|
||||
}
|
||||
|
||||
/**
|
||||
* La sesión del servidor (`GET /auth/me`), consultada una sola vez por
|
||||
* ejecución: el guard corre en cada navegación y no debe multiplicar la
|
||||
* petición. Un 401 significa «no hay sesión», no un error de la aplicación.
|
||||
*/
|
||||
sesion(): Observable<Usuario | null> {
|
||||
const actual = this.usuarioActual();
|
||||
if (actual) return of(actual);
|
||||
this.consulta ??= this.http.get<Usuario>('/auth/me').pipe(
|
||||
tap((usuario) => this.usuarioActual.set(usuario)),
|
||||
catchError((error: HttpErrorResponse) => (error.status === 401 ? of(null) : throwError(() => error))),
|
||||
shareReplay({ bufferSize: 1, refCount: false }),
|
||||
);
|
||||
return this.consulta;
|
||||
}
|
||||
|
||||
/** `POST /auth/login`; el 401 llega tal cual para que el formulario lo muestre. */
|
||||
login(usuario: string, contrasena: string): Observable<Usuario> {
|
||||
return this.http
|
||||
.post<Usuario>('/auth/login', { usuario, contrasena })
|
||||
.pipe(tap((sesion) => this.establecer(sesion)));
|
||||
}
|
||||
|
||||
/** `POST /auth/logout`: la sesión ya vencida también limpia el cliente. */
|
||||
logout(): Observable<void> {
|
||||
return this.http.post<void>('/auth/logout', {}).pipe(
|
||||
catchError((error: HttpErrorResponse) => (error.status === 401 ? of(undefined) : throwError(() => error))),
|
||||
tap(() => this.limpiar()),
|
||||
);
|
||||
}
|
||||
|
||||
limpiar(): void {
|
||||
this.usuarioActual.set(null);
|
||||
this.consulta = of(null);
|
||||
}
|
||||
|
||||
private establecer(usuario: Usuario): void {
|
||||
this.usuarioActual.set(usuario);
|
||||
this.consulta = of(usuario);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user