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 0000000..df4c1f9 Binary files /dev/null and b/public/branding/LogoISSSTELEON.png differ diff --git a/public/branding/favicon-isssteleon.png b/public/branding/favicon-isssteleon.png new file mode 100644 index 0000000..5247c1e Binary files /dev/null and b/public/branding/favicon-isssteleon.png differ 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 - +