add initial Angular components, services, and routing setup

This commit is contained in:
Vincent Guillet
2025-09-24 11:31:28 +02:00
parent dfb4ac302a
commit 18f0364e26
64 changed files with 15879 additions and 0 deletions

17
client/.editorconfig Normal file
View File

@@ -0,0 +1,17 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
ij_typescript_use_double_quotes = false
[*.md]
max_line_length = off
trim_trailing_whitespace = false

42
client/.gitignore vendored Normal file
View File

@@ -0,0 +1,42 @@
# See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db

14
client/Dockerfile Normal file
View File

@@ -0,0 +1,14 @@
# Dockerfile pour développement/demo Angular avec ng serve
FROM node:20
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 4200
CMD ["npx", "ng", "serve", "--host", "0.0.0.0"]

27
client/README.md Normal file
View File

@@ -0,0 +1,27 @@
# Client
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 18.2.21.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities.
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.

98
client/angular.json Normal file
View File

@@ -0,0 +1,98 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"client": {
"projectType": "application",
"schematics": {},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/client",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": [
"zone.js"
],
"tsConfig": "tsconfig.app.json",
"assets": [
{
"glob": "**/*",
"input": "public"
}
],
"styles": [
"@angular/material/prebuilt-themes/azure-blue.css",
"src/styles.css"
],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kB",
"maximumError": "1MB"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kB",
"maximumError": "4kB"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"buildTarget": "client:build:production"
},
"development": {
"buildTarget": "client:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n"
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": [
"zone.js",
"zone.js/testing"
],
"tsConfig": "tsconfig.spec.json",
"assets": [
{
"glob": "**/*",
"input": "public"
}
],
"styles": [
"@angular/material/prebuilt-themes/azure-blue.css",
"src/styles.css"
],
"scripts": []
}
}
}
}
}
}

14168
client/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

40
client/package.json Normal file
View File

@@ -0,0 +1,40 @@
{
"name": "client",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "^18.2.0",
"@angular/cdk": "^18.2.14",
"@angular/common": "^18.2.0",
"@angular/compiler": "^18.2.0",
"@angular/core": "^18.2.0",
"@angular/forms": "^18.2.0",
"@angular/material": "^18.2.14",
"@angular/platform-browser": "^18.2.0",
"@angular/platform-browser-dynamic": "^18.2.0",
"@angular/router": "^18.2.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.10"
},
"devDependencies": {
"@angular-devkit/build-angular": "^18.2.21",
"@angular/cli": "^18.2.21",
"@angular/compiler-cli": "^18.2.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.2.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.5.2"
}
}

BIN
client/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

View File

@@ -0,0 +1,2 @@
<app-navbar></app-navbar>
<router-outlet></router-outlet>

View File

