Updated auth config
All checks were successful
Gitea/swiss-client/pipeline/head This commit looks good

This commit is contained in:
2025-10-08 21:36:13 +02:00
parent 0fd693aa42
commit 8083e7fc5f
13 changed files with 225 additions and 62 deletions

10
package-lock.json generated
View File

@@ -25,6 +25,7 @@
"@popperjs/core": "^2.11.8", "@popperjs/core": "^2.11.8",
"bootstrap": "^5.3.7", "bootstrap": "^5.3.7",
"express": "^4.21.2", "express": "^4.21.2",
"jwt-decode": "^4.0.0",
"moment": "2.30.1", "moment": "2.30.1",
"ngx-cookie-service-ssr": "^20.1.0", "ngx-cookie-service-ssr": "^20.1.0",
"ngx-mask": "^20.0.3", "ngx-mask": "^20.0.3",
@@ -6835,6 +6836,15 @@
], ],
"license": "MIT" "license": "MIT"
}, },
"node_modules/jwt-decode": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz",
"integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==",
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/karma": { "node_modules/karma": {
"version": "6.4.4", "version": "6.4.4",
"resolved": "https://registry.npmjs.org/karma/-/karma-6.4.4.tgz", "resolved": "https://registry.npmjs.org/karma/-/karma-6.4.4.tgz",

View File

@@ -28,6 +28,7 @@
"@popperjs/core": "^2.11.8", "@popperjs/core": "^2.11.8",
"bootstrap": "^5.3.7", "bootstrap": "^5.3.7",
"express": "^4.21.2", "express": "^4.21.2",
"jwt-decode": "^4.0.0",
"moment": "2.30.1", "moment": "2.30.1",
"ngx-cookie-service-ssr": "^20.1.0", "ngx-cookie-service-ssr": "^20.1.0",
"ngx-mask": "^20.0.3", "ngx-mask": "^20.0.3",

View File

