From a370f307b50ff02033409dff17a470c500e84430 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Tue, 29 Sep 2026 10:23:09 -0600 Subject: [PATCH] feat(auth): implementar flujo de login y acceso en WebApp --- Dockerfile | 2 +- angular.json | 3 + proxy.docker.json | 5 + proxy.local.json | 5 + public/branding/LogoISSSTELEON.png | Bin 0 -> 13023 bytes public/branding/favicon-isssteleon.png | Bin 0 -> 17696 bytes src/app/app.config.ts | 2 + src/app/app.html | 8 +- src/app/app.routes.ts | 13 ++- src/app/app.scss | 2 + src/app/app.spec.ts | 31 ++++++ src/app/app.ts | 7 +- src/app/auth/area-placeholder.ts | 13 +++ src/app/auth/auth.guard.spec.ts | 94 +++++++++++++++++ src/app/auth/auth.guard.ts | 28 +++++ src/app/auth/auth.models.ts | 17 +++ src/app/auth/auth.roles.spec.ts | 30 ++++++ src/app/auth/auth.roles.ts | 12 +++ src/app/auth/auth.service.spec.ts | 32 ++++++ src/app/auth/auth.service.ts | 18 ++++ src/app/auth/auth.state.spec.ts | 79 ++++++++++++++ src/app/auth/auth.state.ts | 77 ++++++++++++++ src/app/auth/auth.storage.spec.ts | 40 +++++++ src/app/auth/auth.storage.ts | 41 ++++++++ src/app/auth/home.spec.ts | 40 +++++++ src/app/auth/home.ts | 25 +++++ src/app/auth/login.html | 39 +++++++ src/app/auth/login.scss | 120 +++++++++++++++++++++ src/app/auth/login.spec.ts | 139 +++++++++++++++++++++++++ src/app/auth/login.ts | 73 +++++++++++++ src/index.html | 2 +- 31 files changed, 991 insertions(+), 6 deletions(-) create mode 100644 proxy.docker.json create mode 100644 proxy.local.json create mode 100644 public/branding/LogoISSSTELEON.png create mode 100644 public/branding/favicon-isssteleon.png create mode 100644 src/app/auth/area-placeholder.ts create mode 100644 src/app/auth/auth.guard.spec.ts create mode 100644 src/app/auth/auth.guard.ts create mode 100644 src/app/auth/auth.models.ts create mode 100644 src/app/auth/auth.roles.spec.ts create mode 100644 src/app/auth/auth.roles.ts create mode 100644 src/app/auth/auth.service.spec.ts create mode 100644 src/app/auth/auth.service.ts create mode 100644 src/app/auth/auth.state.spec.ts create mode 100644 src/app/auth/auth.state.ts create mode 100644 src/app/auth/auth.storage.spec.ts create mode 100644 src/app/auth/auth.storage.ts create mode 100644 src/app/auth/home.spec.ts create mode 100644 src/app/auth/home.ts create mode 100644 src/app/auth/login.html create mode 100644 src/app/auth/login.scss create mode 100644 src/app/auth/login.spec.ts create mode 100644 src/app/auth/login.ts diff --git a/Dockerfile b/Dockerfile index aebd4d1..ca5d45b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -7,4 +7,4 @@ RUN npm install COPY . . EXPOSE 4200 -CMD ["npx", "ng", "serve", "--host", "0.0.0.0", "--port", "4200"] +CMD ["npx", "ng", "serve", "--host", "0.0.0.0", "--port", "4200", "--proxy-config", "proxy.docker.json"] diff --git a/angular.json b/angular.json index 2b304ca..21608c8 100644 --- a/angular.json +++ b/angular.json @@ -59,6 +59,9 @@ }, "serve": { "builder": "@angular/build:dev-server", + "options": { + "proxyConfig": "proxy.local.json" + }, "configurations": { "production": { "buildTarget": "WebApp:build:production" diff --git a/proxy.docker.json b/proxy.docker.json new file mode 100644 index 0000000..69cfb1e --- /dev/null +++ b/proxy.docker.json @@ -0,0 +1,5 @@ +{ + "/auth/**": { + "target": "http://webapi:5000" + } +} diff --git a/proxy.local.json b/proxy.local.json new file mode 100644 index 0000000..18aaf8f --- /dev/null +++ b/proxy.local.json @@ -0,0 +1,5 @@ +{ + "/auth/**": { + "target": "http://127.0.0.1:5000" + } +} diff --git a/public/branding/LogoISSSTELEON.png b/public/branding/LogoISSSTELEON.png new file mode 100644 index 0000000000000000000000000000000000000000..df4c1f93561d6a8db96768ad9b46632b53ec6367 GIT binary patch literal 13023 zcmeHu`8(8K__tC@SrUn4NuN-bO4-*?lChNRTavx8WE~ljFeOw(V;}o2+1If~_Amy6 z31y7IU@#cNb9|qF;rZ?P{@^;-b>_U!xzBy>{eF3GsISd>=F%Ak1_oB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1AGe7}2eKtW>TV!Z literal 0 HcmV?d00001 diff --git a/src/app/app.config.ts b/src/app/app.config.ts index e60fc79..e606a5d 100644 --- a/src/app/app.config.ts +++ b/src/app/app.config.ts @@ -1,10 +1,12 @@ import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core'; import { provideRouter } from '@angular/router'; +import { provideHttpClient } from '@angular/common/http'; import { routes } from './app.routes'; export const appConfig: ApplicationConfig = { providers: [ provideBrowserGlobalErrorListeners(), + provideHttpClient(), provideRouter(routes) ] }; diff --git a/src/app/app.html b/src/app/app.html index ff298c4..3b4fd40 100644 --- a/src/app/app.html +++ b/src/app/app.html @@ -1,7 +1,13 @@ +@if (auth.isAuthenticated()) { {{ title }} + + {{ auth.user()?.username }} + +}

- + @if (auth.status() === 'checking') {

Comprobando sesión…

} +
diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts index dc39edb..0f841de 100644 --- a/src/app/app.routes.ts +++ b/src/app/app.routes.ts @@ -1,3 +1,14 @@ import { Routes } from '@angular/router'; +import { authGuard, anonymousGuard, areaGuard } from './auth/auth.guard'; +import { AreaPlaceholder } from './auth/area-placeholder'; +import { Home } from './auth/home'; +import { Login } from './auth/login'; -export const routes: Routes = []; +export const routes: Routes = [ + { path: 'login', component: Login, canActivate: [anonymousGuard] }, + { path: '', pathMatch: 'full', component: Home, canActivate: [authGuard] }, + { path: 'cacu', component: AreaPlaceholder, data: { area: 'CACU' }, canActivate: [areaGuard('CACU')] }, + { path: 'cama', component: AreaPlaceholder, data: { area: 'CAMA' }, canActivate: [areaGuard('CAMA')] }, + { path: 'tea', component: AreaPlaceholder, data: { area: 'TEA' }, canActivate: [areaGuard('TEA')] }, + { path: '**', redirectTo: '' }, +]; diff --git a/src/app/app.scss b/src/app/app.scss index 8e69d4f..bcaf5d1 100644 --- a/src/app/app.scss +++ b/src/app/app.scss @@ -1,3 +1,5 @@ main { padding: 1.5rem; } +.spacer { flex: 1; } +.username { font-size: .875rem; margin-right: .5rem; overflow: hidden; text-overflow: ellipsis; } diff --git a/src/app/app.spec.ts b/src/app/app.spec.ts index f1bdf4a..a23b7b3 100644 --- a/src/app/app.spec.ts +++ b/src/app/app.spec.ts @@ -1,10 +1,23 @@ +import { signal } from '@angular/core'; import { TestBed } from '@angular/core/testing'; +import { provideRouter } from '@angular/router'; +import { vi } from 'vitest'; import { App } from './app'; +import { AuthState } from './auth/auth.state'; +import { routes } from './app.routes'; +import { authGuard, anonymousGuard } from './auth/auth.guard'; describe('App', () => { + const status = signal('anonymous'); + const user = signal({ id: 1, username: 'demo', roles: ['CAMA'] }); + const logout = vi.fn(); beforeEach(async () => { + status.set('anonymous'); logout.mockClear(); await TestBed.configureTestingModule({ imports: [App], + providers: [provideRouter([]), { provide: AuthState, useValue: { + status, user, isAuthenticated: () => status() === 'authenticated', logout, + } }], }) .compileComponents(); }); @@ -16,10 +29,28 @@ describe('App', () => { }); it('should render the toolbar title', async () => { + status.set('authenticated'); const fixture = TestBed.createComponent(App); await fixture.whenStable(); fixture.detectChanges(); const compiled = fixture.nativeElement as HTMLElement; expect(compiled.querySelector('mat-toolbar')?.textContent).toContain('ISSSTELEON'); }); + it('hides shell for anonymous and checking', () => { + const fixture = TestBed.createComponent(App); fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('mat-toolbar')).toBeNull(); + status.set('checking'); fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('mat-toolbar')).toBeNull(); + expect(fixture.nativeElement.querySelector('router-outlet').parentElement.hidden).toBe(true); + }); + it('invokes local logout from shell', () => { + status.set('authenticated'); const fixture = TestBed.createComponent(App); fixture.detectChanges(); + fixture.nativeElement.querySelector('button').click(); expect(logout).toHaveBeenCalledOnce(); + }); + it('preserves login, protected home and wildcard alongside area routes', () => { + expect(routes.map(route => route.path)).toEqual(['login', '', 'cacu', 'cama', 'tea', '**']); + expect(routes[0].canActivate).toEqual([anonymousGuard]); + expect(routes[1].canActivate).toEqual([authGuard]); + expect(routes.at(-1)?.redirectTo).toBe(''); + }); }); diff --git a/src/app/app.ts b/src/app/app.ts index 71ff325..f58fd35 100644 --- a/src/app/app.ts +++ b/src/app/app.ts @@ -1,13 +1,16 @@ -import { Component } from '@angular/core'; +import { Component, inject } from '@angular/core'; import { RouterOutlet } from '@angular/router'; import { MatToolbarModule } from '@angular/material/toolbar'; +import { MatButtonModule } from '@angular/material/button'; +import { AuthState } from './auth/auth.state'; @Component({ - imports: [RouterOutlet, MatToolbarModule], + imports: [RouterOutlet, MatToolbarModule, MatButtonModule], selector: 'app-root', styleUrl: './app.scss', templateUrl: './app.html', }) export class App { + protected readonly auth = inject(AuthState); protected readonly title = 'ISSSTELEON'; } diff --git a/src/app/auth/area-placeholder.ts b/src/app/auth/area-placeholder.ts new file mode 100644 index 0000000..2b29255 --- /dev/null +++ b/src/app/auth/area-placeholder.ts @@ -0,0 +1,13 @@ +import { Component, inject } from '@angular/core'; +import { ActivatedRoute, RouterLink } from '@angular/router'; +import { MatButtonModule } from '@angular/material/button'; +import { Area } from './auth.roles'; + +@Component({ + selector: 'app-area-placeholder', + imports: [RouterLink, MatButtonModule], + template: `

Área {{ area }}

Volver a áreas`, +}) +export class AreaPlaceholder { + protected readonly area: Area = inject(ActivatedRoute).snapshot.data['area']; +} diff --git a/src/app/auth/auth.guard.spec.ts b/src/app/auth/auth.guard.spec.ts new file mode 100644 index 0000000..dd09b15 --- /dev/null +++ b/src/app/auth/auth.guard.spec.ts @@ -0,0 +1,94 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { ActivatedRouteSnapshot, Router, RouterStateSnapshot, provideRouter } from '@angular/router'; +import { authGuard, anonymousGuard, areaGuard } from './auth.guard'; +import { Role } from './auth.models'; +import { Area } from './auth.roles'; +import { routes } from '../app.routes'; +import { AuthState } from './auth.state'; + +describe('Auth guards', () => { + let http: HttpTestingController; + const user = { id: 1, username: 'demo', roles: ['CAMA'] }; + beforeEach(() => { + sessionStorage.clear(); + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([])] }); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => { http.verify(); sessionStorage.clear(); }); + const run = (guard: typeof authGuard) => TestBed.runInInjectionContext(() => + guard({} as ActivatedRouteSnapshot, {} as RouterStateSnapshot)); + const url = (result: unknown) => TestBed.inject(Router).serializeUrl(result as ReturnType); + it('anonymous redirects protected route to login', async () => { + expect(url(await run(authGuard))).toBe('/login'); + }); + it('anonymous can open login', async () => { expect(await run(anonymousGuard)).toBe(true); }); + it('authenticated allows home and redirects login', async () => { + const login = TestBed.inject(AuthState).login('demo', 'test-password'); + http.expectOne('/auth/login').flush({ token: 'test-token', expires_in: 28800, user }); await login; + expect(await run(authGuard)).toBe(true); expect(url(await run(anonymousGuard))).toBe('/'); + }); + it('both guards wait on the same restore', async () => { + sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token'); + let resolved = false; + const home = Promise.resolve(run(authGuard)).then(result => { resolved = true; return result; }); + const login = run(anonymousGuard); + await Promise.resolve(); expect(resolved).toBe(false); + expect(TestBed.inject(AuthState).status()).toBe('checking'); + http.expectOne('/auth/me').flush({ user }); + expect(await home).toBe(true); expect(url(await login)).toBe('/'); + }); + it('rejected restore redirects home and allows login', async () => { + sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token'); + const home = run(authGuard); const login = run(anonymousGuard); + http.expectOne('/auth/me').flush({}, { status: 401, statusText: 'Unauthorized' }); + expect(url(await home)).toBe('/login'); expect(await login).toBe(true); + }); + + it('anonymous is redirected to login for every area', async () => { + for (const area of ['CACU', 'CAMA', 'TEA'] as const) { + expect(url(await run(areaGuard(area)))).toBe('/login'); + } + }); + const cases: [Role[], Area[]][] = [ + [['CAMA'], ['CAMA']], [['CACU', 'CAMA'], ['CACU', 'CAMA']], + [['ADMIN'], ['CACU', 'CAMA', 'TEA']], [[], []], + ]; + for (const [roles, allowed] of cases) { + it(`evaluates area guards and configured routes for ${JSON.stringify(roles)}`, async () => { + const login = TestBed.inject(AuthState).login('demo', 'test-password'); + http.expectOne('/auth/login').flush({ token: 'test-token', expires_in: 28800, user: { ...user, roles } }); + await login; + for (const area of ['CACU', 'CAMA', 'TEA'] as const) { + const result = await run(areaGuard(area)); + expect(result === true ? true : url(result)).toBe(allowed.includes(area) ? true : '/'); + const route = routes.find(route => route.path === area.toLowerCase())!; + expect(route.data?.['area']).toBe(area); + expect(route.component).toBeDefined(); + expect(route.canActivate?.length).toBe(1); + const routed = await run(route.canActivate![0] as typeof authGuard); + expect(routed === true ? true : url(routed)).toBe(allowed.includes(area) ? true : '/'); + } + http.expectNone('/auth/me'); + expect(TestBed.inject(AuthState).isAuthenticated()).toBe(true); + }); + } + it('waits for shared restore and uses server roles instead of cached roles', async () => { + sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token'); + sessionStorage.setItem('ISSSTELEON.auth.user', JSON.stringify({ ...user, roles: ['ADMIN'] })); + let resolved = false; + const cama = Promise.resolve(run(areaGuard('CAMA'))).then(result => { resolved = true; return result; }); + const cacu = run(areaGuard('CACU')); const home = run(authGuard); + await Promise.resolve(); expect(resolved).toBe(false); + http.expectOne('/auth/me').flush({ user }); + expect(await cama).toBe(true); expect(url(await cacu)).toBe('/'); expect(await home).toBe(true); + expect(await run(areaGuard('CAMA'))).toBe(true); http.expectNone('/auth/me'); + }); + it('rejected restore redirects pending area guards to login', async () => { + sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token'); + const cama = run(areaGuard('CAMA')); const tea = run(areaGuard('TEA')); + http.expectOne('/auth/me').flush({}, { status: 401, statusText: 'Unauthorized' }); + expect(url(await cama)).toBe('/login'); expect(url(await tea)).toBe('/login'); + }); +}); diff --git a/src/app/auth/auth.guard.ts b/src/app/auth/auth.guard.ts new file mode 100644 index 0000000..30db41c --- /dev/null +++ b/src/app/auth/auth.guard.ts @@ -0,0 +1,28 @@ +import { inject } from '@angular/core'; +import { CanActivateFn, Router } from '@angular/router'; +import { AuthState } from './auth.state'; +import { Area, canAccessArea } from './auth.roles'; + +export function areaGuard(area: Area): CanActivateFn { + return async () => { + const auth = inject(AuthState); + const router = inject(Router); + await auth.restore(); + if (!auth.isAuthenticated()) return router.createUrlTree(['/login']); + return canAccessArea(auth.user()?.roles ?? [], area) || router.createUrlTree(['/']); + }; +} + +export const authGuard: CanActivateFn = async () => { + const auth = inject(AuthState); + const router = inject(Router); + await auth.restore(); + return auth.isAuthenticated() || router.createUrlTree(['/login']); +}; + +export const anonymousGuard: CanActivateFn = async () => { + const auth = inject(AuthState); + const router = inject(Router); + await auth.restore(); + return !auth.isAuthenticated() || router.createUrlTree(['/']); +}; diff --git a/src/app/auth/auth.models.ts b/src/app/auth/auth.models.ts new file mode 100644 index 0000000..00ba6d4 --- /dev/null +++ b/src/app/auth/auth.models.ts @@ -0,0 +1,17 @@ +export type Role = 'ADMIN' | 'CACU' | 'CAMA' | 'TEA'; + +export interface AuthUser { + id: number; + username: string; + roles: Role[]; +} + +export interface LoginResponse { + token: string; + expires_in: number; + user: AuthUser; +} + +export interface MeResponse { + user: AuthUser; +} diff --git a/src/app/auth/auth.roles.spec.ts b/src/app/auth/auth.roles.spec.ts new file mode 100644 index 0000000..be78409 --- /dev/null +++ b/src/app/auth/auth.roles.spec.ts @@ -0,0 +1,30 @@ +import { Role } from './auth.models'; +import { Area, canAccessArea, getAccessibleAreas } from './auth.roles'; + +describe('Area access', () => { + const cases: [Role[], Area[]][] = [ + [[], []], + [['CACU'], ['CACU']], + [['CAMA'], ['CAMA']], + [['TEA'], ['TEA']], + [['CACU', 'CAMA'], ['CACU', 'CAMA']], + [['CACU', 'TEA'], ['CACU', 'TEA']], + [['CAMA', 'TEA'], ['CAMA', 'TEA']], + [['CACU', 'CAMA', 'TEA'], ['CACU', 'CAMA', 'TEA']], + [['ADMIN'], ['CACU', 'CAMA', 'TEA']], + [['ADMIN', 'CAMA'], ['CACU', 'CAMA', 'TEA']], + ]; + for (const [roles, allowed] of cases) { + it(`evaluates all areas and stable list for ${JSON.stringify(roles)}`, () => { + for (const area of ['CACU', 'CAMA', 'TEA'] as const) { + expect(canAccessArea(roles, area)).toBe(allowed.includes(area)); + } + expect(getAccessibleAreas(roles)).toEqual(allowed); + }); + } + it('keeps canonical order without modifying or duplicating input', () => { + const roles: readonly Role[] = Object.freeze(['TEA', 'CAMA', 'CACU', 'CAMA']); + expect(getAccessibleAreas(roles)).toEqual(['CACU', 'CAMA', 'TEA']); + expect(roles).toEqual(['TEA', 'CAMA', 'CACU', 'CAMA']); + }); +}); diff --git a/src/app/auth/auth.roles.ts b/src/app/auth/auth.roles.ts new file mode 100644 index 0000000..d0cd82e --- /dev/null +++ b/src/app/auth/auth.roles.ts @@ -0,0 +1,12 @@ +import { Role } from './auth.models'; + +export type Area = 'CACU' | 'CAMA' | 'TEA'; + +export function canAccessArea(roles: readonly Role[], area: Area): boolean { + return roles.includes('ADMIN') || roles.includes(area); +} + +export function getAccessibleAreas(roles: readonly Role[]): Area[] { + const areas: Area[] = ['CACU', 'CAMA', 'TEA']; + return areas.filter(area => canAccessArea(roles, area)); +} diff --git a/src/app/auth/auth.service.spec.ts b/src/app/auth/auth.service.spec.ts new file mode 100644 index 0000000..931a286 --- /dev/null +++ b/src/app/auth/auth.service.spec.ts @@ -0,0 +1,32 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { AuthService } from './auth.service'; + +describe('AuthService', () => { + let api: AuthService; + let http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + api = TestBed.inject(AuthService); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + it('posts credentials using a relative URL without Bearer', () => { + const response = { token: 'test-token', expires_in: 28800, user: { id: 1, username: 'demo', roles: [] } }; + api.login('demo', 'test-password').subscribe(value => expect(value).toEqual(response)); + const request = http.expectOne('/auth/login'); + expect(request.request.method).toBe('POST'); + expect(request.request.body).toEqual({ username: 'demo', password: 'test-password' }); + expect(request.request.headers.has('Authorization')).toBe(false); + request.flush(response); + }); + it('gets current identity with explicit Bearer', () => { + const response = { user: { id: 1, username: 'demo', roles: ['CAMA'] } }; + api.me('test-token').subscribe(value => expect(value).toEqual(response)); + const request = http.expectOne('/auth/me'); + expect(request.request.method).toBe('GET'); + expect(request.request.headers.get('Authorization')).toBe('Bearer test-token'); + request.flush(response); + }); +}); diff --git a/src/app/auth/auth.service.ts b/src/app/auth/auth.service.ts new file mode 100644 index 0000000..a48be21 --- /dev/null +++ b/src/app/auth/auth.service.ts @@ -0,0 +1,18 @@ +import { inject, Injectable } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +import { LoginResponse, MeResponse } from './auth.models'; + +@Injectable({ providedIn: 'root' }) +export class AuthService { + private readonly http = inject(HttpClient); + + login(username: string, password: string) { + return this.http.post('/auth/login', { username, password }); + } + + me(token: string) { + return this.http.get('/auth/me', { + headers: { Authorization: `Bearer ${token}` }, + }); + } +} diff --git a/src/app/auth/auth.state.spec.ts b/src/app/auth/auth.state.spec.ts new file mode 100644 index 0000000..519cc3c --- /dev/null +++ b/src/app/auth/auth.state.spec.ts @@ -0,0 +1,79 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { Router, provideRouter } from '@angular/router'; +import { vi } from 'vitest'; +import { AuthState } from './auth.state'; +import { AuthStorage } from './auth.storage'; + +describe('AuthState', () => { + const user = { id: 1, username: 'demo', roles: ['CAMA'] }; + let auth: AuthState; + let http: HttpTestingController; + beforeEach(() => { + sessionStorage.clear(); + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([])] }); + auth = TestBed.inject(AuthState); http = TestBed.inject(HttpTestingController); + }); + afterEach(() => { http.verify(); sessionStorage.clear(); vi.restoreAllMocks(); }); + const seed = () => sessionStorage.setItem('ISSSTELEON.auth.token', 'test-token'); + it('starts checking without trusting cache', () => { + expect(auth.status()).toBe('checking'); expect(auth.user()).toBeNull(); expect(auth.isAuthenticated()).toBe(false); + }); + it('restores without token without HTTP and clears cached identity', async () => { + sessionStorage.setItem('ISSSTELEON.auth.user', JSON.stringify(user)); + await auth.restore(); expect(auth.status()).toBe('anonymous'); expect(auth.user()).toBeNull(); + http.expectNone('/auth/me'); expect(TestBed.inject(AuthStorage).readUser()).toBeNull(); + }); + it('shares concurrent restore and trusts only the current server identity', async () => { + seed(); sessionStorage.setItem('ISSSTELEON.auth.user', JSON.stringify(user)); + const first = auth.restore(); const second = auth.restore(); expect(first).toBe(second); + expect(auth.status()).toBe('checking'); expect(auth.user()).toBeNull(); + const current = { ...user, roles: ['TEA'] }; + http.expectOne('/auth/me').flush({ user: current }); await Promise.all([first, second]); + expect(auth.isAuthenticated()).toBe(true); expect(auth.user()).toEqual(current); + expect(TestBed.inject(AuthStorage).readUser()).toEqual(current); + expect(TestBed.inject(AuthStorage).readToken()).toBe('test-token'); + await auth.restore(); http.expectNone('/auth/me'); + }); + for (const status of [401, 500, 0]) { + it(`clears session on restore error ${status}`, async () => { + seed(); const pending = auth.restore(); + const request = http.expectOne('/auth/me'); + if (status === 0) request.error(new ProgressEvent('error')); + else request.flush({}, { status, statusText: 'Rejected' }); + await pending; expect(auth.status()).toBe('anonymous'); expect(auth.user()).toBeNull(); + expect(TestBed.inject(AuthStorage).readToken()).toBeNull(); + }); + } + it('login saves identity and local logout clears it and navigates', async () => { + const navigate = vi.spyOn(TestBed.inject(Router), 'navigateByUrl').mockResolvedValue(true); + const pending = auth.login('demo', 'test-password'); + http.expectOne('/auth/login').flush({ token: 'test-token', expires_in: 28800, user }); await pending; + expect(auth.isAuthenticated()).toBe(true); expect(auth.user()).toEqual(user); + expect(TestBed.inject(AuthStorage).readToken()).toBe('test-token'); + expect(TestBed.inject(AuthStorage).readUser()).toEqual(user); + auth.logout(); expect(auth.status()).toBe('anonymous'); expect(auth.user()).toBeNull(); + expect(TestBed.inject(AuthStorage).readToken()).toBeNull(); expect(navigate).toHaveBeenCalledWith('/login'); + await auth.restore(); http.expectNone('/auth/me'); + }); + it('failed login remains anonymous', async () => { + const pending = auth.login('demo', 'test-password'); + const assertion = expect(pending).rejects.toMatchObject({ status: 401 }); + http.expectOne('/auth/login').flush({}, { status: 401, statusText: 'Unauthorized' }); + await assertion; expect(auth.status()).toBe('anonymous'); expect(auth.user()).toBeNull(); + }); + it('late restore cannot undo logout', async () => { + vi.spyOn(TestBed.inject(Router), 'navigateByUrl').mockResolvedValue(true); + seed(); const pending = auth.restore(); auth.logout(); + http.expectOne('/auth/me').flush({ user }); await pending; + expect(auth.status()).toBe('anonymous'); expect(TestBed.inject(AuthStorage).readToken()).toBeNull(); + }); + it('late restore cannot overwrite a new login', async () => { + seed(); const restoring = auth.restore(); const login = auth.login('demo', 'test-password'); + const current = { ...user, roles: ['ADMIN'] }; + http.expectOne('/auth/login').flush({ token: 'new-test-token', expires_in: 28800, user: current }); + await login; http.expectOne('/auth/me').flush({ user }); await restoring; + expect(auth.user()).toEqual(current); expect(TestBed.inject(AuthStorage).readToken()).toBe('new-test-token'); + }); +}); diff --git a/src/app/auth/auth.state.ts b/src/app/auth/auth.state.ts new file mode 100644 index 0000000..ecec6f8 --- /dev/null +++ b/src/app/auth/auth.state.ts @@ -0,0 +1,77 @@ +import { computed, inject, Injectable, signal } from '@angular/core'; +import { Router } from '@angular/router'; +import { firstValueFrom } from 'rxjs'; +import { AuthUser } from './auth.models'; +import { AuthService } from './auth.service'; +import { AuthStorage } from './auth.storage'; + +@Injectable({ providedIn: 'root' }) +export class AuthState { + private readonly api = inject(AuthService); + private readonly storage = inject(AuthStorage); + private readonly router = inject(Router); + private readonly currentUser = signal(null); + private readonly token = signal(null); + private readonly currentStatus = signal<'checking' | 'authenticated' | 'anonymous'>('checking'); + readonly user = this.currentUser.asReadonly(); + readonly status = this.currentStatus.asReadonly(); + readonly isAuthenticated = computed(() => this.status() === 'authenticated'); + private restoration?: Promise; + private generation = 0; + + restore(): Promise { + if (this.restoration) return this.restoration; + if (this.status() !== 'checking') return Promise.resolve(); + const token = this.storage.readToken(); + if (!token) { + this.clear(); + return Promise.resolve(); + } + const generation = this.generation; + const pending = this.validate(token, generation); + this.restoration = pending; + void pending.finally(() => { + if (this.restoration === pending) this.restoration = undefined; + }); + return pending; + } + + private async validate(token: string, generation: number): Promise { + try { + const response = await firstValueFrom(this.api.me(token)); + if (generation !== this.generation) return; + this.token.set(token); + this.currentUser.set(response.user); + this.storage.updateUser(response.user); + this.currentStatus.set('authenticated'); + } catch { + if (generation === this.generation) this.clear(); + } + } + + async login(username: string, password: string): Promise { + const generation = ++this.generation; + this.restoration = undefined; + this.clear(); + const response = await firstValueFrom(this.api.login(username, password)); + if (generation !== this.generation) return; + this.token.set(response.token); + this.currentUser.set(response.user); + this.storage.save(response.token, response.user); + this.currentStatus.set('authenticated'); + } + + logout(): void { + ++this.generation; + this.restoration = undefined; + this.clear(); + void this.router.navigateByUrl('/login'); + } + + private clear(): void { + this.token.set(null); + this.currentUser.set(null); + this.storage.clear(); + this.currentStatus.set('anonymous'); + } +} diff --git a/src/app/auth/auth.storage.spec.ts b/src/app/auth/auth.storage.spec.ts new file mode 100644 index 0000000..51fbb48 --- /dev/null +++ b/src/app/auth/auth.storage.spec.ts @@ -0,0 +1,40 @@ +import { AuthStorage } from './auth.storage'; +import { vi } from 'vitest'; + +describe('AuthStorage', () => { + const user = { id: 1, username: 'demo', roles: ['CAMA'] as const }; + let storage: AuthStorage; + beforeEach(() => { sessionStorage.clear(); storage = new AuthStorage(); }); + afterEach(() => { vi.restoreAllMocks(); sessionStorage.clear(); }); + it('reads empty storage safely', () => { + expect(storage.readToken()).toBeNull(); expect(storage.readUser()).toBeNull(); + }); + it('saves and clears the tab session', () => { + storage.save('test-token', { ...user, roles: ['CAMA'] }); + expect(storage.readToken()).toBe('test-token'); expect(storage.readUser()).toEqual(user); + storage.updateUser({ ...user, roles: ['ADMIN'] }); + expect(storage.readUser()?.roles).toEqual(['ADMIN']); + storage.clear(); expect(storage.readToken()).toBeNull(); expect(storage.readUser()).toBeNull(); + }); + it('ignores malformed JSON and invalid cache shapes', () => { + for (const value of ['{', '123', '{"id":1}', '{"id":1,"username":"demo","roles":["OTHER"]}']) { + sessionStorage.setItem('ISSSTELEON.auth.user', value); + expect(storage.readUser()).toBeNull(); + } + }); + it('tolerates unavailable sessionStorage', () => { + vi.spyOn(window, 'sessionStorage', 'get').mockImplementation(() => { throw new Error('disabled'); }); + expect(storage.readToken()).toBeNull(); expect(storage.readUser()).toBeNull(); + expect(() => storage.save('test-token', { ...user, roles: ['CAMA'] })).not.toThrow(); + expect(() => storage.updateUser({ ...user, roles: ['CAMA'] })).not.toThrow(); + expect(() => storage.clear()).not.toThrow(); + }); + it('tolerates read, write and removal failures', () => { + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('read'); }); + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('write'); }); + vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(() => { throw new Error('remove'); }); + expect(storage.readToken()).toBeNull(); expect(storage.readUser()).toBeNull(); + expect(() => storage.save('test-token', { ...user, roles: ['CAMA'] })).not.toThrow(); + expect(() => storage.clear()).not.toThrow(); + }); +}); diff --git a/src/app/auth/auth.storage.ts b/src/app/auth/auth.storage.ts new file mode 100644 index 0000000..86d182b --- /dev/null +++ b/src/app/auth/auth.storage.ts @@ -0,0 +1,41 @@ +import { Injectable } from '@angular/core'; +import { AuthUser } from './auth.models'; + +@Injectable({ providedIn: 'root' }) +export class AuthStorage { + private readonly tokenKey = 'ISSSTELEON.auth.token'; + private readonly userKey = 'ISSSTELEON.auth.user'; + + readToken(): string | null { + try { return sessionStorage.getItem(this.tokenKey); } catch { return null; } + } + + readUser(): AuthUser | null { + try { + const value: unknown = JSON.parse(sessionStorage.getItem(this.userKey) ?? 'null'); + if (typeof value !== 'object' || value === null) return null; + const user = value as AuthUser; + return typeof user.id === 'number' && typeof user.username === 'string' && + Array.isArray(user.roles) && user.roles.every(role => + ['ADMIN', 'CACU', 'CAMA', 'TEA'].includes(role)) ? user : null; + } catch { return null; } + } + + save(token: string, user: AuthUser): void { + try { + sessionStorage.setItem(this.tokenKey, token); + sessionStorage.setItem(this.userKey, JSON.stringify(user)); + } catch { this.clear(); } + } + + updateUser(user: AuthUser): void { + try { sessionStorage.setItem(this.userKey, JSON.stringify(user)); } catch { this.clear(); } + } + + clear(): void { + // Attempt both removals even if one storage operation fails. + for (const key of [this.tokenKey, this.userKey]) { + try { sessionStorage.removeItem(key); } catch { /* Storage may be disabled. */ } + } + } +} diff --git a/src/app/auth/home.spec.ts b/src/app/auth/home.spec.ts new file mode 100644 index 0000000..5126e45 --- /dev/null +++ b/src/app/auth/home.spec.ts @@ -0,0 +1,40 @@ +import { signal } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideRouter } from '@angular/router'; +import { AuthUser, Role } from './auth.models'; +import { AuthState } from './auth.state'; +import { Home } from './home'; + +describe('Home areas', () => { + const user = signal({ id: 1, username: 'demo', roles: [] }); + beforeEach(() => { + user.set({ id: 1, username: 'demo', roles: [] }); + TestBed.configureTestingModule({ imports: [Home], providers: [ + provideRouter([]), { provide: AuthState, useValue: { user } }, + ] }); + }); + const cases: [Role[], string[]][] = [ + [['CAMA'], ['CAMA']], [['CACU', 'CAMA'], ['CACU', 'CAMA']], + [['ADMIN'], ['CACU', 'CAMA', 'TEA']], [[], []], + ]; + for (const [roles, areas] of cases) { + it(`renders only authorized links for ${JSON.stringify(roles)}`, () => { + user.set({ id: 1, username: 'demo', roles }); + const fixture = TestBed.createComponent(Home); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + const links = Array.from(root.querySelectorAll('a')); + expect(links.map(link => link.textContent?.trim())).toEqual(areas); + expect(links.map(link => link.getAttribute('href'))).toEqual(areas.map(area => '/' + area.toLowerCase())); + expect(root.querySelector('[role="status"]')?.textContent ?? null) + .toBe(areas.length ? null : 'No tienes áreas asignadas.'); + }); + } + it('updates navigation from current AuthState roles', () => { + user.set({ id: 1, username: 'demo', roles: ['ADMIN'] }); + const fixture = TestBed.createComponent(Home); fixture.detectChanges(); + expect(fixture.nativeElement.querySelectorAll('a').length).toBe(3); + user.set({ id: 1, username: 'demo', roles: ['TEA'] }); fixture.detectChanges(); + expect(Array.from(fixture.nativeElement.querySelectorAll('a') as NodeListOf) + .map(link => link.textContent?.trim())).toEqual(['TEA']); + }); +}); diff --git a/src/app/auth/home.ts b/src/app/auth/home.ts new file mode 100644 index 0000000..3405adf --- /dev/null +++ b/src/app/auth/home.ts @@ -0,0 +1,25 @@ +import { Component, computed, inject } from '@angular/core'; +import { RouterLink } from '@angular/router'; +import { MatButtonModule } from '@angular/material/button'; +import { AuthState } from './auth.state'; +import { getAccessibleAreas } from './auth.roles'; + +@Component({ + selector: 'app-home', + imports: [RouterLink, MatButtonModule], + template: ` +

Áreas disponibles

+ + `, + styles: `nav { display: flex; flex-wrap: wrap; gap: 1rem; }`, +}) +export class Home { + private readonly auth = inject(AuthState); + protected readonly areas = computed(() => getAccessibleAreas(this.auth.user()?.roles ?? [])); +} diff --git a/src/app/auth/login.html b/src/app/auth/login.html new file mode 100644 index 0000000..c8f66cc --- /dev/null +++ b/src/app/auth/login.html @@ -0,0 +1,39 @@ + diff --git a/src/app/auth/login.scss b/src/app/auth/login.scss new file mode 100644 index 0000000..bec9c09 --- /dev/null +++ b/src/app/auth/login.scss @@ -0,0 +1,120 @@ +@use '@angular/material' as mat; + +:host { + --login-page-bg: #f7f7f7; + --login-surface: #ffffff; + --login-text: #333333; + --login-text-muted: #667085; + --login-border: #cccccc; + --login-focus: #00833c; + --isssteleon-lime: #99ca3c; + --isssteleon-green: #00833c; + --login-icon-teal: #5f9ea0; + --login-action-bg: #f8f9fa; + --login-action-border: #e9ecef; + + display: grid; + box-sizing: border-box; + min-height: 100dvh; + margin: -1.5rem; // Compensate the existing main padding only while Login is mounted. + padding: 2rem 24px; + place-items: center; + background: var(--login-page-bg); + color: var(--login-text); + font-family: Roboto, Arial, sans-serif; +} + +.login { width: min(100%, 26rem); min-width: 0; } + +h1 { + display: flex; + align-items: center; + gap: 1rem; + margin: 0 0 2rem; + font-size: 1.5rem; + font-weight: 500; + line-height: 1.3; + white-space: nowrap; + + &::before, &::after { + content: ''; + flex: 1; + min-width: 0; + border-top: 1px solid var(--login-border); + } +} + +form { display: flex; flex-direction: column; gap: .75rem; } + +.login-field { + width: 100%; + position: relative; + isolation: isolate; + @include mat.form-field-overrides(( + outlined-container-shape: 5px, + outlined-outline-color: var(--login-border), + outlined-hover-outline-color: var(--login-text-muted), + outlined-focus-outline-color: var(--login-focus), + outlined-focus-label-text-color: var(--login-focus), + outlined-label-text-color: var(--login-text-muted), + outlined-input-text-color: var(--login-text), + outlined-caret-color: var(--login-focus), + container-text-size: 16px, + )); + // Keep the validation subscript on the page background. + &::before { content: ''; position: absolute; inset: 0 0 auto; height: 56px; + background: var(--login-surface); border-radius: 5px; z-index: -1; } +} + +.password-toggle { + color: var(--login-text-muted); + margin-inline-end: 4px; + min-width: 48px; + min-height: 48px; + svg { width: 24px; height: 24px; fill: none; stroke: currentColor; stroke-width: 1.8; } +} + +.login-action.mat-mdc-unelevated-button { + @include mat.button-overrides(( + filled-container-color: var(--login-action-bg), + filled-label-text-color: var(--login-text), + filled-container-shape: 8px, + filled-container-height: 50px, + filled-label-text-size: 16px, + filled-label-text-weight: 500, + filled-state-layer-color: var(--login-focus), + filled-disabled-container-color: #e9ecef, + filled-disabled-label-text-color: #707780, + )); + width: 100%; + min-height: 50px; + border: 1px solid var(--login-action-border); + border-radius: 8px; + background: var(--login-action-bg); + color: var(--login-text); + font: 500 16px Roboto, Arial, sans-serif; + cursor: pointer; + box-shadow: 0 1px 2px #00000014; + transition: transform 160ms cubic-bezier(.2, 0, 0, 1), background-color 160ms ease, + border-color 160ms ease, box-shadow 160ms ease; + &:hover:not(:disabled) { + transform: translateY(-1px); + background: #eef2ed; + border-color: var(--login-focus); + box-shadow: 0 3px 7px #0000001c; + } + &:active:not(:disabled) { transform: translateY(0) scale(.99); background: #e4ebdf; box-shadow: none; } + &:disabled { transform: none; transition: none; background: #e9ecef; color: #707780; box-shadow: none; cursor: default; } +} + +button:focus-visible { outline: 2px solid var(--login-focus); outline-offset: 3px; } +@media (prefers-reduced-motion: reduce) { + .login-action.mat-mdc-unelevated-button { + transition: none; + &:hover:not(:disabled), &:active:not(:disabled) { transform: none; } + } +} +.login-feedback { min-height: 2.5rem; font-size: .875rem; line-height: 1.4; } +[role='alert'] { color: var(--mat-sys-error); margin: 0; } +[role='status'] { color: var(--login-text-muted); margin: 0; } +.login-logo { display: block; width: min(100%, clamp(200px, 17vw, 240px)); height: auto; object-fit: contain; margin: 1.5rem auto 0; } diff --git a/src/app/auth/login.spec.ts b/src/app/auth/login.spec.ts new file mode 100644 index 0000000..ddf9b15 --- /dev/null +++ b/src/app/auth/login.spec.ts @@ -0,0 +1,139 @@ +import { TestBed } from '@angular/core/testing'; +import { HttpErrorResponse } from '@angular/common/http'; +import { Router, provideRouter } from '@angular/router'; +import { vi } from 'vitest'; +import { AuthState } from './auth.state'; +import { Login } from './login'; + +describe('Login', () => { + let login: ReturnType; + beforeEach(() => { + login = vi.fn().mockResolvedValue(undefined); + TestBed.configureTestingModule({ imports: [Login], providers: [provideRouter([]), + { provide: AuthState, useValue: { login, isAuthenticated: () => true } }] }); + vi.spyOn(TestBed.inject(Router), 'navigateByUrl').mockResolvedValue(true); + }); + afterEach(() => vi.restoreAllMocks()); + const create = () => { + const fixture = TestBed.createComponent(Login); fixture.detectChanges(); return fixture; + }; + const fill = (component: Login) => component.form.setValue({ username: 'Demo', password: 'test-password' }); + const usernameInput = (fixture: ReturnType>) => + fixture.nativeElement.querySelector('input[autocomplete="username"]') as HTMLInputElement; + const hasUsernameError = (fixture: { nativeElement: HTMLElement }) => + !!fixture.nativeElement.querySelector('mat-error'); + it('renders required credentials and submit button', () => { + const fixture = create(); const element: HTMLElement = fixture.nativeElement; + expect(element.querySelector('input[autocomplete="username"]')).toBeTruthy(); + expect(element.querySelector('input[type="password"]')).toBeTruthy(); + expect(element.querySelector('button[type="submit"]')?.textContent).toContain('Iniciar sesión'); + expect(fixture.componentInstance.form.invalid).toBe(true); + }); + it('rejects empty and invalid credentials', async () => { + const component = create().componentInstance; await component.submit(); expect(login).not.toHaveBeenCalled(); + for (const username of ['ab', 'a'.repeat(65), 'demo@']) { + component.form.setValue({ username, password: 'test-password' }); expect(component.form.invalid).toBe(true); + } + component.form.setValue({ username: 'demo', password: 'a'.repeat(129) }); expect(component.form.invalid).toBe(true); + }); + it('shows the username error after blur, hides it while editing, and restores it on blur if still invalid', () => { + const fixture = create(); const input = usernameInput(fixture); const control = fixture.componentInstance.form.controls.username; + input.dispatchEvent(new Event('focus')); input.dispatchEvent(new Event('blur')); fixture.detectChanges(); + expect(control.invalid).toBe(true); + expect(hasUsernameError(fixture)).toBe(true); + expect(input.closest('mat-form-field')?.classList.contains('mat-form-field-invalid')).toBe(true); + input.dispatchEvent(new Event('focus')); fixture.detectChanges(); + expect(fixture.componentInstance.usernameEditing()).toBe(true); + expect(hasUsernameError(fixture)).toBe(false); + expect(input.closest('mat-form-field')?.classList.contains('mat-form-field-invalid')).toBe(false); + input.dispatchEvent(new Event('input')); input.dispatchEvent(new Event('blur')); fixture.detectChanges(); + expect(hasUsernameError(fixture)).toBe(true); + expect(input.closest('mat-form-field')?.classList.contains('mat-form-field-invalid')).toBe(true); + }); + it('keeps the username error cleared after editing to a valid value', () => { + const fixture = create(); const input = usernameInput(fixture); const control = fixture.componentInstance.form.controls.username; + input.dispatchEvent(new Event('focus')); input.dispatchEvent(new Event('blur')); fixture.detectChanges(); + expect(hasUsernameError(fixture)).toBe(true); + input.dispatchEvent(new Event('focus')); + input.value = 'valid-user'; input.dispatchEvent(new Event('input', { bubbles: true })); + input.dispatchEvent(new Event('blur')); fixture.detectChanges(); + expect(control.valid).toBe(true); + expect(hasUsernameError(fixture)).toBe(false); + }); + it('shows field errors on invalid submit and suppresses them once editing starts', async () => { + const fixture = create(); const component = fixture.componentInstance; + await component.submit(); fixture.detectChanges(); + expect(component.submitted()).toBe(true); + expect(fixture.nativeElement.querySelectorAll('mat-error').length).toBe(2); + const input = usernameInput(fixture); input.dispatchEvent(new Event('focus')); fixture.detectChanges(); + expect(fixture.nativeElement.querySelectorAll('mat-error').length).toBe(1); + expect(component.form.controls.username.invalid).toBe(true); + }); + it('uses dynamic subscripts for both fields', () => { + const fixture = create(); + expect(fixture.nativeElement.querySelectorAll('mat-form-field[subscriptsizing="dynamic"]').length).toBe(2); + }); + it('submits normalized credentials, clears password and navigates home', async () => { + const component = create().componentInstance; fill(component); await component.submit(); + expect(login).toHaveBeenCalledWith('demo', 'test-password'); + expect(TestBed.inject(Router).navigateByUrl).toHaveBeenCalledWith('/'); + expect(component.form.controls.password.value).toBe(''); expect(component.loading()).toBe(false); + }); + it('shows loading and prevents duplicate submissions', async () => { + let resolve!: () => void; + login.mockReturnValue(new Promise(done => { resolve = done; })); + const fixture = create(); const component = fixture.componentInstance; fill(component); + const pending = component.submit(); fixture.detectChanges(); + expect(component.loading()).toBe(true); + expect((fixture.nativeElement.querySelector('button[type="submit"]') as HTMLButtonElement).disabled).toBe(true); + expect(fixture.nativeElement.querySelector('[role="status"]')).toBeTruthy(); + await component.submit(); expect(login).toHaveBeenCalledTimes(1); resolve(); await pending; + }); + it('starts with the password hidden and an accessible unpressed toggle', () => { + const fixture = create(); + const element: HTMLElement = fixture.nativeElement; + const toggle = element.querySelector('.password-toggle') as HTMLButtonElement; + expect(element.querySelector('input[autocomplete="current-password"]')?.getAttribute('type')).toBe('password'); + expect(toggle.type).toBe('button'); + expect(toggle.getAttribute('aria-label')).toBe('Mostrar contraseña'); + expect(toggle.getAttribute('aria-pressed')).toBe('false'); + }); + it('shows and hides the password with matching aria states without submitting', () => { + const fixture = create(); fill(fixture.componentInstance); + const element: HTMLElement = fixture.nativeElement; + const toggle = element.querySelector('.password-toggle') as HTMLButtonElement; + toggle.click(); fixture.detectChanges(); + expect(element.querySelector('input[autocomplete="current-password"]')?.getAttribute('type')).toBe('text'); + expect(toggle.getAttribute('aria-label')).toBe('Ocultar contraseña'); + expect(toggle.getAttribute('aria-pressed')).toBe('true'); + expect(login).not.toHaveBeenCalled(); + toggle.click(); fixture.detectChanges(); + expect(element.querySelector('input[autocomplete="current-password"]')?.getAttribute('type')).toBe('password'); + expect(toggle.getAttribute('aria-label')).toBe('Mostrar contraseña'); + expect(toggle.getAttribute('aria-pressed')).toBe('false'); + expect(login).not.toHaveBeenCalled(); + expect(fixture.componentInstance.form.controls.password.value).toBe('test-password'); + }); + it('submits the unchanged password while it is visible', async () => { + const fixture = create(); fill(fixture.componentInstance); + (fixture.nativeElement.querySelector('.password-toggle') as HTMLButtonElement).click(); + fixture.detectChanges(); + fixture.nativeElement.querySelector('form').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })); + await fixture.whenStable(); + expect(login).toHaveBeenCalledExactlyOnceWith('demo', 'test-password'); + expect(TestBed.inject(Router).navigateByUrl).toHaveBeenCalledWith('/'); + expect(fixture.componentInstance.form.controls.password.value).toBe(''); + }); + for (const status of [401, 500, 0, 404]) { + it(`shows generic error for ${status}`, async () => { + login.mockRejectedValue(new HttpErrorResponse({ status, error: 'PRIVATE TECHNICAL BODY' })); + const fixture = create(); const component = fixture.componentInstance; fill(component); await component.submit(); + fixture.detectChanges(); + expect(component.error()).toBe(status === 401 ? 'Usuario o contraseña incorrectos.' + : 'No fue posible iniciar sesión. Inténtalo de nuevo.'); + expect(fixture.nativeElement.textContent).not.toContain('PRIVATE TECHNICAL BODY'); + expect(TestBed.inject(Router).navigateByUrl).not.toHaveBeenCalled(); + expect(component.loading()).toBe(false); expect(component.form.controls.password.value).toBe(''); + }); + } +}); diff --git a/src/app/auth/login.ts b/src/app/auth/login.ts new file mode 100644 index 0000000..c549e0a --- /dev/null +++ b/src/app/auth/login.ts @@ -0,0 +1,73 @@ +import { Component, inject, signal } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; +import { FormBuilder, FormGroupDirective, NgForm, ReactiveFormsModule, Validators } from '@angular/forms'; +import { ErrorStateMatcher } from '@angular/material/core'; +import { Router } from '@angular/router'; +import { MatIconModule } from '@angular/material/icon'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { MatButtonModule } from '@angular/material/button'; +import { AuthState } from './auth.state'; + +class LoginFieldErrorStateMatcher implements ErrorStateMatcher { + constructor(private readonly isEditing: () => boolean) {} + + isErrorState(control: { invalid: boolean; touched: boolean } | null, form: FormGroupDirective | NgForm | null): boolean { + return !!control?.invalid && (control.touched || !!form?.submitted) && !this.isEditing(); + } +} + +@Component({ + selector: 'app-login', + imports: [ReactiveFormsModule, MatIconModule, MatFormFieldModule, MatInputModule, MatButtonModule], + templateUrl: './login.html', + styleUrl: './login.scss', +}) +export class Login { + private readonly auth = inject(AuthState); + private readonly router = inject(Router); + readonly loading = signal(false); + readonly error = signal(''); + readonly passwordVisible = signal(false); + readonly submitted = signal(false); + readonly usernameEditing = signal(false); + readonly passwordEditing = signal(false); + readonly usernameErrorMatcher = new LoginFieldErrorStateMatcher(() => this.usernameEditing()); + readonly passwordErrorMatcher = new LoginFieldErrorStateMatcher(() => this.passwordEditing()); + readonly form = inject(FormBuilder).nonNullable.group({ + username: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(64), + Validators.pattern(/^[a-zA-Z0-9._-]+$/)]], + password: ['', [Validators.required, Validators.maxLength(128)]], + }); + + showUsernameError(): boolean { + return this.form.controls.username.invalid && (this.form.controls.username.touched || this.submitted()) + && !this.usernameEditing(); + } + + showPasswordError(): boolean { + return this.form.controls.password.invalid && (this.form.controls.password.touched || this.submitted()) + && !this.passwordEditing(); + } + + async submit(): Promise { + if (this.loading()) return; + this.submitted.set(true); + if (this.form.invalid) { this.form.markAllAsTouched(); return; } + this.loading.set(true); + this.error.set(''); + const { username, password } = this.form.getRawValue(); + try { + await this.auth.login(username.trim().toLowerCase(), password); + this.form.controls.password.reset(); + if (this.auth.isAuthenticated()) await this.router.navigateByUrl('/'); + } catch (error) { + this.form.controls.password.reset(); + this.error.set(error instanceof HttpErrorResponse && error.status === 401 + ? 'Usuario o contraseña incorrectos.' + : 'No fue posible iniciar sesión. Inténtalo de nuevo.'); + } finally { + this.loading.set(false); + } + } +} diff --git a/src/index.html b/src/index.html index 5ac61ae..9f0ffa3 100644 --- a/src/index.html +++ b/src/index.html @@ -5,7 +5,7 @@ WebApp - +