@@ -0,0 +1,29 @@
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have the 'client' title`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('client');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('Hello, client');
});
});

View File

@@ -0,0 +1,14 @@
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import {NavbarComponent} from './components/navbar/navbar.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, NavbarComponent],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'client';
}

View File

@@ -0,0 +1,32 @@
import {APP_INITIALIZER, ApplicationConfig, inject, provideZoneChangeDetection} from '@angular/core';
import {provideRouter} from '@angular/router';
import {routes} from './app.routes';
import {provideHttpClient, withInterceptors} from '@angular/common/http';
import {provideAnimationsAsync} from '@angular/platform-browser/animations/async';
import {authTokenInterceptor} from './interceptors/authToken/auth-token.interceptor';
import {AuthService} from './services/auth/auth.service';
import {catchError, firstValueFrom, of} from 'rxjs';
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({eventCoalescing: true}),
provideRouter(routes),
provideAnimationsAsync(),
provideHttpClient(withInterceptors([
authTokenInterceptor
])
),
{
provide: APP_INITIALIZER,
multi: true,
useFactory: () => {
const auth = inject(AuthService);
return () => firstValueFrom(auth.bootstrapSession().pipe(
catchError(err => of(null))
)
);
}
}, provideAnimationsAsync()
]
};

View File

@@ -0,0 +1,54 @@
import { Routes } from '@angular/router';
import {HomeComponent} from './pages/home/home.component';
import {RegisterComponent} from './pages/register/register.component';
import {LoginComponent} from './pages/login/login.component';
import {ProfileComponent} from './pages/profile/profile.component';
import {guestOnlyCanActivate, guestOnlyCanMatch} from './guards/guest-only/guest-only.guard';
import {authOnlyCanMatch} from './guards/auth-only/auth-only.guard';
import {AdminComponent} from './pages/admin/admin.component';
import {adminOnlyCanMatch} from './guards/admin-only/admin-only.guard';
export const routes: Routes = [
{
path : '',
children: [
{
path : '',
component: HomeComponent
},
{
path : 'home',
component: HomeComponent
}
]
},
{
path: 'register',
component: RegisterComponent,
canMatch: [guestOnlyCanMatch],
canActivate: [guestOnlyCanActivate]
},
{
path : 'login',
component: LoginComponent,
canMatch: [guestOnlyCanMatch],
canActivate: [guestOnlyCanActivate]
},
{
path : 'profile',
component: ProfileComponent,
canMatch: [authOnlyCanMatch],
canActivate: [authOnlyCanMatch]
},
{
path : 'admin',
component: AdminComponent,
canMatch: [adminOnlyCanMatch],
canActivate: [adminOnlyCanMatch]
},
{
path : '**',
redirectTo: ''
}
];

View File

@@ -0,0 +1,24 @@
.container {
max-width: 1200px;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
}
.brand {
font-weight: bold;
font-size: 1.2rem;
cursor: pointer;
}
.nav-actions {
display: flex;
gap: 0.5rem;
align-items: center;
}
.mat-menu-item mat-icon {
margin-right: 8px;
}

View File

@@ -0,0 +1,33 @@
<mat-toolbar color="primary">
<div class="container">
<div class="brand" [routerLink]="'/'">Demo</div>
<div class="nav-actions">
@if (getUser(); as user) {
<button mat-button [matMenuTriggerFor]="userMenu">
<mat-icon>account_circle</mat-icon>
Logged in as {{ user.username }}
<mat-icon>expand_more</mat-icon>
</button>
<mat-menu #userMenu="matMenu">
@if (authService.hasRole('Administrator')) {
<button mat-menu-item [routerLink]="'/admin'">
<mat-icon>admin_panel_settings</mat-icon>
Admin
</button>
}
<button mat-menu-item [routerLink]="'/profile'">
<mat-icon>person</mat-icon>
Profile
</button>
<button mat-menu-item (click)="authService.logout().subscribe()">
<mat-icon>logout</mat-icon>
Logout
</button>
</mat-menu>
} @else {
<button mat-button [routerLink]="'/login'">Login</button>
<button mat-button [routerLink]="'/register'">Sign Up</button>
}
</div>
</div>
</mat-toolbar>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NavbarComponent } from './navbar.component';
describe('NavbarComponent', () => {
let component: NavbarComponent;
let fixture: ComponentFixture<NavbarComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [NavbarComponent]
})
.compileComponents();
fixture = TestBed.createComponent(NavbarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,47 @@
import {Component, inject} from '@angular/core';
import {MatToolbar} from '@angular/material/toolbar';
import {MatButton} from '@angular/material/button';
import {Router, RouterLink} from '@angular/router';
import {AuthService} from '../../services/auth/auth.service';
import {MatMenu, MatMenuItem, MatMenuTrigger} from '@angular/material/menu';
import {MatIcon} from '@angular/material/icon';
@Component({
selector: 'app-navbar',
standalone: true,
imports: [
MatToolbar,
MatButton,
RouterLink,
MatMenuTrigger,
MatIcon,
MatMenu,
MatMenuItem
],
templateUrl: './navbar.component.html',
styleUrl: './navbar.component.css'
})
export class NavbarComponent {
protected readonly authService = inject(AuthService);
private readonly router: Router = inject(Router);
login() {
this.router.navigate(['/login'], {queryParams: {redirect: '/profile'}}).then();
}
logout() {
this.authService.logout().subscribe({
next: () => {
this.login();
},
error: (err) => {
console.error('Logout failed:', err);
}
});
}
getUser() {
return this.authService.user();
}
}

View File

@@ -0,0 +1,17 @@
import { TestBed } from '@angular/core/testing';
import { CanActivateFn } from '@angular/router';
import { adminOnlyGuard } from './admin-only.guard';
describe('adminOnlyGuard', () => {
const executeGuard: CanActivateFn = (...guardParameters) =>
TestBed.runInInjectionContext(() => adminOnlyGuard(...guardParameters));
beforeEach(() => {
TestBed.configureTestingModule({});
});
it('should be created', () => {
expect(executeGuard).toBeTruthy();
});
});

View File

@@ -0,0 +1,27 @@
import { inject } from '@angular/core';
import { CanActivateFn, CanMatchFn, Router, UrlTree, ActivatedRouteSnapshot, Route } from '@angular/router';
import { AuthService } from '../../services/auth/auth.service';
function requireAdmin(url?: string): boolean | UrlTree {
const authService: AuthService = inject(AuthService);
const router: Router = inject(Router);
// 1) pas connecté -> envoie vers /login (avec redirect)
if (!authService.isLoggedIn()) {
return router.createUrlTree(['/login'], { queryParams: { redirect: url ?? router.url } });
}
// 2) connecté mais pas ADMIN -> redirige vers /home (ou /403 si tu crées une page)
if (!authService.hasRole('Administrator')) {
return router.parseUrl('/home');
}
// 3) ok
return true;
}
export const adminOnlyCanActivate: CanActivateFn = (route: ActivatedRouteSnapshot): boolean | UrlTree =>
requireAdmin(route?.url?.map(u => u.path).join('/') ?? '/admin');
export const adminOnlyCanMatch: CanMatchFn = (route: Route): boolean | UrlTree =>
requireAdmin(route?.path ?? '/admin');

View File

@@ -0,0 +1,17 @@
import { TestBed } from '@angular/core/testing';
import { CanMatchFn } from '@angular/router';
import { authOnlyGuard } from './auth-only.guard';
describe('authOnlyGuard', () => {
const executeGuard: CanMatchFn = (...guardParameters) =>
TestBed.runInInjectionContext(() => authOnlyGuard(...guardParameters));
beforeEach(() => {
TestBed.configureTestingModule({});
});
it('should be created', () => {
expect(executeGuard).toBeTruthy();
});
});

View File

@@ -0,0 +1,21 @@
import { inject } from '@angular/core';
import { CanActivateFn, CanMatchFn, Router, UrlTree, ActivatedRouteSnapshot, Route } from '@angular/router';
import { AuthService } from '../../services/auth/auth.service';
function requireAuth(url?: string): boolean | UrlTree {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.isLoggedIn()) {
return true;
}
// redirige vers /login avec un param "redirect"
return router.createUrlTree(['/login'], { queryParams: { redirect: url ?? router.url } });
}
export const authOnlyCanActivate: CanActivateFn = (route: ActivatedRouteSnapshot): boolean | UrlTree =>
requireAuth(route?.url?.map(urlSegment => urlSegment.path).join('/') ?? '/login');
export const authOnlyCanMatch: CanMatchFn = (route: Route): boolean | UrlTree =>
requireAuth(route?.path ?? '/login');

View File

@@ -0,0 +1,17 @@
import { TestBed } from '@angular/core/testing';
import { CanMatchFn } from '@angular/router';
import { guestOnlyGuard } from './guest-only.guard';
describe('guestOnlyGuard', () => {
const executeGuard: CanMatchFn = (...guardParameters) =>
TestBed.runInInjectionContext(() => guestOnlyGuard(...guardParameters));
beforeEach(() => {
TestBed.configureTestingModule({});
});
it('should be created', () => {
expect(executeGuard).toBeTruthy();
});
});

View File

@@ -0,0 +1,13 @@
import { inject } from '@angular/core';
import { Router, UrlTree, CanActivateFn, CanMatchFn } from '@angular/router';
import { AuthService } from '../../services/auth/auth.service';
function redirectIfLoggedIn(): boolean | UrlTree {
const authService = inject(AuthService);
const router = inject(Router);
// Si déjà connecté -> redirige vers /home
return authService.isLoggedIn() ? router.parseUrl('/home') : true;
}
export const guestOnlyCanMatch: CanMatchFn = () => redirectIfLoggedIn();
export const guestOnlyCanActivate: CanActivateFn = () => redirectIfLoggedIn();

View File

@@ -0,0 +1,17 @@
import { TestBed } from '@angular/core/testing';
import { HttpInterceptorFn } from '@angular/common/http';
import { authTokenInterceptor } from './auth-token.interceptor';
describe('authTokenInterceptor', () => {
const interceptor: HttpInterceptorFn = (req, next) =>
TestBed.runInInjectionContext(() => authTokenInterceptor(req, next));
beforeEach(() => {
TestBed.configureTestingModule({});
});
it('should be created', () => {
expect(interceptor).toBeTruthy();
});
});

View File

@@ -0,0 +1,45 @@
import {HttpErrorResponse, HttpInterceptorFn} from '@angular/common/http';
import {inject} from '@angular/core';
import {AuthService} from '../../services/auth/auth.service';
import {catchError, switchMap, throwError} from 'rxjs';
let isRefreshing = false;
export const authTokenInterceptor: HttpInterceptorFn = (req, next) => {
const authService: AuthService = inject(AuthService);
const token = authService.getAccessToken();
// Ajout de lAuthorization si on a un access token en mémoire
const authReq = token
? req.clone({setHeaders: {Authorization: `Bearer ${token}`}, withCredentials: true})
: req.clone({withCredentials: true});
return next(authReq).pipe(
catchError((error: any) => {
const is401 = error instanceof HttpErrorResponse && error.status === 401;
// si 401 et pas déjà en refresh, tente un refresh puis rejoue la requête 1 fois
if (is401 && !isRefreshing) {
isRefreshing = true;
return inject(AuthService).refresh().pipe(
switchMap(newToken => {
isRefreshing = false;
if (!newToken) return throwError(() => error);
const retryReq = req.clone({
setHeaders: {Authorization: `Bearer ${newToken}`},
withCredentials: true
});
return next(retryReq);
}),
catchError(err => {
isRefreshing = false;
return throwError(() => err);
})
);
}
return throwError(() => error);
})
);
};

View File

@@ -0,0 +1,7 @@
import { Credentials } from './credentials';
describe('Credentials', () => {
it('should create an instance', () => {
expect(new Credentials()).toBeTruthy();
});
});

View File

@@ -0,0 +1,4 @@
export interface Credentials {
username: string;
password: string;
}

View File

@@ -0,0 +1,7 @@
import { UserModel } from './user.model';
describe('UserModel', () => {
it('should create an instance', () => {
expect(new UserModel()).toBeTruthy();
});
});

View File

@@ -0,0 +1,7 @@
export class User {
firstName: string = '';
lastName: string = '';
username: string = '';
email: string = '';
role: string = '';
}

View File

@@ -0,0 +1 @@
<p>admin works!</p>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AdminComponent } from './admin.component';
describe('AdminComponent', () => {
let component: AdminComponent;
let fixture: ComponentFixture<AdminComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AdminComponent]
})
.compileComponents();
fixture = TestBed.createComponent(AdminComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,12 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-admin',
standalone: true,
imports: [],
templateUrl: './admin.component.html',
styleUrl: './admin.component.css'
})
export class AdminComponent {
}

View File

@@ -0,0 +1,13 @@
.home-container {
max-width: 800px;
margin: 0 auto;
padding: 2rem 1rem;
text-align: center;
}
.home-actions {
margin-top: 2rem;
display: flex;
justify-content: center;
gap: 1rem;
}

View File

@@ -0,0 +1,13 @@
<div class="home-container">
@if (getUser(); as user) {
<h1>Welcome, {{ user.firstName }}!</h1>
<p>What would you like to do today?</p>
} @else {
<h1>Welcome to the demo</h1>
<p>Create an account or sign in to get started.</p>
<div class="home-actions">
<button mat-flat-button [routerLink]="'/login'">Login</button>
<button mat-raised-button [routerLink]="'/register'">Sign Up</button>
</div>
}
</div>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HomeComponent } from './home.component';
describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [HomeComponent]
})
.compileComponents();
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,23 @@
import {Component, inject} from '@angular/core';
import {MatButton} from '@angular/material/button';
import {AuthService} from '../../services/auth/auth.service';
import {RouterLink} from '@angular/router';
@Component({
selector: 'app-home',
standalone: true,
imports: [
MatButton,
RouterLink
],
templateUrl: './home.component.html',
styleUrl: './home.component.css'
})
export class HomeComponent {
protected readonly authService: AuthService = inject(AuthService);
getUser() {
return this.authService.user();
}
}

View File

@@ -0,0 +1,20 @@
#container {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
form {
background-color: white;
padding: 20px;
border-radius: 10px;
display: flex;
flex-direction: column;
width: 400px;
}
mat-error {
text-align: center;
}

View File

@@ -0,0 +1,17 @@
<div id="container">
<form (submit)="login()" [formGroup]="loginFormGroup">
<h3>Sign in</h3>
<mat-form-field>
<mat-label>Username</mat-label>
<input matInput formControlName="username">
</mat-form-field>
<mat-form-field>
<mat-label>Password</mat-label>
<input matInput type="password" formControlName="password">
</mat-form-field>
<button mat-flat-button [disabled]="loginFormGroup.invalid">Login</button>
@if (invalidCredentials) {
<mat-error>Invalid credentials</mat-error>
}
</form>
</div>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { LoginComponent } from './login.component';
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [LoginComponent]
})
.compileComponents();
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,65 @@
import {Component, inject, OnDestroy} from '@angular/core';
import {MatError, MatFormField, MatLabel} from '@angular/material/form-field';
import {FormBuilder, ReactiveFormsModule, Validators} from '@angular/forms';
import {AuthService} from '../../services/auth/auth.service';
import {Router} from '@angular/router';
import {Subscription} from 'rxjs';
import {Credentials} from '../../interfaces/credentials/credentials';
import {User} from '../../models/user/user.model';
import {MatInput} from '@angular/material/input';
import {MatButton} from '@angular/material/button';
@Component({
selector: 'app-login',
standalone: true,
imports: [
MatFormField,
MatLabel,
MatError,
ReactiveFormsModule,
MatInput,
MatButton
],
templateUrl: './login.component.html',
styleUrl: './login.component.css'
})
export class LoginComponent implements OnDestroy {
private readonly formBuilder: FormBuilder = inject(FormBuilder);
private readonly authService: AuthService = inject(AuthService);
private readonly router: Router = inject(Router);
private loginSubscription: Subscription | null = null;
loginFormGroup = this.formBuilder.group({
username: ['', [
Validators.required
]],
password: ['', [
Validators.required
]]
});
invalidCredentials = false;
ngOnDestroy() {
this.loginSubscription?.unsubscribe();
}
login() {
this.loginSubscription = this.authService.login(
this.loginFormGroup.value as Credentials).subscribe({
next: (result: User | null | undefined) => {
this.navigateHome();
},
error: (error) => {
console.log(error);
this.invalidCredentials = true;
}
});
}
navigateHome() {
this.router.navigate(['/home']).then();
}
}

View File

@@ -0,0 +1 @@
<p>not-found works!</p>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NotFoundComponent } from './not-found.component';
describe('NotFoundComponent', () => {
let component: NotFoundComponent;
let fixture: ComponentFixture<NotFoundComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [NotFoundComponent]
})
.compileComponents();
fixture = TestBed.createComponent(NotFoundComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,12 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-not-found',
standalone: true,
imports: [],
templateUrl: './not-found.component.html',
styleUrl: './not-found.component.css'
})
export class NotFoundComponent {
}

View File

@@ -0,0 +1,72 @@
:host {
display: flex;
justify-content: center;
align-items: center;
min-height: 50vh;
}
.profile-card {
max-width: 380px;
width: 100%;
margin: 0 auto;
padding: 2rem 1.5rem 1.5rem 1.5rem;
border-radius: 18px;
box-shadow: 0 4px 24px rgba(25, 118, 210, 0.08);
background: #fff;
}
.profile-avatar {
background: #1976d2;
color: #fff;
width: 64px;
height: 64px;
font-size: 48px;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
box-shadow: 0 2px 8px rgba(25, 118, 210, 0.15);
}
.profile-actions {
display: flex;
justify-content: center;
gap: 1rem;
margin-top: 1.5rem;
}
mat-card-header {
flex-direction: column;
align-items: center;
text-align: center;
margin-bottom: 1rem;
}
mat-card-title {
font-size: 1.3rem;
font-weight: 600;
margin-top: 0.5rem;
}
mat-card-subtitle {
color: #888;
font-size: 1rem;
margin-bottom: 0.5rem;
}
mat-card-content p {
display: flex;
align-items: center;
gap: 10px;
margin: 1rem 0 0 0;
font-size: 1.05rem;
color: #444;
justify-content: center;
}
mat-card-actions {
display: flex;
justify-content: center;
margin-top: 1.5rem;
}

View File

@@ -0,0 +1,27 @@
@if (getUser(); as user) {
<mat-card class="profile-card">
<mat-card-header>
<div mat-card-avatar class="profile-avatar">
<mat-icon>account_circle</mat-icon>
</div>
<mat-card-title>{{ user.firstName }} {{ user.lastName }}</mat-card-title>
<mat-card-subtitle>{{ user.username }} ({{ user.role }})</mat-card-subtitle>
</mat-card-header>
<mat-card-content>
<p>
<mat-icon>email</mat-icon>
{{ user.email }}
</p>
</mat-card-content>
<mat-card-actions class="profile-actions">
<button mat-raised-button color="primary">
<mat-icon>edit</mat-icon>
Edit profile
</button>
<button mat-raised-button color="warn" (click)="logout()">
<mat-icon>logout</mat-icon>
Logout
</button>
</mat-card-actions>
</mat-card>
}

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ProfileComponent } from './profile.component';
describe('ProfileComponent', () => {
let component: ProfileComponent;
let fixture: ComponentFixture<ProfileComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ProfileComponent]
})
.compileComponents();
fixture = TestBed.createComponent(ProfileComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,51 @@
import {Component, inject} from '@angular/core';
import {
MatCard,
MatCardActions,
MatCardContent,
MatCardHeader,
MatCardSubtitle,
MatCardTitle
} from '@angular/material/card';
import {MatIcon} from '@angular/material/icon';
import {MatButton} from '@angular/material/button';
import {AuthService} from '../../services/auth/auth.service';
import {User} from '../../models/user/user.model';
import {Router} from '@angular/router';
@Component({
selector: 'app-profile',
standalone: true,
imports: [
MatCard,
MatCardHeader,
MatIcon,
MatCardTitle,
MatCardSubtitle,
MatCardContent,
MatCardActions,
MatButton
],
templateUrl: './profile.component.html',
styleUrl: './profile.component.css'
})
export class ProfileComponent {
private readonly authService: AuthService = inject(AuthService);
private readonly router: Router = inject(Router);
logout() {
this.authService.logout().subscribe({
next: () => {
this.router.navigate(['/login'], {queryParams: {redirect: '/profile'}}).then();
},
error: (err) => {
console.error('Logout failed:', err);
}
});
}
getUser(): User | null {
return this.authService.user();
}
}

View File

@@ -0,0 +1,32 @@
.auth-wrap {
min-height: 100vh;
display: grid;
place-items: center;
padding: 16px;
}
.auth-card {
width: 100%;
max-width: 520px;
}
.form-grid {
display: grid;
gap: 16px;
margin-top: 16px;
}
.actions {
display: flex;
margin: 8px;
button {
display: inline-flex;
align-items: center;
gap: 8px;
}
}
.ml-8 {
margin-left: 8px;
}

View File

@@ -0,0 +1,137 @@
<section class="auth-wrap">
<mat-card class="auth-card">
<mat-card-header>
<mat-card-title>Registration</mat-card-title>
<mat-card-subtitle>Create a new account</mat-card-subtitle>
</mat-card-header>
<mat-card-content>
<form [formGroup]="registerForm" (ngSubmit)="onRegister()" class="form-grid">
<!-- First Name -->
<mat-form-field appearance="outline">
<mat-label>First Name</mat-label>
<input matInput
id="firstName"
name="firstName"
formControlName="firstName"
type="text"
autocomplete="given-name"
required>
@if (isFieldInvalid('firstName')) {
<mat-error>{{ getFieldError('firstName') }}</mat-error>
}
</mat-form-field>
<!-- Last Name -->
<mat-form-field appearance="outline">
<mat-label>Last Name</mat-label>
<input matInput
id="lastName"
name="lastName"
formControlName="lastName"
type="text"
autocomplete="family-name"
required>
@if (isFieldInvalid('lastName')) {
<mat-error>{{ getFieldError('lastName') }}</mat-error>
}
</mat-form-field>
<!-- Username -->
<mat-form-field appearance="outline">
<mat-label>Username</mat-label>
<input matInput
id="username"
name="username"
formControlName="username"
type="text"
autocomplete="username"
required>
@if (isFieldInvalid('username')) {
<mat-error>{{ getFieldError('username') }}</mat-error>
}
</mat-form-field>
<!-- Email -->
<mat-form-field appearance="outline">
<mat-label>Email</mat-label>
<input matInput
id="email"
name="email"
formControlName="email"
type="email"
autocomplete="email"
required>
@if (isFieldInvalid('email')) {
<mat-error>{{ getFieldError('email') }}</mat-error>
}
</mat-form-field>
<!-- Password -->
<mat-form-field appearance="outline">
<mat-label>Password</mat-label>
<input matInput
id="password"
name="password"
formControlName="password"
type="password"
autocomplete="new-password"
required>
@if (isFieldInvalid('password')) {
<mat-error>{{ getFieldError('password') }}</mat-error>
}
</mat-form-field>
<!-- Password confirmation -->
<mat-form-field appearance="outline">
<mat-label>Confirm Password</mat-label>
<input matInput
id="confirmPassword"
name="confirmPassword"
formControlName="confirmPassword"
type="password"
autocomplete="new-password"
required>
@if (isFieldInvalid('confirmPassword')) {
<mat-error>{{ getFieldError('confirmPassword') }}</mat-error>
}
</mat-form-field>
@if (registerForm.hasError('passwordMismatch') && (registerForm.dirty || registerForm.touched || isSubmitted)) {
<mat-error>Les mots de passe ne correspondent pas</mat-error>
}
<!-- Terms and Conditions -->
<mat-checkbox formControlName="termsAndConditions" id="iAgree">
I agree to the <a href="#" target="_blank" rel="noopener">terms and conditions</a>
</mat-checkbox>
@if (isFieldInvalid('termsAndConditions')) {
<div class="mat-caption mat-error">{{ getFieldError('termsAndConditions') }}</div>
}
<!-- Submit Button -->
<div class="actions">
<button mat-raised-button color="primary"
type="submit"
[disabled]="isLoading || registerForm.invalid">
@if (isLoading) {
<mat-progress-spinner diameter="16" mode="indeterminate"></mat-progress-spinner>
<span class="ml-8">Signing up…</span>
} @else {
Sign up
}
</button>
</div>
</form>
</mat-card-content>
<mat-divider></mat-divider>
<mat-card-actions align="end">
<span class="mat-body-small">
Already have an account?
<a [routerLink]="'/login'">Sign in</a>
</span>
</mat-card-actions>
</mat-card>
</section>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RegisterComponent } from './register.component';
describe('RegisterComponent', () => {
let component: RegisterComponent;
let fixture: ComponentFixture<RegisterComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [RegisterComponent]
})
.compileComponents();
fixture = TestBed.createComponent(RegisterComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,157 @@
import {Component, inject, OnDestroy} from '@angular/core';
import {
AbstractControl,
FormBuilder,
FormGroup,
ReactiveFormsModule,
ValidationErrors,
ValidatorFn,
Validators
} from '@angular/forms';
import {Router, RouterLink} from '@angular/router';
import {MatError, MatFormField, MatLabel} from '@angular/material/form-field';
import {MatInput} from '@angular/material/input';
import {
MatCard,
MatCardActions,
MatCardContent,
MatCardHeader,
MatCardSubtitle,
MatCardTitle
} from '@angular/material/card';
import {MatProgressSpinner} from '@angular/material/progress-spinner';
import {MatDivider} from '@angular/material/divider';
import {AuthService} from '../../services/auth/auth.service';
import {MatCheckbox} from '@angular/material/checkbox';
import {MatButton} from '@angular/material/button';
import {Subscription} from 'rxjs';
@Component({
selector: 'app-register',
standalone: true,
imports: [
MatError,
MatFormField,
MatLabel,
MatInput,
MatCard,
MatCardHeader,
MatCardTitle,
MatCardSubtitle,
MatCardContent,
ReactiveFormsModule,
MatProgressSpinner,
MatDivider,
MatCardActions,
RouterLink,
MatCheckbox,
MatButton
],
templateUrl: './register.component.html',
styleUrl: './register.component.css'
})
export class RegisterComponent implements OnDestroy {
registerForm: FormGroup;
isSubmitted = false;
isLoading = false;
private readonly router: Router = inject(Router);
private readonly authService: AuthService = inject(AuthService);
private registerSubscription: Subscription | null = null;
constructor(private readonly formBuilder: FormBuilder) {
this.registerForm = this.formBuilder.group({
firstName: ['', [
Validators.required,
Validators.minLength(3),
Validators.maxLength(50),
Validators.pattern('^[a-zA-Z]+$')
]],
lastName: ['', [
Validators.required,
Validators.minLength(3),
Validators.maxLength(50),
Validators.pattern('^[a-zA-Z]+$')
]],
username: ['', [
Validators.required,
Validators.minLength(3),
Validators.maxLength(20),
Validators.pattern('^[a-zA-Z0-9_]+$')
]],
email: ['', [
Validators.required,
Validators.minLength(3),
Validators.maxLength(120),
Validators.email
]],
password: ['', [
Validators.required,
Validators.minLength(8),
Validators.maxLength(20),
Validators.pattern('^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$')
]],
confirmPassword: ['', [
Validators.required,
Validators.minLength(8),
Validators.maxLength(20),
Validators.pattern('^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$')
]],
termsAndConditions: [false, Validators.requiredTrue]
}, {validators: this.passwordMatchValidator});
}
ngOnDestroy(): void {
this.registerSubscription?.unsubscribe();
}
private readonly passwordMatchValidator: ValidatorFn = (group: AbstractControl): ValidationErrors | null => {
const password = group.get('password')?.value;
const confirmPassword = group.get('confirmPassword')?.value;
return password === confirmPassword ? null : {passwordMismatch: true};
};
onRegister() {
this.isSubmitted = true;
if (this.registerForm.valid) {
this.isLoading = true;
const registrationData = this.registerForm.value;
delete registrationData.confirmPassword;
this.registerSubscription = this.authService.register(registrationData).subscribe({
next: (response) => {
this.isLoading = false;
this.registerForm.reset();
this.isSubmitted = false;
alert("Registration successful!");
this.router.navigate(['/']).then();
},
error: (error) => {
console.error('Erreur HTTP:', error);
this.isLoading = false;
alert("An error occurred during registration. Please try again.");
}
});
}
}
isFieldInvalid(fieldName: string): boolean {
const field = this.registerForm.get(fieldName);
return Boolean(field && field.invalid && (field.dirty || field.touched || this.isSubmitted));
}
getFieldError(fieldName: string): string {
const field = this.registerForm.get(fieldName);
if (field && field.errors) {
if (field.errors['required']) return `Ce champ est obligatoire`;
if (field.errors['email']) return `Format d'email invalide`;
if (field.errors['minlength']) return `Minimum ${field.errors['minlength'].requiredLength} caractères`;
if (field.errors['maxlength']) return `Maximum ${field.errors['maxlength'].requiredLength} caractères`;
}
return '';
}
}