@@ -17,10 +17,10 @@
<mat-icon>group</mat-icon> <mat-icon>group</mat-icon>
Spelers Spelers
</a> </a>
@if (this.userService.isLoggedIn()) { @if (this.authService.isLoggedIn()) {
<button mat-flat-button [matMenuTriggerFor]="accountMenu"> <button mat-flat-button [matMenuTriggerFor]="accountMenu">
<mat-icon>person</mat-icon> <mat-icon>person</mat-icon>
{{ user }} {{ this.authService.getUsername() }}
</button> </button>
<mat-menu #accountMenu="matMenu"> <mat-menu #accountMenu="matMenu">
<button mat-menu-item (click)="logOut()"> <button mat-menu-item (click)="logOut()">

View File

@@ -6,9 +6,10 @@ import {MatIcon} from "@angular/material/icon";
import {MatToolbar} from "@angular/material/toolbar"; import {MatToolbar} from "@angular/material/toolbar";
import {filter, map, Subscription} from "rxjs"; import {filter, map, Subscription} from "rxjs";
import {MatMenu, MatMenuItem, MatMenuTrigger} from "@angular/material/menu"; import {MatMenu, MatMenuItem, MatMenuTrigger} from "@angular/material/menu";
import {UserService} from "./authentication/user.service"; // import {UserService} from "./authentication/user.service";
import {TournamentService} from "./service/tournament.service"; import {TournamentService} from "./service/tournament.service";
import {HeaderService} from "./service/header.service"; import {HeaderService} from "./service/header.service";
import {AuthService} from "./auth/auth.service";
@Component({ @Component({
selector: 'app-root', selector: 'app-root',
@@ -19,11 +20,11 @@ import {HeaderService} from "./service/header.service";
export class AppComponent implements OnInit { export class AppComponent implements OnInit {
header: string; header: string;
user: string; // user: string;
userSubscription: Subscription; // userSubscription: Subscription;
constructor( constructor(
protected userService: UserService, protected authService: AuthService,
private router: Router, private router: Router,
protected activatedRoute: ActivatedRoute, protected activatedRoute: ActivatedRoute,
private tournamentService: TournamentService, private tournamentService: TournamentService,
@@ -32,7 +33,7 @@ export class AppComponent implements OnInit {
} }
ngOnInit() { ngOnInit() {
this.userSubscription = this.userService.currentUser.subscribe(newUser => this.user = newUser); // this.userSubscription = this.userService.currentUser.subscribe(newUser => this.user = newUser);
this.router.events.pipe( this.router.events.pipe(
filter(event => event instanceof NavigationEnd), filter(event => event instanceof NavigationEnd),
@@ -55,8 +56,8 @@ export class AppComponent implements OnInit {
} }
logOut() { logOut() {
this.userService.removeUser(); this.authService.logout();
this.router.navigate(['/auth/login']); this.router.navigate(['/login']);
} }
addTestData() { addTestData() {

View File

@@ -13,6 +13,7 @@ import {ErrorInterceptor} from "./authentication/errorInterceptor";
import {provideNgxMask} from "ngx-mask"; import {provideNgxMask} from "ngx-mask";
import {UserService} from './authentication/user.service'; import {UserService} from './authentication/user.service';
import {provideAnimations} from "@angular/platform-browser/animations"; import {provideAnimations} from "@angular/platform-browser/animations";
import {AuthInterceptor} from "./auth/auth.interceptor";
export const appConfig: ApplicationConfig = { export const appConfig: ApplicationConfig = {
providers: [ providers: [
@@ -28,8 +29,8 @@ export const appConfig: ApplicationConfig = {
provideMomentDateAdapter(undefined, {useUtc: false}), provideMomentDateAdapter(undefined, {useUtc: false}),
{ provide: MAT_SNACK_BAR_DEFAULT_OPTIONS, useValue: { duration: 2500}}, { provide: MAT_SNACK_BAR_DEFAULT_OPTIONS, useValue: { duration: 2500}},
AuthGuard, AuthGuard,
{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, // { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
provideNgxMask(), provideNgxMask(),
] ]
}; };

View File

@@ -8,24 +8,24 @@ import {TournamentDrawComponent} from "./components/tournament-draw/tournament-d
import {TournamentManageComponent} from "./components/tournament-manage/tournament-manage.component"; import {TournamentManageComponent} from "./components/tournament-manage/tournament-manage.component";
import {MatchSheetsComponent} from "./components/match-sheets/match-sheets.component"; import {MatchSheetsComponent} from "./components/match-sheets/match-sheets.component";
import {RoundOverviewComponent} from "./components/round-overview/round-overview.component"; import {RoundOverviewComponent} from "./components/round-overview/round-overview.component";
import {AuthGuard} from "./authentication/authguard";
import {LoginComponent} from "./components/login/login.component"; import {LoginComponent} from "./components/login/login.component";
import {TournamentPlayersComponent} from "./components/tournament-players/tournament-players.component"; import {TournamentPlayersComponent} from "./components/tournament-players/tournament-players.component";
import {AuthGuard} from "./auth/auth-guard.service";
export const routes: Routes = [ export const routes: Routes = [
{ path: '', component: TournamentListComponent, canActivate: [AuthGuard], data: { header: 'Toernooien' }}, { path: '', component: TournamentListComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Toernooien' }},
{ path: 'tournaments', component: TournamentListComponent, canActivate: [AuthGuard], data: { header: 'Toernooien' }}, { path: 'tournaments', component: TournamentListComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Toernooien' }},
{ path: 'tournaments/add', component: TournamentEditComponent, canActivate: [AuthGuard], data: { header: 'Nieuw Toernooi' }}, { path: 'tournaments/add', component: TournamentEditComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Nieuw Toernooi' }},
{ path: 'tournaments/:id/edit', component: TournamentEditComponent, canActivate: [AuthGuard], data: { header: 'Bewerk Toernooi' }}, { path: 'tournaments/:id/edit', component: TournamentEditComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Bewerk Toernooi' }},
{ path: 'tournaments/:id/registrations', component: TournamentPlayersComponent, canActivate: [AuthGuard], data: { header: 'Inschrijvingen' }}, { path: 'tournaments/:id/registrations', component: TournamentPlayersComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Inschrijvingen' }},
{ path: 'tournaments/:id/draw', component: TournamentDrawComponent, canActivate: [AuthGuard], data: { header: 'Toernooi loten' }}, { path: 'tournaments/:id/draw', component: TournamentDrawComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Toernooi loten' }},
{ path: 'tournaments/:id/manage', component: TournamentManageComponent, canActivate: [AuthGuard]}, { path: 'tournaments/:id/manage', component: TournamentManageComponent, canActivate: [AuthGuard]},
{ path: 'tournaments/:id/manage/:tab', component: TournamentManageComponent, canActivate: [AuthGuard], data: { header: 'Toernooien' }}, { path: 'tournaments/:id/manage/:tab', component: TournamentManageComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Toernooien' }},
{ path: 'players', component: PlayerListComponent, canActivate: [AuthGuard], data: { header: 'Spelers' }}, { path: 'players', component: PlayerListComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Spelers' }},
{ path: 'players/add', component: PlayerEditComponent, canActivate: [AuthGuard], data: { header: 'Nieuwe Speler' }}, { path: 'players/add', component: PlayerEditComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Nieuwe Speler' }},
{ path: 'players/:id/edit', component: PlayerEditComponent, canActivate: [AuthGuard], data: { header: 'Bewerk Speler' }}, { path: 'players/:id/edit', component: PlayerEditComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Bewerk Speler' }},
{ path: 'players/:id/registrations', component: PlayerRegistrationsComponent, canActivate: [AuthGuard]}, { path: 'players/:id/registrations', component: PlayerRegistrationsComponent, canActivate: [AuthGuard]},
{ path: 'tournaments/:id/rounds/:roundId/matchsheets', component: MatchSheetsComponent, canActivate: [AuthGuard]}, { path: 'tournaments/:id/rounds/:roundId/matchsheets', component: MatchSheetsComponent, canActivate: [AuthGuard]},
{ path: 'tournaments/:id/rounds/:roundId/overview', component: RoundOverviewComponent, canActivate: [AuthGuard], data: { header: 'Rondeoverzicht' }}, { path: 'tournaments/:id/rounds/:roundId/overview', component: RoundOverviewComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Rondeoverzicht' }},
{ path: 'auth/login', component: LoginComponent, data: { header: 'Inloggen'}} { path: 'login', component: LoginComponent, data: { header: 'Inloggen'}}
]; ];

View File

@@ -0,0 +1,22 @@
import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {AuthService} from './auth.service';
@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {
}
public canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.authService.isLoggedIn() && this.authService.isUserInRole(next.routeConfig?.data?.['role'])) {
return true;
} else {
// this.router.navigateByUrl("/login");
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
}
}

View File

@@ -0,0 +1,35 @@
import {Injectable} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {catchError, Observable, throwError} from 'rxjs';
import {Router} from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthInterceptor implements HttpInterceptor {
constructor(private router: Router) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let token = sessionStorage.getItem("app.token");
if (token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`
},
});
}
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => this.handleErrorRes(error))
);
}
private handleErrorRes(error: HttpErrorResponse): Observable<never> {
if (error.status === 401) {
this.router.navigateByUrl("/login", {replaceUrl: true});
}
return throwError(() => error);
}
}

View File

@@ -0,0 +1,86 @@
import {Inject, Injectable, PLATFORM_ID} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {environment} from "../../environments/environment";
import {isPlatformBrowser} from "@angular/common";
import {jwtDecode, JwtPayload} from "jwt-decode";
@Injectable({
providedIn: 'root'
})
export class AuthService {
private readonly authUrl: string
constructor(private http: HttpClient,
@Inject(PLATFORM_ID) private platformId: Object) {
this.authUrl = `${environment.backendUrl}/api/auth`;
}
private get isBrowser(): boolean {
return isPlatformBrowser(this.platformId);
}
isLoggedIn(): boolean {
if (!this.isBrowser) return false;
return sessionStorage.getItem("app.token") != null;
}
login(username: string, password: string): Observable<string> {
if (!this.isBrowser) {
throw new Error('Login can only be performed in browser');
}
const credentials = btoa(`${username}:${password}`);
const httpOptions = {
headers: {
'Authorization': `Basic ${credentials}`,
'Content-Type': 'application/json'
},
responseType: 'text' as 'text',
};
return this.http.post(this.authUrl, null, httpOptions);
}
logout() {
if (!this.isBrowser) return;
sessionStorage.removeItem("app.token");
sessionStorage.removeItem("app.roles");
}
isUserInRole(roleFromRoute: string) {
if (!this.isBrowser) return false;
const roles = sessionStorage.getItem("app.roles");
if (roles!.includes(",")) {
if (roles === roleFromRoute) {
return true;
}
} else {
const roleArray = roles!.split(",");
for (let role of roleArray) {
if (role === roleFromRoute) {
return true;
}
}
}
return false;
}
getUsername(): string | null {
if (!this.isBrowser) return null;
const token = sessionStorage.getItem("app.token");
if (!token) return null;
try {
const decodedToken = jwtDecode<JwtPayload>(token);
return decodedToken.sub || null; // 'sub' is the standard JWT claim for subject/username
} catch (error) {
console.error('Error decoding token:', error);
return null;
}
}
}

View File

@@ -1,22 +1,23 @@
<mat-card> <mat-card>
<mat-card-content> <mat-card-content>
<form class="form-horizontal" [formGroup]="form"> <form class="form-horizontal" (ngSubmit)="login()">
<div class="row"> <div class="row">
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Gebruikersnaam</mat-label> <mat-label>Gebruikersnaam</mat-label>
<input matInput placeholder="Gebruikersnaam" formControlName="username" required> <input matInput name="username" placeholder="Gebruikersnaam" required [(ngModel)]="username">
</mat-form-field> </mat-form-field>
</div> </div>
<div class="row"> <div class="row">
<mat-form-field appearance="outline"> <mat-form-field appearance="outline">
<mat-label>Wachtwoord</mat-label> <mat-label>Wachtwoord</mat-label>
<input matInput placeholder="Wachtwoord" type="password" formControlName="password" required> <input matInput name="password" placeholder="Wachtwoord" type="password" required [(ngModel)]="password">
</mat-form-field> </mat-form-field>
</div> </div>
<button class="w-100 mt-2" mat-button mat-flat-button color="primary" <button class="w-100 mt-2" mat-button mat-flat-button color="primary"
(click)="login()" [disabled]="form.invalid"> (click)="login()">
Inloggen Inloggen
</button> </button>
</form> </form>
<p>{{message}}</p>
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>

View File

@@ -1,4 +1,4 @@
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms'; import {FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators} from '@angular/forms';
import {Component, OnInit} from '@angular/core'; import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router, RouterLink} from '@angular/router'; import {ActivatedRoute, Router, RouterLink} from '@angular/router';
import {MatCard, MatCardContent, MatCardHeader, MatCardTitle} from "@angular/material/card"; import {MatCard, MatCardContent, MatCardHeader, MatCardTitle} from "@angular/material/card";
@@ -10,6 +10,9 @@ import {AuthenticationService} from "../../authentication/authentication.service
import {UserService} from "../../authentication/user.service"; import {UserService} from "../../authentication/user.service";
import {LoginCredentials} from "../../authentication/loginCredentials"; import {LoginCredentials} from "../../authentication/loginCredentials";
import {User} from "../../authentication/user"; import {User} from "../../authentication/user";
import {jwtDecode, JwtPayload} from "jwt-decode";
import {AuthService} from "../../auth/auth.service";
import {MatSnackBar} from "@angular/material/snack-bar";
@Component({ @Component({
@@ -23,6 +26,7 @@ import {User} from "../../authentication/user";
MatInput, MatInput,
MatLabel, MatLabel,
MatCard, MatCard,
FormsModule,
], ],
standalone: true, standalone: true,
styleUrls: ['./login.component.scss'] styleUrls: ['./login.component.scss']
@@ -32,48 +36,46 @@ export class LoginComponent implements OnInit {
private returnUrl: string; private returnUrl: string;
private ipAddress: string; private ipAddress: string;
constructor( username: string = "";
private route: ActivatedRoute, password: string = "";
private fb: FormBuilder, message: string = "";
private authenticationService: AuthenticationService,
private router: Router, constructor(private authService: AuthService,
private userPersistenceService: UserService, private route: ActivatedRoute,
) { private router: Router,
this.initializeForm(); private snackBar: MatSnackBar) {
} }
private initializeForm() {
this.form = this.fb.group({
username: ['', [Validators.required]],
password: ['', [Validators.required]],
});
}
ngOnInit() { ngOnInit() {
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
} }
login() { public login(): void {
if (this.form.invalid) { console.log('Na inloggen door naar' + this.returnUrl);
return; sessionStorage.removeItem("app.token");
}
let loginCredentials = new LoginCredentials(); this.authService.login(this.username, this.password)
loginCredentials = { .subscribe({
...loginCredentials, next: (token) => {
...this.form.value, console.log('Login successful');
}; sessionStorage.setItem("app.token", token);
this.authenticationService const decodedToken = jwtDecode<JwtPayload>(token);
.login(loginCredentials) // @ts-ignore
.subscribe( sessionStorage.setItem("app.roles", decodedToken.scope);
{
next: (user: User) => { // this.router.navigateByUrl("/persons");
this.userPersistenceService.setUser(user); console.log('Let us go to {url}', this.returnUrl);
this.router.navigate([this.returnUrl]);
} // this.router.navigate([this.returnUrl]);
this.router.navigate([this.route.snapshot.queryParams['returnUrl'] || '/']);
},
error: (error) => {
console.log('Login unsuccesful');
this.snackBar.open(`Login failed: ${error.status}`, "OK")
} }
); });
} }
} }

View File

@@ -45,7 +45,6 @@ export class PlayerEditComponent implements OnInit {
player: Player; player: Player;
isEditMode: boolean = false; isEditMode: boolean = false;
constructor( constructor(
private playerService: PlayerService, private playerService: PlayerService,
private route: ActivatedRoute, private route: ActivatedRoute,

View File

@@ -3114,6 +3114,11 @@ jsonparse@^1.3.1:
resolved "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz" resolved "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz"
integrity sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg== integrity sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg==
jwt-decode@^4.0.0:
version "4.0.0"
resolved "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz"
integrity sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==
karma-chrome-launcher@~3.2.0: karma-chrome-launcher@~3.2.0:
version "3.2.0" version "3.2.0"
resolved "https://registry.npmjs.org/karma-chrome-launcher/-/karma-chrome-launcher-3.2.0.tgz" resolved "https://registry.npmjs.org/karma-chrome-launcher/-/karma-chrome-launcher-3.2.0.tgz"