Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
515a92b395 | ||
|
|
0174272bdd | ||
|
|
5669cd63ec |
@@ -2,7 +2,8 @@
|
|||||||
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
||||||
"version": 1,
|
"version": 1,
|
||||||
"cli": {
|
"cli": {
|
||||||
"packageManager": "npm"
|
"packageManager": "npm",
|
||||||
|
"analytics": false
|
||||||
},
|
},
|
||||||
"newProjectRoot": "projects",
|
"newProjectRoot": "projects",
|
||||||
"projects": {
|
"projects": {
|
||||||
@@ -80,6 +81,7 @@
|
|||||||
"builder": "@angular/build:unit-test",
|
"builder": "@angular/build:unit-test",
|
||||||
"options": {
|
"options": {
|
||||||
"coverage": true,
|
"coverage": true,
|
||||||
|
"isolate": true,
|
||||||
"coverageReporters": [
|
"coverageReporters": [
|
||||||
"text-summary",
|
"text-summary",
|
||||||
"lcov",
|
"lcov",
|
||||||
|
|||||||
@@ -1,13 +1,21 @@
|
|||||||
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
|
import {ApplicationConfig, inject, provideAppInitializer, provideBrowserGlobalErrorListeners} from '@angular/core';
|
||||||
import { provideRouter } from '@angular/router';
|
import { provideRouter } from '@angular/router';
|
||||||
import { routes } from './app.routes';
|
import { routes } from './app.routes';
|
||||||
import { mockApiInterceptor } from './core/interceptors/mock-api-interceptor';
|
import { mockApiInterceptor } from './core/interceptors/mock-api-interceptor';
|
||||||
import { provideHttpClient, withInterceptors } from '@angular/common/http';
|
import { provideHttpClient, withInterceptors } from '@angular/common/http';
|
||||||
|
import {catchError, firstValueFrom, of} from 'rxjs';
|
||||||
|
import {AuthService} from './core/services/auth.service';
|
||||||
|
import {authInterceptor} from './core/interceptors/auth-interceptor';
|
||||||
|
|
||||||
export const appConfig: ApplicationConfig = {
|
export const appConfig: ApplicationConfig = {
|
||||||
providers: [
|
providers: [
|
||||||
provideBrowserGlobalErrorListeners(),
|
provideBrowserGlobalErrorListeners(),
|
||||||
provideRouter(routes),
|
provideRouter(routes),
|
||||||
provideHttpClient(withInterceptors([mockApiInterceptor])),
|
provideHttpClient(withInterceptors([authInterceptor, mockApiInterceptor])),
|
||||||
|
provideAppInitializer(() => {
|
||||||
|
const auth = inject(AuthService);
|
||||||
|
// Un 401 ici est normal : ça veut juste dire qu'il n'y a pas de session.
|
||||||
|
return firstValueFrom(auth.refreshShared().pipe(catchError(() => of(null))));
|
||||||
|
}),
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
import { Routes } from '@angular/router';
|
import { Routes } from '@angular/router';
|
||||||
|
import {authGuard} from './core/guards/auth-guard';
|
||||||
|
|
||||||
export const routes: Routes = [
|
export const routes: Routes = [
|
||||||
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
|
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
|
||||||
|
{ path: 'login', loadComponent: () => import('./features/auth/login/login').then(m => m.Login) },
|
||||||
|
{ path: 'change-password', loadComponent: () => import('./features/auth/change-password/change-password').then(m => m.ChangePassword) },
|
||||||
{
|
{
|
||||||
path: 'dashboard',
|
path: 'dashboard',
|
||||||
loadComponent: () => import('./features/dashboard/dashboard').then((m) => m.Dashboard),
|
canActivate: [authGuard],
|
||||||
|
loadComponent: () => import('./features/dashboard/dashboard').then(m => m.Dashboard),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { Router, ActivatedRouteSnapshot } from '@angular/router';
|
||||||
|
import { vi } from 'vitest';
|
||||||
|
import { authGuard } from './auth-guard';
|
||||||
|
import { AuthService } from '../services/auth.service';
|
||||||
|
|
||||||
|
describe('authGuard', () => {
|
||||||
|
let authMock: { isAuthenticated: ReturnType<typeof vi.fn>; principal: ReturnType<typeof vi.fn> };
|
||||||
|
let routerMock: { navigate: ReturnType<typeof vi.fn> };
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
authMock = { isAuthenticated: vi.fn(), principal: vi.fn() };
|
||||||
|
routerMock = { navigate: vi.fn() };
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
{ provide: AuthService, useValue: authMock },
|
||||||
|
{ provide: Router, useValue: routerMock },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('redirige vers /login si non authentifié', () => {
|
||||||
|
authMock.isAuthenticated.mockReturnValue(false);
|
||||||
|
|
||||||
|
const result = TestBed.runInInjectionContext(() =>
|
||||||
|
authGuard({ data: {} } as ActivatedRouteSnapshot, {} as any)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result).toBe(false);
|
||||||
|
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('redirige vers /login si le rôle ne correspond pas', () => {
|
||||||
|
authMock.isAuthenticated.mockReturnValue(true);
|
||||||
|
authMock.principal.mockReturnValue({ role: 'lecteur' });
|
||||||
|
|
||||||
|
const result = TestBed.runInInjectionContext(() =>
|
||||||
|
authGuard({ data: { role: 'admin' } } as unknown as ActivatedRouteSnapshot, {} as any)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result).toBe(false);
|
||||||
|
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('autorise si authentifié et rôle correspondant', () => {
|
||||||
|
authMock.isAuthenticated.mockReturnValue(true);
|
||||||
|
authMock.principal.mockReturnValue({ role: 'admin' });
|
||||||
|
|
||||||
|
const result = TestBed.runInInjectionContext(() =>
|
||||||
|
authGuard({ data: { role: 'admin' } } as unknown as ActivatedRouteSnapshot, {} as any)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('autorise si authentifié et aucun rôle requis', () => {
|
||||||
|
authMock.isAuthenticated.mockReturnValue(true);
|
||||||
|
authMock.principal.mockReturnValue({ role: 'lecteur' });
|
||||||
|
|
||||||
|
const result = TestBed.runInInjectionContext(() =>
|
||||||
|
authGuard({ data: {} } as ActivatedRouteSnapshot, {} as any)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { inject } from '@angular/core';
|
||||||
|
import { CanActivateFn, Router } from '@angular/router';
|
||||||
|
import { AuthService } from '../services/auth.service';
|
||||||
|
|
||||||
|
export const authGuard: CanActivateFn = (route) => {
|
||||||
|
const auth = inject(AuthService);
|
||||||
|
const router = inject(Router);
|
||||||
|
|
||||||
|
if (!auth.isAuthenticated()) {
|
||||||
|
router.navigate(['/login']);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const requiredRole = route.data['role'] as string | undefined;
|
||||||
|
if (requiredRole && auth.principal()?.role !== requiredRole) {
|
||||||
|
router.navigate(['/login']);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
};
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import {
|
||||||
|
HttpClient,
|
||||||
|
HttpHandlerFn,
|
||||||
|
HttpHeaders,
|
||||||
|
HttpRequest,
|
||||||
|
provideHttpClient,
|
||||||
|
withInterceptors
|
||||||
|
} from '@angular/common/http';
|
||||||
|
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
|
import { of, throwError } from 'rxjs';
|
||||||
|
import { vi } from 'vitest';
|
||||||
|
import { authInterceptor } from './auth-interceptor';
|
||||||
|
import { AuthService } from '../services/auth.service';
|
||||||
|
|
||||||
|
describe('authInterceptor', () => {
|
||||||
|
let http: HttpClient;
|
||||||
|
let httpMock: HttpTestingController;
|
||||||
|
let authMock: { getAccessToken: ReturnType<typeof vi.fn>; clearSession: ReturnType<typeof vi.fn>; refreshShared: ReturnType<typeof vi.fn> };
|
||||||
|
let routerMock: { navigate: ReturnType<typeof vi.fn> };
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
authMock = {
|
||||||
|
getAccessToken: vi.fn().mockReturnValue('fake-token'),
|
||||||
|
clearSession: vi.fn(),
|
||||||
|
refreshShared: vi.fn(),
|
||||||
|
};
|
||||||
|
routerMock = { navigate: vi.fn() };
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
provideHttpClient(withInterceptors([authInterceptor])),
|
||||||
|
provideHttpClientTesting(),
|
||||||
|
{ provide: AuthService, useValue: authMock },
|
||||||
|
{ provide: Router, useValue: routerMock },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
http = TestBed.inject(HttpClient);
|
||||||
|
httpMock = TestBed.inject(HttpTestingController);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => httpMock.verify());
|
||||||
|
|
||||||
|
it('ajoute le header Authorization quand un token est disponible', () => {
|
||||||
|
http.get('/api/v1/stats/summary').subscribe();
|
||||||
|
const req = httpMock.expectOne('/api/v1/stats/summary');
|
||||||
|
expect(req.request.headers.get('Authorization')).toBe('Bearer fake-token');
|
||||||
|
req.flush({});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("n'ajoute pas le header Authorization sur /auth/login", () => {
|
||||||
|
http.post('/api/v1/auth/login', {}).subscribe();
|
||||||
|
const req = httpMock.expectOne('/api/v1/auth/login');
|
||||||
|
expect(req.request.headers.has('Authorization')).toBe(false);
|
||||||
|
req.flush({});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ajoute withCredentials sur les routes /auth/*', () => {
|
||||||
|
http.post('/api/v1/auth/login', {}).subscribe();
|
||||||
|
const req = httpMock.expectOne('/api/v1/auth/login');
|
||||||
|
expect(req.request.withCredentials).toBe(true);
|
||||||
|
req.flush({});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('redirige vers /change-password sur un 403 avec ce detail précis', () => {
|
||||||
|
http.get('/api/v1/dashboard').subscribe({ error: () => {} });
|
||||||
|
const req = httpMock.expectOne('/api/v1/dashboard');
|
||||||
|
req.flush({ detail: 'password_change_required' }, { status: 403, statusText: 'Forbidden' });
|
||||||
|
expect(routerMock.navigate).toHaveBeenCalledWith(['/change-password']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ne redirige pas sur un 403 avec un autre detail', () => {
|
||||||
|
http.get('/api/v1/dashboard').subscribe({ error: () => {} });
|
||||||
|
const req = httpMock.expectOne('/api/v1/dashboard');
|
||||||
|
req.flush({ detail: 'Droits insuffisants' }, { status: 403, statusText: 'Forbidden' });
|
||||||
|
expect(routerMock.navigate).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('déconnecte et redirige vers /login sur un 401 avec error="invalid_token"', () => {
|
||||||
|
http.get('/api/v1/dashboard').subscribe({ error: () => {} });
|
||||||
|
const req = httpMock.expectOne('/api/v1/dashboard');
|
||||||
|
req.flush(
|
||||||
|
{},
|
||||||
|
{ status: 401, statusText: 'Unauthorized', headers: new HttpHeaders({ 'WWW-Authenticate': 'Bearer error="invalid_token"' }) }
|
||||||
|
);
|
||||||
|
expect(authMock.clearSession).toHaveBeenCalled();
|
||||||
|
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('déconnecte directement sur un 401 provenant de /auth/refresh, sans tenter de rafraîchir', () => {
|
||||||
|
http.post('/api/v1/auth/refresh', {}).subscribe({ error: () => {} });
|
||||||
|
const req = httpMock.expectOne('/api/v1/auth/refresh');
|
||||||
|
req.flush({}, { status: 401, statusText: 'Unauthorized' });
|
||||||
|
expect(authMock.clearSession).toHaveBeenCalled();
|
||||||
|
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rafraîchit puis rejoue la requête sur un 401 avec error="expired"', () => {
|
||||||
|
authMock.refreshShared.mockReturnValue(of({ access_token: 'new-token' }));
|
||||||
|
authMock.getAccessToken.mockReturnValueOnce('old-token').mockReturnValue('new-token');
|
||||||
|
|
||||||
|
let result: unknown;
|
||||||
|
http.get('/api/v1/dashboard').subscribe((r) => (result = r));
|
||||||
|
|
||||||
|
const firstReq = httpMock.expectOne('/api/v1/dashboard');
|
||||||
|
firstReq.flush({}, { status: 401, statusText: 'Unauthorized', headers: new HttpHeaders({ 'WWW-Authenticate': 'Bearer error="expired"' }) });
|
||||||
|
|
||||||
|
const retriedReq = httpMock.expectOne('/api/v1/dashboard');
|
||||||
|
expect(retriedReq.request.headers.get('Authorization')).toBe('Bearer new-token');
|
||||||
|
retriedReq.flush({ ok: true });
|
||||||
|
|
||||||
|
expect(result).toEqual({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('déconnecte si le rafraîchissement échoue après un 401 "expired"', () => {
|
||||||
|
authMock.refreshShared.mockReturnValue(throwError(() => new Error('refresh failed')));
|
||||||
|
|
||||||
|
http.get('/api/v1/dashboard').subscribe({ error: () => {} });
|
||||||
|
const req = httpMock.expectOne('/api/v1/dashboard');
|
||||||
|
req.flush({}, { status: 401, statusText: 'Unauthorized', headers: new HttpHeaders({ 'WWW-Authenticate': 'Bearer error="expired"' }) });
|
||||||
|
|
||||||
|
expect(authMock.clearSession).toHaveBeenCalled();
|
||||||
|
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("propage l'erreur telle quelle si ce n'est pas une HttpErrorResponse", () => {
|
||||||
|
const req = new HttpRequest('GET', '/api/v1/dashboard');
|
||||||
|
const boom = new Error('erreur inattendue, pas HTTP');
|
||||||
|
const next: HttpHandlerFn = () => throwError(() => boom);
|
||||||
|
|
||||||
|
let captured: unknown;
|
||||||
|
TestBed.runInInjectionContext(() => {
|
||||||
|
authInterceptor(req, next).subscribe({ error: (e) => (captured = e) });
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(captured).toBe(boom);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('propage un 401 sur /auth/login sans tenter de rafraîchir ni déconnecter', () => {
|
||||||
|
http.post('/api/v1/auth/login', {}).subscribe({ error: () => {} });
|
||||||
|
const req = httpMock.expectOne('/api/v1/auth/login');
|
||||||
|
req.flush({}, { status: 401, statusText: 'Unauthorized' });
|
||||||
|
|
||||||
|
expect(authMock.refreshShared).not.toHaveBeenCalled();
|
||||||
|
expect(authMock.clearSession).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("propage un 401 dont le WWW-Authenticate ne correspond à aucun cas connu", () => {
|
||||||
|
http.get('/api/v1/dashboard').subscribe({ error: () => {} });
|
||||||
|
const req = httpMock.expectOne('/api/v1/dashboard');
|
||||||
|
req.flush(
|
||||||
|
{},
|
||||||
|
{ status: 401, statusText: 'Unauthorized', headers: new HttpHeaders({ 'WWW-Authenticate': 'Bearer error="unknown_case"' }) }
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(authMock.refreshShared).not.toHaveBeenCalled();
|
||||||
|
expect(authMock.clearSession).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
|
||||||
|
import { inject } from '@angular/core';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
|
import { Observable, catchError, switchMap, throwError } from 'rxjs';
|
||||||
|
import { AuthService } from '../services/auth.service';
|
||||||
|
import { TokenResponse } from '../../shared/models/auth.model';
|
||||||
|
|
||||||
|
function parseAuthError(response: HttpErrorResponse): string | null {
|
||||||
|
const header = response.headers?.get('WWW-Authenticate') ?? '';
|
||||||
|
const match = header.match(/error="([^"]+)"/);
|
||||||
|
return match ? match[1] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const authInterceptor: HttpInterceptorFn = (req, next) => {
|
||||||
|
const auth = inject(AuthService);
|
||||||
|
const router = inject(Router);
|
||||||
|
|
||||||
|
const isAuthRoute = req.url.includes('/auth/');
|
||||||
|
let request = isAuthRoute ? req.clone({ withCredentials: true }) : req;
|
||||||
|
|
||||||
|
const token = auth.getAccessToken();
|
||||||
|
if (token && !req.url.endsWith('/auth/login')) {
|
||||||
|
request = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
|
||||||
|
}
|
||||||
|
|
||||||
|
return next(request).pipe(
|
||||||
|
catchError((error: unknown) => {
|
||||||
|
if (!(error instanceof HttpErrorResponse)) {
|
||||||
|
return throwError(() => error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error.status === 403) {
|
||||||
|
const detail = (error.error as { detail?: string })?.detail;
|
||||||
|
if (detail === 'password_change_required') {
|
||||||
|
router.navigate(['/change-password']);
|
||||||
|
}
|
||||||
|
return throwError(() => error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error.status !== 401 || req.url.endsWith('/auth/login')) {
|
||||||
|
return throwError(() => error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.url.endsWith('/auth/refresh')) {
|
||||||
|
auth.clearSession();
|
||||||
|
router.navigate(['/login']);
|
||||||
|
return throwError(() => error);
|
||||||
|
}
|
||||||
|
|
||||||
|
const kind = parseAuthError(error);
|
||||||
|
|
||||||
|
if (kind === 'invalid_token') {
|
||||||
|
auth.clearSession();
|
||||||
|
router.navigate(['/login']);
|
||||||
|
return throwError(() => error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kind === 'expired' || kind === 'token_stale') {
|
||||||
|
return (auth.refreshShared() as Observable<TokenResponse>).pipe(
|
||||||
|
switchMap(() => {
|
||||||
|
const retried = request.clone({
|
||||||
|
setHeaders: { Authorization: `Bearer ${auth.getAccessToken()}` },
|
||||||
|
});
|
||||||
|
return next(retried);
|
||||||
|
}),
|
||||||
|
catchError((refreshError) => {
|
||||||
|
auth.clearSession();
|
||||||
|
router.navigate(['/login']);
|
||||||
|
return throwError(() => refreshError);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return throwError(() => error);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
import { environment } from '../../../environments/environment';
|
||||||
|
|
||||||
|
describe('AuthService', () => {
|
||||||
|
let service: AuthService;
|
||||||
|
let httpMock: HttpTestingController;
|
||||||
|
|
||||||
|
const tokenResponse = {
|
||||||
|
access_token: 'abc123',
|
||||||
|
token_type: 'bearer',
|
||||||
|
expires_in: 900,
|
||||||
|
principal: {
|
||||||
|
id: '1',
|
||||||
|
email: 'a@a.com',
|
||||||
|
role: 'admin' as const,
|
||||||
|
kind: 'human' as const,
|
||||||
|
must_change_password: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [provideHttpClient(), provideHttpClientTesting()],
|
||||||
|
});
|
||||||
|
service = TestBed.inject(AuthService);
|
||||||
|
httpMock = TestBed.inject(HttpTestingController);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => httpMock.verify());
|
||||||
|
|
||||||
|
it('stocke le token et le principal après un login réussi', () => {
|
||||||
|
service.login({ email: 'a@a.com', password: 'secret' }).subscribe();
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(`${environment.apiUrl}/auth/login`);
|
||||||
|
expect(req.request.withCredentials).toBe(true);
|
||||||
|
req.flush(tokenResponse);
|
||||||
|
|
||||||
|
expect(service.getAccessToken()).toBe('abc123');
|
||||||
|
expect(service.principal()?.email).toBe('a@a.com');
|
||||||
|
expect(service.isAuthenticated()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('efface la session au logout', () => {
|
||||||
|
service.login({ email: 'a@a.com', password: 'secret' }).subscribe();
|
||||||
|
httpMock.expectOne(`${environment.apiUrl}/auth/login`).flush(tokenResponse);
|
||||||
|
|
||||||
|
service.logout().subscribe();
|
||||||
|
httpMock.expectOne(`${environment.apiUrl}/auth/logout`).flush(null);
|
||||||
|
|
||||||
|
expect(service.getAccessToken()).toBeNull();
|
||||||
|
expect(service.isAuthenticated()).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ne déclenche qu'un seul appel réseau si refreshShared est appelé plusieurs fois avant la réponse", () => {
|
||||||
|
service.refreshShared().subscribe();
|
||||||
|
service.refreshShared().subscribe();
|
||||||
|
service.refreshShared().subscribe();
|
||||||
|
|
||||||
|
const requests = httpMock.match(`${environment.apiUrl}/auth/refresh`);
|
||||||
|
expect(requests.length).toBe(1);
|
||||||
|
requests[0].flush(tokenResponse);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('met à jour la session après un changement de mot de passe réussi', () => {
|
||||||
|
service.changePassword({ current_password: 'old', new_password: 'new-password-1234' }).subscribe();
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(`${environment.apiUrl}/auth/password`);
|
||||||
|
req.flush(tokenResponse);
|
||||||
|
|
||||||
|
expect(service.getAccessToken()).toBe('abc123');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('récupère le principal courant via /auth/me', () => {
|
||||||
|
let result: unknown;
|
||||||
|
service.me().subscribe((r) => (result = r));
|
||||||
|
|
||||||
|
const req = httpMock.expectOne(`${environment.apiUrl}/auth/me`);
|
||||||
|
expect(req.request.method).toBe('GET');
|
||||||
|
req.flush(tokenResponse.principal);
|
||||||
|
|
||||||
|
expect(result).toEqual(tokenResponse.principal);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { Service, signal, computed, inject } from '@angular/core';
|
||||||
|
import { HttpClient } from '@angular/common/http';
|
||||||
|
import { Observable, tap, finalize, shareReplay } from 'rxjs';
|
||||||
|
import { LoginRequest, PasswordChangeRequest, Principal, TokenResponse } from '../../shared/models/auth.model';
|
||||||
|
import { environment } from '../../../environments/environment';
|
||||||
|
|
||||||
|
@Service()
|
||||||
|
export class AuthService {
|
||||||
|
private http = inject(HttpClient);
|
||||||
|
|
||||||
|
// Jamais de localStorage/sessionStorage/cookie côté JS : juste un signal en
|
||||||
|
// mémoire. Un rechargement de page le perd, c'est voulu par le contrat.
|
||||||
|
private accessTokenSignal = signal<string | null>(null);
|
||||||
|
private principalSignal = signal<Principal | null>(null);
|
||||||
|
|
||||||
|
readonly principal = this.principalSignal.asReadonly();
|
||||||
|
readonly isAuthenticated = computed(() => this.principalSignal() !== null);
|
||||||
|
|
||||||
|
private rotation$?: Observable<TokenResponse>;
|
||||||
|
|
||||||
|
getAccessToken(): string | null {
|
||||||
|
return this.accessTokenSignal();
|
||||||
|
}
|
||||||
|
|
||||||
|
private setSession(response: TokenResponse): void {
|
||||||
|
this.accessTokenSignal.set(response.access_token);
|
||||||
|
this.principalSignal.set(response.principal);
|
||||||
|
}
|
||||||
|
|
||||||
|
clearSession(): void {
|
||||||
|
this.accessTokenSignal.set(null);
|
||||||
|
this.principalSignal.set(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
login(credentials: LoginRequest): Observable<TokenResponse> {
|
||||||
|
return this.http
|
||||||
|
.post<TokenResponse>(`${environment.apiUrl}/auth/login`, credentials, { withCredentials: true })
|
||||||
|
.pipe(tap((response) => this.setSession(response)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Un seul rafraîchissement en vol à la fois, partagé entre tous les
|
||||||
|
// appelants (sinon le serveur révoque toute la session sur des rotations concurrentes).
|
||||||
|
refreshShared(): Observable<TokenResponse> {
|
||||||
|
this.rotation$ ??= this.http
|
||||||
|
.post<TokenResponse>(`${environment.apiUrl}/auth/refresh`, {}, { withCredentials: true })
|
||||||
|
.pipe(
|
||||||
|
tap((response) => this.setSession(response)),
|
||||||
|
finalize(() => (this.rotation$ = undefined)),
|
||||||
|
shareReplay(1)
|
||||||
|
);
|
||||||
|
return this.rotation$;
|
||||||
|
}
|
||||||
|
|
||||||
|
logout(): Observable<void> {
|
||||||
|
return this.http
|
||||||
|
.post<void>(`${environment.apiUrl}/auth/logout`, {}, { withCredentials: true })
|
||||||
|
.pipe(tap(() => this.clearSession()));
|
||||||
|
}
|
||||||
|
|
||||||
|
changePassword(payload: PasswordChangeRequest): Observable<TokenResponse> {
|
||||||
|
return this.http
|
||||||
|
.post<TokenResponse>(`${environment.apiUrl}/auth/password`, payload, { withCredentials: true })
|
||||||
|
.pipe(tap((response) => this.setSession(response)));
|
||||||
|
}
|
||||||
|
|
||||||
|
me(): Observable<Principal> {
|
||||||
|
return this.http.get<Principal>(`${environment.apiUrl}/auth/me`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<div class="auth-page">
|
||||||
|
<form class="auth-card" [formGroup]="form" (ngSubmit)="onSubmit()">
|
||||||
|
<h1>Nouveau mot de passe</h1>
|
||||||
|
<p class="auth-subtitle">Votre mot de passe est provisoire, vous devez le modifier avant de continuer</p>
|
||||||
|
|
||||||
|
<label for="current_password">Mot de passe actuel</label>
|
||||||
|
<input
|
||||||
|
id="current_password"
|
||||||
|
type="password"
|
||||||
|
formControlName="current_password"
|
||||||
|
autocomplete="current-password"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<label for="new_password">Nouveau mot de passe</label>
|
||||||
|
<input
|
||||||
|
id="new_password"
|
||||||
|
type="password"
|
||||||
|
formControlName="new_password"
|
||||||
|
autocomplete="new-password"
|
||||||
|
/>
|
||||||
|
<span class="auth-hint">12 à 128 caractères</span>
|
||||||
|
|
||||||
|
@if (errorMessage()) {
|
||||||
|
<p class="auth-error">{{ errorMessage() }}</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
<button type="submit" [disabled]="form.invalid || isLoading()">
|
||||||
|
{{ isLoading() ? 'Modification...' : 'Valider' }}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
:host {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-height: 100vh;
|
||||||
|
background: #f3f4f6;
|
||||||
|
font-family: 'Segoe UI', system-ui, sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-card {
|
||||||
|
background: #ffffff;
|
||||||
|
border: 1px solid #e5e7eb;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 2.5rem;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 360px;
|
||||||
|
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: #1f2937;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-subtitle {
|
||||||
|
margin: 0.25rem 0 1.5rem;
|
||||||
|
color: #6b7280;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #374151;
|
||||||
|
margin-bottom: 0.35rem;
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
input {
|
||||||
|
padding: 0.6rem 0.75rem;
|
||||||
|
border: 1px solid #d1d5db;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
|
||||||
|
&:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: #3b82f6;
|
||||||
|
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
margin-top: 1.5rem;
|
||||||
|
padding: 0.7rem;
|
||||||
|
background: #3b82f6;
|
||||||
|
color: #fff;
|
||||||
|
border: none;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
|
||||||
|
&:disabled {
|
||||||
|
background: #9ca3af;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
&:not(:disabled):hover {
|
||||||
|
background: #2563eb;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-hint {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: #9ca3af;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-error {
|
||||||
|
margin: 0.75rem 0 0;
|
||||||
|
color: #dc2626;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { ReactiveFormsModule } from '@angular/forms';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
|
import { of, throwError } from 'rxjs';
|
||||||
|
import { vi } from 'vitest';
|
||||||
|
import { ChangePassword } from './change-password';
|
||||||
|
import { AuthService } from '../../../core/services/auth.service';
|
||||||
|
|
||||||
|
describe('ChangePassword', () => {
|
||||||
|
let authMock: { changePassword: ReturnType<typeof vi.fn> };
|
||||||
|
let routerMock: { navigate: ReturnType<typeof vi.fn> };
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
authMock = { changePassword: vi.fn() };
|
||||||
|
routerMock = { navigate: vi.fn() };
|
||||||
|
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [ChangePassword, ReactiveFormsModule],
|
||||||
|
providers: [
|
||||||
|
{ provide: AuthService, useValue: authMock },
|
||||||
|
{ provide: Router, useValue: routerMock },
|
||||||
|
],
|
||||||
|
}).compileComponents();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ne soumet pas si le formulaire est invalide (mot de passe trop court)', () => {
|
||||||
|
const fixture = TestBed.createComponent(ChangePassword);
|
||||||
|
const component = fixture.componentInstance;
|
||||||
|
component.form.setValue({ current_password: 'old', new_password: 'trop-court' });
|
||||||
|
|
||||||
|
component.onSubmit();
|
||||||
|
expect(authMock.changePassword).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('redirige vers /dashboard après un changement réussi', () => {
|
||||||
|
const fixture = TestBed.createComponent(ChangePassword);
|
||||||
|
const component = fixture.componentInstance;
|
||||||
|
component.form.setValue({ current_password: 'ancien-mot-de-passe', new_password: 'un-nouveau-mot-de-passe-valide' });
|
||||||
|
|
||||||
|
authMock.changePassword.mockReturnValue(of({ principal: { role: 'admin' } }));
|
||||||
|
|
||||||
|
component.onSubmit();
|
||||||
|
expect(routerMock.navigate).toHaveBeenCalledWith(['/dashboard']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("affiche un message d'erreur si le mot de passe actuel est incorrect", () => {
|
||||||
|
const fixture = TestBed.createComponent(ChangePassword);
|
||||||
|
const component = fixture.componentInstance;
|
||||||
|
component.form.setValue({ current_password: 'mauvais-mot-de-passe', new_password: 'un-nouveau-mot-de-passe-valide' });
|
||||||
|
|
||||||
|
authMock.changePassword.mockReturnValue(throwError(() => new Error('401')));
|
||||||
|
|
||||||
|
component.onSubmit();
|
||||||
|
fixture.detectChanges(); // rend le bloc @if (errorMessage())
|
||||||
|
|
||||||
|
expect(component.errorMessage()).toContain('incorrect');
|
||||||
|
const errorEl = fixture.nativeElement.querySelector('.auth-error');
|
||||||
|
expect(errorEl?.textContent).toContain('incorrect');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('désactive le bouton tant que le formulaire est invalide', () => {
|
||||||
|
const fixture = TestBed.createComponent(ChangePassword);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const button = fixture.nativeElement.querySelector('button[type="submit"]');
|
||||||
|
expect(button.disabled).toBe(true);
|
||||||
|
expect(fixture.nativeElement.querySelector('.auth-error')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('déclenche onSubmit via la soumission réelle du formulaire (ngSubmit)', () => {
|
||||||
|
const fixture = TestBed.createComponent(ChangePassword);
|
||||||
|
const component = fixture.componentInstance;
|
||||||
|
component.form.setValue({ current_password: 'ancien-mot-de-passe', new_password: 'un-nouveau-mot-de-passe-valide' });
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
authMock.changePassword.mockReturnValue(of({ principal: { role: 'admin' } }));
|
||||||
|
|
||||||
|
const form = fixture.nativeElement.querySelector('form');
|
||||||
|
form.dispatchEvent(new Event('submit'));
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(authMock.changePassword).toHaveBeenCalledWith({
|
||||||
|
current_password: 'ancien-mot-de-passe',
|
||||||
|
new_password: 'un-nouveau-mot-de-passe-valide',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { Component, inject, signal } from '@angular/core';
|
||||||
|
import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
|
import { AuthService } from '../../../core/services/auth.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-change-password',
|
||||||
|
standalone: true,
|
||||||
|
imports: [ReactiveFormsModule],
|
||||||
|
templateUrl: './change-password.html',
|
||||||
|
styleUrl: './change-password.scss',
|
||||||
|
})
|
||||||
|
export class ChangePassword {
|
||||||
|
private fb = inject(FormBuilder);
|
||||||
|
private auth = inject(AuthService);
|
||||||
|
private router = inject(Router);
|
||||||
|
|
||||||
|
errorMessage = signal<string | null>(null);
|
||||||
|
isLoading = signal(false);
|
||||||
|
|
||||||
|
form = this.fb.nonNullable.group({
|
||||||
|
current_password: ['', Validators.required],
|
||||||
|
new_password: ['', [Validators.required, Validators.minLength(12), Validators.maxLength(128)]],
|
||||||
|
});
|
||||||
|
|
||||||
|
onSubmit(): void {
|
||||||
|
if (this.form.invalid) return;
|
||||||
|
this.isLoading.set(true);
|
||||||
|
this.errorMessage.set(null);
|
||||||
|
|
||||||
|
this.auth.changePassword(this.form.getRawValue()).subscribe({
|
||||||
|
next: (response) => {
|
||||||
|
this.router.navigate(['/dashboard']);
|
||||||
|
},
|
||||||
|
error: () => {
|
||||||
|
this.isLoading.set(false);
|
||||||
|
this.errorMessage.set('Mot de passe actuel incorrect, ou nouveau mot de passe invalide (12 à 128 caractères).');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
<div class="auth-page">
|
||||||
|
<form class="auth-card" [formGroup]="form" (ngSubmit)="onSubmit()">
|
||||||
|
<h1>Connexion</h1>
|
||||||
|
<p class="auth-subtitle">Accédez à votre espace EnerVision</p>
|
||||||
|
|
||||||
|
<label for="email">Email</label>
|
||||||
|
<input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
formControlName="email"
|
||||||
|
autocomplete="username"
|
||||||
|
placeholder="vous@enervision.fr"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<label for="password">Mot de passe</label>
|
||||||
|
<input
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
formControlName="password"
|
||||||
|
autocomplete="current-password"
|
||||||
|
/>
|
||||||
|
|
||||||
|
@if (errorMessage()) {
|
||||||
|
<p class="auth-error">
|
||||||
|
{{ errorMessage() }}
|
||||||
|
@if (retryAfterSeconds(); as seconds) {
|
||||||
|
(réessayez dans {{ seconds }}s)
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
<button type="submit" [disabled]="form.invalid || isLoading()">
|
||||||
|
{{ isLoading() ? 'Connexion...' : 'Se connecter' }}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
:host {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-height: 100vh;
|
||||||
|
background: #f3f4f6;
|
||||||
|
font-family: 'Segoe UI', system-ui, sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-card {
|
||||||
|
background: #ffffff;
|
||||||
|
border: 1px solid #e5e7eb;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 2.5rem;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 360px;
|
||||||
|
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: #1f2937;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-subtitle {
|
||||||
|
margin: 0.25rem 0 1.5rem;
|
||||||
|
color: #6b7280;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #374151;
|
||||||
|
margin-bottom: 0.35rem;
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
input {
|
||||||
|
padding: 0.6rem 0.75rem;
|
||||||
|
border: 1px solid #d1d5db;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
|
||||||
|
&:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: #3b82f6;
|
||||||
|
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
margin-top: 1.5rem;
|
||||||
|
padding: 0.7rem;
|
||||||
|
background: #3b82f6;
|
||||||
|
color: #fff;
|
||||||
|
border: none;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
|
||||||
|
&:disabled {
|
||||||
|
background: #9ca3af;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
&:not(:disabled):hover {
|
||||||
|
background: #2563eb;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-error {
|
||||||
|
margin: 0.75rem 0 0;
|
||||||
|
color: #dc2626;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { ReactiveFormsModule } from '@angular/forms';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
|
import { HttpErrorResponse, HttpHeaders } from '@angular/common/http';
|
||||||
|
import { of, throwError } from 'rxjs';
|
||||||
|
import { vi } from 'vitest';
|
||||||
|
import { Login } from './login';
|
||||||
|
import { AuthService } from '../../../core/services/auth.service';
|
||||||
|
|
||||||
|
describe('Login', () => {
|
||||||
|
let authMock: { login: ReturnType<typeof vi.fn> };
|
||||||
|
let routerMock: { navigate: ReturnType<typeof vi.fn> };
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
authMock = { login: vi.fn() };
|
||||||
|
routerMock = { navigate: vi.fn() };
|
||||||
|
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [Login, ReactiveFormsModule],
|
||||||
|
providers: [
|
||||||
|
{ provide: AuthService, useValue: authMock },
|
||||||
|
{ provide: Router, useValue: routerMock },
|
||||||
|
],
|
||||||
|
}).compileComponents();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ne soumet pas si le formulaire est invalide', () => {
|
||||||
|
const fixture = TestBed.createComponent(Login);
|
||||||
|
fixture.componentInstance.onSubmit();
|
||||||
|
expect(authMock.login).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('redirige vers /change-password si must_change_password est vrai', () => {
|
||||||
|
const fixture = TestBed.createComponent(Login);
|
||||||
|
const component = fixture.componentInstance;
|
||||||
|
component.form.setValue({ email: 'a@a.com', password: 'secret' });
|
||||||
|
|
||||||
|
authMock.login.mockReturnValue(of({ principal: { role: 'admin', must_change_password: true } }));
|
||||||
|
|
||||||
|
component.onSubmit();
|
||||||
|
expect(routerMock.navigate).toHaveBeenCalledWith(['/change-password']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('redirige vers /dashboard si le mot de passe est déjà à jour', () => {
|
||||||
|
const fixture = TestBed.createComponent(Login);
|
||||||
|
const component = fixture.componentInstance;
|
||||||
|
component.form.setValue({ email: 'a@a.com', password: 'secret' });
|
||||||
|
|
||||||
|
authMock.login.mockReturnValue(of({ principal: { role: 'lecteur', must_change_password: false } }));
|
||||||
|
|
||||||
|
component.onSubmit();
|
||||||
|
expect(routerMock.navigate).toHaveBeenCalledWith(['/dashboard']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('affiche un message générique sur un 401', () => {
|
||||||
|
const fixture = TestBed.createComponent(Login);
|
||||||
|
const component = fixture.componentInstance;
|
||||||
|
component.form.setValue({ email: 'a@a.com', password: 'wrong' });
|
||||||
|
|
||||||
|
authMock.login.mockReturnValue(throwError(() => new HttpErrorResponse({ status: 401 })));
|
||||||
|
|
||||||
|
component.onSubmit();
|
||||||
|
fixture.detectChanges(); // rend le bloc @if (errorMessage()) du template
|
||||||
|
|
||||||
|
expect(component.errorMessage()).toBe('Email ou mot de passe incorrect.');
|
||||||
|
const errorEl = fixture.nativeElement.querySelector('.auth-error');
|
||||||
|
expect(errorEl?.textContent).toContain('Email ou mot de passe incorrect.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("affiche le délai d'attente sur un 429 avec Retry-After", () => {
|
||||||
|
const fixture = TestBed.createComponent(Login);
|
||||||
|
const component = fixture.componentInstance;
|
||||||
|
component.form.setValue({ email: 'a@a.com', password: 'wrong' });
|
||||||
|
|
||||||
|
authMock.login.mockReturnValue(
|
||||||
|
throwError(() => new HttpErrorResponse({ status: 429, headers: new HttpHeaders({ 'Retry-After': '30' }) }))
|
||||||
|
);
|
||||||
|
|
||||||
|
component.onSubmit();
|
||||||
|
fixture.detectChanges(); // rend aussi le sous-bloc @if (retryAfterSeconds(); as seconds)
|
||||||
|
|
||||||
|
expect(component.retryAfterSeconds()).toBe(30);
|
||||||
|
const errorEl = fixture.nativeElement.querySelector('.auth-error');
|
||||||
|
expect(errorEl?.textContent).toContain('30s');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('désactive le bouton tant que le formulaire est invalide', () => {
|
||||||
|
const fixture = TestBed.createComponent(Login);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const button = fixture.nativeElement.querySelector('button[type="submit"]');
|
||||||
|
expect(button.disabled).toBe(true);
|
||||||
|
expect(fixture.nativeElement.querySelector('.auth-error')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('déclenche onSubmit via la soumission réelle du formulaire (ngSubmit)', () => {
|
||||||
|
const fixture = TestBed.createComponent(Login);
|
||||||
|
const component = fixture.componentInstance;
|
||||||
|
component.form.setValue({ email: 'a@a.com', password: 'secret' });
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
authMock.login.mockReturnValue(of({ principal: { role: 'lecteur', must_change_password: false } }));
|
||||||
|
|
||||||
|
const form = fixture.nativeElement.querySelector('form');
|
||||||
|
form.dispatchEvent(new Event('submit'));
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(authMock.login).toHaveBeenCalledWith({ email: 'a@a.com', password: 'secret' });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { Component, inject, signal } from '@angular/core';
|
||||||
|
import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
|
import { AuthService } from '../../../core/services/auth.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-login',
|
||||||
|
standalone: true,
|
||||||
|
imports: [ReactiveFormsModule],
|
||||||
|
templateUrl: './login.html',
|
||||||
|
styleUrl: './login.scss',
|
||||||
|
})
|
||||||
|
export class Login {
|
||||||
|
private fb = inject(FormBuilder);
|
||||||
|
private auth = inject(AuthService);
|
||||||
|
private router = inject(Router);
|
||||||
|
|
||||||
|
errorMessage = signal<string | null>(null);
|
||||||
|
retryAfterSeconds = signal<number | null>(null);
|
||||||
|
isLoading = signal(false);
|
||||||
|
|
||||||
|
form = this.fb.nonNullable.group({
|
||||||
|
email: ['', [Validators.required, Validators.email]],
|
||||||
|
password: ['', Validators.required],
|
||||||
|
});
|
||||||
|
|
||||||
|
onSubmit(): void {
|
||||||
|
if (this.form.invalid) return;
|
||||||
|
|
||||||
|
this.isLoading.set(true);
|
||||||
|
this.errorMessage.set(null);
|
||||||
|
this.retryAfterSeconds.set(null);
|
||||||
|
|
||||||
|
this.auth.login(this.form.getRawValue()).subscribe({
|
||||||
|
next: (response) => {
|
||||||
|
if (response.principal.must_change_password) {
|
||||||
|
this.router.navigate(['/change-password']);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.router.navigate(['/dashboard']);
|
||||||
|
},
|
||||||
|
error: (error: HttpErrorResponse) => {
|
||||||
|
this.isLoading.set(false);
|
||||||
|
if (error.status === 429) {
|
||||||
|
const retryAfter = error.headers.get('Retry-After');
|
||||||
|
this.retryAfterSeconds.set(retryAfter ? Number(retryAfter) : null);
|
||||||
|
this.errorMessage.set('Trop de tentatives, réessayez plus tard.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.errorMessage.set('Email ou mot de passe incorrect.');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
<div class="dashboard">
|
<div class="dashboard">
|
||||||
<header class="dashboard__header">
|
<header class="dashboard__header">
|
||||||
|
<div>
|
||||||
<h1>Vue d'ensemble</h1>
|
<h1>Vue d'ensemble</h1>
|
||||||
<p class="dashboard__subtitle">Consommation instantanée du parc</p>
|
<p class="dashboard__subtitle">Consommation instantanée du parc</p>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="logout-button" (click)="onLogout()">Déconnexion</button>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@if (error(); as message) {
|
@if (error(); as message) {
|
||||||
|
|||||||
@@ -144,3 +144,30 @@ h2 {
|
|||||||
.alert-item__message {
|
.alert-item__message {
|
||||||
font-size: 0.9rem;
|
font-size: 0.9rem;
|
||||||
}
|
}
|
||||||
|
.dashboard__header {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: space-between;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.75rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.logout-button {
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
background: #ffffff;
|
||||||
|
border: 1px solid #d1d5db;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #374151;
|
||||||
|
cursor: pointer;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: #f3f4f6;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import { of, throwError } from 'rxjs';
|
|||||||
import { Dashboard } from './dashboard';
|
import { Dashboard } from './dashboard';
|
||||||
import { StatsService } from '../../core/services/stats.service';
|
import { StatsService } from '../../core/services/stats.service';
|
||||||
import { AlertsService } from '../../core/services/alerts.service';
|
import { AlertsService } from '../../core/services/alerts.service';
|
||||||
|
import {AuthService} from '../../core/services/auth.service';
|
||||||
|
import {Router} from '@angular/router';
|
||||||
|
|
||||||
vi.mock('chart.js', () => {
|
vi.mock('chart.js', () => {
|
||||||
class ChartMock {
|
class ChartMock {
|
||||||
@@ -92,4 +94,58 @@ describe('Dashboard', () => {
|
|||||||
|
|
||||||
expect(fixture.componentInstance.alerts().length).toBe(0);
|
expect(fixture.componentInstance.alerts().length).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('appelle logout et redirige vers /login au clic sur le bouton de déconnexion', () => {
|
||||||
|
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
||||||
|
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([])) };
|
||||||
|
const authMock = { logout: vi.fn().mockReturnValue(of(undefined)), clearSession: vi.fn() };
|
||||||
|
const routerMock = { navigate: vi.fn() };
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [Dashboard],
|
||||||
|
providers: [
|
||||||
|
{ provide: StatsService, useValue: statsMock },
|
||||||
|
{ provide: AlertsService, useValue: alertsMock },
|
||||||
|
{ provide: AuthService, useValue: authMock },
|
||||||
|
{ provide: Router, useValue: routerMock },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(Dashboard);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const button = fixture.nativeElement.querySelector('.logout-button');
|
||||||
|
button.click();
|
||||||
|
|
||||||
|
expect(authMock.logout).toHaveBeenCalled();
|
||||||
|
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
||||||
|
});
|
||||||
|
it('déconnecte localement et redirige vers /login même si logout échoue côté réseau', () => {
|
||||||
|
const statsMock = { getSummary: vi.fn().mockReturnValue(of({ total_sites: 7, sites: [] })) };
|
||||||
|
const alertsMock = { getAlerts: vi.fn().mockReturnValue(of([])) };
|
||||||
|
const authMock = {
|
||||||
|
logout: vi.fn().mockReturnValue(throwError(() => new Error('réseau indisponible'))),
|
||||||
|
clearSession: vi.fn(),
|
||||||
|
};
|
||||||
|
const routerMock = { navigate: vi.fn() };
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [Dashboard],
|
||||||
|
providers: [
|
||||||
|
{ provide: StatsService, useValue: statsMock },
|
||||||
|
{ provide: AlertsService, useValue: alertsMock },
|
||||||
|
{ provide: AuthService, useValue: authMock },
|
||||||
|
{ provide: Router, useValue: routerMock },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(Dashboard);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const button = fixture.nativeElement.querySelector('.logout-button');
|
||||||
|
button.click();
|
||||||
|
|
||||||
|
expect(authMock.clearSession).toHaveBeenCalled();
|
||||||
|
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,10 +2,12 @@ import { Component, OnInit, inject, signal, DestroyRef } from '@angular/core';
|
|||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
import { timer, switchMap, catchError, EMPTY, Observable } from 'rxjs';
|
import { timer, switchMap, catchError, EMPTY, Observable } from 'rxjs';
|
||||||
import { DecimalPipe } from '@angular/common';
|
import { DecimalPipe } from '@angular/common';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
import { StatsService } from '../../core/services/stats.service';
|
import { StatsService } from '../../core/services/stats.service';
|
||||||
import { ConsumptionGauge } from '../../shared/components/consumption-gauge/consumption-gauge';
|
import { ConsumptionGauge } from '../../shared/components/consumption-gauge/consumption-gauge';
|
||||||
import { SiteLoadChart } from '../../shared/components/site-load-chart/site-load-chart';
|
import { SiteLoadChart } from '../../shared/components/site-load-chart/site-load-chart';
|
||||||
import { AlertsService } from '../../core/services/alerts.service';
|
import { AlertsService } from '../../core/services/alerts.service';
|
||||||
|
import { AuthService } from '../../core/services/auth.service';
|
||||||
import { StatsSummary } from '../../shared/models/stats.model';
|
import { StatsSummary } from '../../shared/models/stats.model';
|
||||||
import { Alert } from '../../shared/models/alert.model';
|
import { Alert } from '../../shared/models/alert.model';
|
||||||
|
|
||||||
@@ -23,6 +25,8 @@ const UNAVAILABLE_MESSAGE =
|
|||||||
export class Dashboard implements OnInit {
|
export class Dashboard implements OnInit {
|
||||||
private statsService = inject(StatsService);
|
private statsService = inject(StatsService);
|
||||||
private alertsService = inject(AlertsService);
|
private alertsService = inject(AlertsService);
|
||||||
|
private auth = inject(AuthService);
|
||||||
|
private router = inject(Router);
|
||||||
private destroyRef = inject(DestroyRef);
|
private destroyRef = inject(DestroyRef);
|
||||||
|
|
||||||
stats = signal<StatsSummary | null>(null);
|
stats = signal<StatsSummary | null>(null);
|
||||||
@@ -50,6 +54,17 @@ export class Dashboard implements OnInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
onLogout(): void {
|
||||||
|
this.auth.logout().subscribe({
|
||||||
|
next: () => this.router.navigate(['/login']),
|
||||||
|
error: () => {
|
||||||
|
// Même si l'appel réseau échoue, on considère l'utilisateur déconnecté localement.
|
||||||
|
this.auth.clearSession();
|
||||||
|
this.router.navigate(['/login']);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private reportUnavailable(): Observable<never> {
|
private reportUnavailable(): Observable<never> {
|
||||||
this.error.set(UNAVAILABLE_MESSAGE);
|
this.error.set(UNAVAILABLE_MESSAGE);
|
||||||
return EMPTY;
|
return EMPTY;
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
export type Role = 'lecteur' | 'operateur' | 'admin';
|
||||||
|
|
||||||
|
export interface LoginRequest {
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PasswordChangeRequest {
|
||||||
|
current_password: string;
|
||||||
|
new_password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Principal {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
role: Role;
|
||||||
|
kind: 'human';
|
||||||
|
must_change_password: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TokenResponse {
|
||||||
|
access_token: string;
|
||||||
|
token_type: string;
|
||||||
|
expires_in: number;
|
||||||
|
principal: Principal;
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
export const environment = {
|
export const environment = {
|
||||||
production: true,
|
production: true,
|
||||||
apiUrl: 'http://localhost:8000/api/v1',
|
apiUrl: '/api/v1',
|
||||||
useMockFixtures: false,
|
useMockFixtures: false,
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user