View File

@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { AuthService } from './auth.service';
describe('LoginService', () => {
let service: AuthService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(AuthService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@@ -0,0 +1,88 @@
import {inject, Injectable, signal} from '@angular/core';
import {catchError, map, of, switchMap, tap} from 'rxjs';
import {Credentials} from '../../interfaces/credentials/credentials';
import {HttpClient} from '@angular/common/http';
import {User} from '../../models/user/user.model';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private readonly http = inject(HttpClient);
private readonly BASE_URL = 'http://localhost:3000/api/auth';
readonly user = signal<User | null>(null);
private readonly accessToken = signal<string | null>(null);
register(user: User) {
return this.http.post(this.BASE_URL + '/register', user, {withCredentials: true});
}
login(credentials: Credentials) {
return this.http.post<any>(this.BASE_URL + '/login', credentials, {withCredentials: true}).pipe(
tap(res => this.accessToken.set(res?.accessToken ?? null)),
switchMap(() => this.me())
);
}
logout() {
return this.http.get(this.BASE_URL + '/logout', {withCredentials: true}).pipe(
tap(() => {
this.accessToken.set(null);
this.user.set(null);
}),
map(() => null)
);
}
// Charge l'utilisateur courant (protégé)
me() {
return this.http.get<User>(this.BASE_URL + '/me', {withCredentials: true}).pipe(
tap(u => this.user.set(u)),
map(() => this.user()),
catchError(() => {
this.user.set(null);
return of(null);
})
);
}
// Demande un nouvel access token via le cookie HttpOnly
refresh() {
return this.http.post<any>(this.BASE_URL + '/refresh', {}, {
withCredentials: true,
observe: 'response'
}).pipe(
map(res => {
const token = (res.body as any)?.accessToken ?? null;
this.accessToken.set(token);
return token;
}),
catchError(() => of(null))
);
}
// Au démarrage de l'app, tenter transparence session -> doit TOUJOURS compléter
bootstrapSession() {
return this.refresh().pipe(
switchMap(token => token ? this.me() : of(null)),
catchError(() => of(null)) // <- sécurité supplémentaire
);
}
isLoggedIn(): boolean {
return this.user() !== null;
}
hasRole(role: string): boolean {
const user: User | null = this.user();
if (!user) return false;
const roles = Array.isArray((user as any).roles) ? (user as any).roles : [(user as any).role];
return roles?.includes(role) ?? false;
}
getAccessToken(): string | null {
return this.accessToken();
}
}

View File

@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { UserService } from './user.service';
describe('UserService', () => {
let service: UserService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(UserService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@@ -0,0 +1,9 @@
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor() { }
}

15
client/src/index.html Normal file
View File

@@ -0,0 +1,15 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Demo</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body class="mat-typography">
<app-root></app-root>
</body>
</html>

6
client/src/main.ts Normal file
View File

@@ -0,0 +1,6 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));

12
client/src/styles.css Normal file
View File

@@ -0,0 +1,12 @@
body, html {
font-family: Roboto, sans-serif;
height: 100%;
background: linear-gradient(
135deg,
rgb(245, 245, 245),
rgb(230, 230, 230)
);
}
html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }

15
client/tsconfig.app.json Normal file
View File

@@ -0,0 +1,15 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts"
],
"include": [
"src/**/*.d.ts"
]
}

33
client/tsconfig.json Normal file
View File

@@ -0,0 +1,33 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"isolatedModules": true,
"esModuleInterop": true,
"sourceMap": true,
"declaration": false,
"experimentalDecorators": true,
"moduleResolution": "bundler",
"importHelpers": true,
"target": "ES2022",
"module": "ES2022",
"lib": [
"ES2022",
"dom"
]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}

15
client/tsconfig.spec.json Normal file
View File

@@ -0,0 +1,15 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
},
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}