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,22 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { map } from 'rxjs';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
/**
|
||||
* Sin sesión no hay ruta protegida: se manda al inicio de sesión y se recuerda
|
||||
* `returnUrl` para volver a donde iba el usuario.
|
||||
*/
|
||||
export const authGuard: CanActivateFn = (_ruta, estado) => {
|
||||
const auth = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
return auth
|
||||
.sesion()
|
||||
.pipe(
|
||||
map(
|
||||
(usuario) =>
|
||||
usuario !== null ||
|
||||
router.createUrlTree(['/login'], { queryParams: { returnUrl: estado.url } }),
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
|
||||
import { inject } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { catchError, throwError } from 'rxjs';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
/**
|
||||
* Una sesión vencida aparece como 401 en cualquier llamada: se limpia el
|
||||
* cliente y se regresa al inicio de sesión. Las rutas `/auth/*` se excluyen
|
||||
* para no ciclar sobre el propio formulario, que ya muestra su error.
|
||||
*/
|
||||
export const authInterceptor: HttpInterceptorFn = (peticion, siguiente) => {
|
||||
const auth = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
return siguiente(peticion).pipe(
|
||||
catchError((error: unknown) => {
|
||||
const vencida =
|
||||
error instanceof HttpErrorResponse && error.status === 401 && !peticion.url.startsWith('/auth/');
|
||||
if (vencida) {
|
||||
auth.limpiar();
|
||||
const destino = router.url.startsWith('/login') ? undefined : router.url;
|
||||
void router.navigate(['/login'], { queryParams: destino ? { returnUrl: destino } : {} });
|
||||
}
|
||||
return throwError(() => error);
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,70 @@
|
||||
// El servicio es la única fuente de verdad de la sesión: el guard decide con su
|
||||
// señal y el interceptor la limpia en un 401. Estas pruebas fijan el contrato
|
||||
// con /auth/* (qué código significa «sin sesión» y qué queda en la señal) para
|
||||
// que un cambio de backend no rompa la interfaz en silencio.
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let http: HttpTestingController;
|
||||
let auth: AuthService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
auth = TestBed.inject(AuthService);
|
||||
});
|
||||
|
||||
afterEach(() => http.verify());
|
||||
|
||||
it('un 401 de /auth/me es «sin sesión», no un error, y la consulta se hace una sola vez', () => {
|
||||
const recibidos: (unknown)[] = [];
|
||||
auth.sesion().subscribe((usuario) => recibidos.push(usuario));
|
||||
auth.sesion().subscribe((usuario) => recibidos.push(usuario));
|
||||
|
||||
http.expectOne('/auth/me').flush({ error: 'sin sesión' }, { status: 401, statusText: 'Unauthorized' });
|
||||
|
||||
expect(recibidos).toEqual([null, null]);
|
||||
expect(auth.autenticado()).toBe(false);
|
||||
});
|
||||
|
||||
it('el login correcto deja al usuario en la señal', () => {
|
||||
auth.login('analista', 'clave-secreta').subscribe();
|
||||
http.expectOne('/auth/login').flush({ usuario: 'analista', nombre: 'Ana', dominios: ['cama'] });
|
||||
|
||||
expect(auth.usuario()).toEqual({ usuario: 'analista', nombre: 'Ana', dominios: ['cama'] });
|
||||
expect(auth.autenticado()).toBe(true);
|
||||
});
|
||||
|
||||
it('dice qué dominios puede ver la cuenta', () => {
|
||||
// Fails if the header or a guard starts offering a domain the server will reject.
|
||||
auth.login('analista', 'clave-secreta').subscribe();
|
||||
http.expectOne('/auth/login').flush({ usuario: 'analista', nombre: 'Ana', dominios: ['cama'] });
|
||||
|
||||
expect(auth.puedeVer('cama')).toBe(true);
|
||||
expect(auth.puedeVer('cacu')).toBe(false);
|
||||
expect(auth.puedeVer('tea')).toBe(false);
|
||||
});
|
||||
|
||||
it('el login rechazado deja el error al formulario y no abre sesión', () => {
|
||||
let codigo = 0;
|
||||
auth.login('analista', 'otra').subscribe({ error: (error) => (codigo = error.status) });
|
||||
http.expectOne('/auth/login').flush({ error: 'usuario o contraseña incorrectos' }, { status: 401, statusText: 'Unauthorized' });
|
||||
|
||||
expect(codigo).toBe(401);
|
||||
expect(auth.autenticado()).toBe(false);
|
||||
});
|
||||
|
||||
it('cerrar sesión limpia al usuario aunque el servidor ya la hubiera vencido', () => {
|
||||
auth.login('analista', 'clave-secreta').subscribe();
|
||||
http.expectOne('/auth/login').flush({ usuario: 'analista', nombre: 'Ana', dominios: ['cama'] });
|
||||
|
||||
auth.logout().subscribe();
|
||||
http.expectOne('/auth/logout').flush({ error: 'sin sesión' }, { status: 401, statusText: 'Unauthorized' });
|
||||
|
||||
expect(auth.autenticado()).toBe(false);
|
||||
expect(auth.usuario()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { map } from 'rxjs';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
/**
|
||||
* Cada cuenta ve solo sus dominios: una ruta con `data.dominio` ajeno manda a la
|
||||
* cuenta a su primer dominio. Sin sesión no decide nada (`authGuard` ya la
|
||||
* mandó al inicio de sesión).
|
||||
*/
|
||||
export const dominioGuard: CanActivateFn = (ruta) => {
|
||||
const auth = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
const pedido = ruta.data?.['dominio'] as string | undefined;
|
||||
return auth.sesion().pipe(
|
||||
map((usuario) => {
|
||||
if (!usuario || !pedido || usuario.dominios.includes(pedido)) return true;
|
||||
const propio = usuario.dominios[0];
|
||||
return propio ? router.createUrlTree(['/indicadores', propio]) : router.createUrlTree(['/']);
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
/**
|
||||
* Helpers for the screens that list domains (cargar información, gobernanza):
|
||||
* an account only ever sees its own, and «Todos» only belongs to one that
|
||||
* reaches every domain — the administrator.
|
||||
*/
|
||||
|
||||
/** De la lista dada, las entradas cuyo dominio alcanza la cuenta. */
|
||||
export function dominiosPermitidos<T extends { id: string }>(auth: AuthService, dominios: readonly T[]): T[] {
|
||||
return dominios.filter((dominio) => auth.puedeVer(dominio.id));
|
||||
}
|
||||
|
||||
/** Si la cuenta alcanza todos: solo entonces tiene sentido ofrecer «Todos». */
|
||||
export function alcanzaTodos(auth: AuthService, dominios: readonly { id: string }[]): boolean {
|
||||
return dominios.every((dominio) => auth.puedeVer(dominio.id));
|
||||
}
|
||||
|
||||
/**
|
||||
* El dominio con el que abre una pantalla: el único que alcanza la cuenta, o
|
||||
* `null` («Todos») cuando alcanza varios. Sin sesión resuelta devuelve `null`,
|
||||
* que es el comportamiento de siempre.
|
||||
*/
|
||||
export function dominioInicial<T extends string>(auth: AuthService, dominios: readonly { id: T }[]): T | null {
|
||||
const propios = dominiosPermitidos(auth, dominios);
|
||||
return propios.length === 1 ? propios[0].id : null;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<section class="login" aria-labelledby="login-titulo">
|
||||
<div class="login__caja">
|
||||
<img class="login__logo" src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
||||
|
||||
<h1 class="login__titulo" id="login-titulo">Inicio de sesión</h1>
|
||||
|
||||
<form class="login__formulario" (ngSubmit)="ingresar()" novalidate>
|
||||
<mat-form-field appearance="outline" class="login__campo" subscriptSizing="dynamic">
|
||||
<input
|
||||
matInput
|
||||
name="usuario"
|
||||
[(ngModel)]="usuario"
|
||||
placeholder="Usuario"
|
||||
aria-label="Usuario"
|
||||
autocomplete="username"
|
||||
autocapitalize="none"
|
||||
spellcheck="false"
|
||||
/>
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field appearance="outline" class="login__campo" subscriptSizing="dynamic">
|
||||
<input
|
||||
matInput
|
||||
name="contrasena"
|
||||
[(ngModel)]="contrasena"
|
||||
[type]="verContrasena() ? 'text' : 'password'"
|
||||
placeholder="Contraseña"
|
||||
aria-label="Contraseña"
|
||||
autocomplete="current-password"
|
||||
/>
|
||||
<button
|
||||
mat-icon-button
|
||||
matSuffix
|
||||
type="button"
|
||||
class="login__ojo"
|
||||
(click)="mostrarContrasena()"
|
||||
[attr.aria-label]="verContrasena() ? 'Ocultar contraseña' : 'Mostrar contraseña'"
|
||||
[attr.aria-pressed]="verContrasena()"
|
||||
>
|
||||
<mat-icon>{{ verContrasena() ? 'visibility_off' : 'visibility' }}</mat-icon>
|
||||
</button>
|
||||
</mat-form-field>
|
||||
|
||||
@if (error(); as mensaje) {
|
||||
<p class="login__error" role="alert">{{ mensaje }}</p>
|
||||
}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
class="login__ingresar"
|
||||
[disabled]="!usuario.trim() || !contrasena || enviando()"
|
||||
>
|
||||
{{ enviando() ? 'Ingresando…' : 'Ingresar' }}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p class="login__legal">©{{ anio }} Todos los derechos reservados.</p>
|
||||
</div>
|
||||
</section>
|
||||
@@ -0,0 +1,170 @@
|
||||
:host {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
/* The button borrows the home actions' palette: white with a thin gray border
|
||||
until the form is complete, then `--color-action` (see styles.scss). */
|
||||
--login-fondo: #f8f9fa;
|
||||
--login-borde: #e9ecef;
|
||||
}
|
||||
|
||||
.login {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex: 1;
|
||||
justify-content: center;
|
||||
/* The whole block sits a little below the middle: the logo above it gives the screen its weight. */
|
||||
padding: var(--space-9) var(--space-5) var(--space-8);
|
||||
}
|
||||
|
||||
.login__caja {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-4);
|
||||
max-width: 340px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* The brand opens the screen and is the biggest thing on it: it is what fills the empty space. */
|
||||
.login__logo {
|
||||
align-self: center;
|
||||
display: block;
|
||||
margin-bottom: 0;
|
||||
width: 260px;
|
||||
animation: login-logo-entrada 600ms ease-out both;
|
||||
}
|
||||
|
||||
@keyframes login-logo-entrada {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-8px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.login__logo {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
.login__titulo {
|
||||
align-items: center;
|
||||
color: var(--color-text);
|
||||
display: flex;
|
||||
font-family: var(--font-heading);
|
||||
font-size: 1.375rem;
|
||||
font-weight: 600;
|
||||
gap: var(--space-4);
|
||||
margin: 0 0 var(--space-2);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* The two rules that flank the title, as in the reference screen. */
|
||||
.login__titulo::before,
|
||||
.login__titulo::after {
|
||||
background: var(--color-border);
|
||||
content: '';
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
}
|
||||
|
||||
.login__formulario {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.login__campo {
|
||||
width: 100%;
|
||||
--mat-form-field-container-height: 44px;
|
||||
--mat-form-field-container-vertical-padding: 12px;
|
||||
}
|
||||
|
||||
.login__ojo {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
/* Edge paints its own reveal control over the password field; the eye in the field is ours. */
|
||||
.login__campo input::-ms-reveal,
|
||||
.login__campo input::-ms-clear {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.login__error {
|
||||
color: var(--mat-sys-error);
|
||||
font-size: 0.875rem;
|
||||
margin: calc(-1 * var(--space-1)) 0 0;
|
||||
}
|
||||
|
||||
/* The button shares the fields' width: one column, one border, no icon and no underline.
|
||||
Its border turns teal when the form is complete, and it fades in instead of switching. */
|
||||
.login__ingresar {
|
||||
align-items: center;
|
||||
background: var(--login-fondo);
|
||||
border: 1px solid var(--login-borde);
|
||||
border-radius: 10px;
|
||||
color: var(--color-text-secondary);
|
||||
cursor: default;
|
||||
display: flex;
|
||||
font: inherit;
|
||||
font-size: 0.9375rem;
|
||||
font-weight: 500;
|
||||
justify-content: center;
|
||||
margin-top: var(--space-2);
|
||||
min-height: 46px;
|
||||
padding: 0 var(--space-5);
|
||||
text-decoration: none;
|
||||
transition:
|
||||
background-color 260ms ease,
|
||||
border-color 260ms ease,
|
||||
color 260ms ease;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.login__ingresar:not(:disabled) {
|
||||
border-color: var(--color-action);
|
||||
color: var(--color-text);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.login__ingresar:hover:not(:disabled) {
|
||||
background: var(--color-action-hover);
|
||||
border-color: var(--color-action);
|
||||
}
|
||||
|
||||
.login__ingresar:focus-visible {
|
||||
outline: 2px solid var(--color-action);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.login__ingresar:disabled {
|
||||
background: var(--login-fondo);
|
||||
border-color: var(--login-borde);
|
||||
}
|
||||
|
||||
.login__legal {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 0.8125rem;
|
||||
margin: var(--space-4) 0 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.login {
|
||||
padding: var(--space-7) var(--space-4);
|
||||
}
|
||||
|
||||
.login__caja {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.login__logo {
|
||||
width: 208px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Component, OnInit, inject, signal } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
/**
|
||||
* Inicio de sesión: el formulario contra `POST /auth/login` y, si el usuario ya
|
||||
* tiene sesión, salta al destino. `returnUrl` lo pone el guard cuando una ruta
|
||||
* protegida lo trajo aquí.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-login-page',
|
||||
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
|
||||
styleUrl: './login-page.scss',
|
||||
templateUrl: './login-page.html',
|
||||
})
|
||||
export class LoginPage implements OnInit {
|
||||
private readonly auth = inject(AuthService);
|
||||
private readonly router = inject(Router);
|
||||
private readonly ruta = inject(ActivatedRoute);
|
||||
|
||||
protected usuario = '';
|
||||
protected contrasena = '';
|
||||
protected readonly verContrasena = signal(false);
|
||||
protected readonly enviando = signal(false);
|
||||
protected readonly error = signal<string | null>(null);
|
||||
protected readonly anio = new Date().getFullYear();
|
||||
|
||||
ngOnInit(): void {
|
||||
// Quien ya inició sesión y abre /login vuelve derecho a la aplicación.
|
||||
this.auth.sesion().subscribe((usuario) => {
|
||||
if (usuario) void this.router.navigateByUrl(this.destino());
|
||||
});
|
||||
}
|
||||
|
||||
protected ingresar(): void {
|
||||
if (!this.usuario.trim() || !this.contrasena || this.enviando()) return;
|
||||
this.enviando.set(true);
|
||||
this.error.set(null);
|
||||
this.auth.login(this.usuario.trim(), this.contrasena).subscribe({
|
||||
next: () => void this.router.navigateByUrl(this.destino()),
|
||||
error: () => {
|
||||
this.enviando.set(false);
|
||||
this.error.set('Usuario o contraseña incorrectos.');
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected mostrarContrasena(): void {
|
||||
this.verContrasena.update((visible) => !visible);
|
||||
}
|
||||
|
||||
private destino(): string {
|
||||
const pedido = this.ruta.snapshot.queryParamMap.get('returnUrl');
|
||||
return pedido?.startsWith('/') && !pedido.startsWith('/login') ? pedido : '/';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user