Updated auth config
All checks were successful
Gitea/swiss-client/pipeline/head This commit looks good
All checks were successful
Gitea/swiss-client/pipeline/head This commit looks good
This commit is contained in:
@@ -17,10 +17,10 @@
|
||||
<mat-icon>group</mat-icon>
|
||||
Spelers
|
||||
</a>
|
||||
@if (this.userService.isLoggedIn()) {
|
||||
@if (this.authService.isLoggedIn()) {
|
||||
<button mat-flat-button [matMenuTriggerFor]="accountMenu">
|
||||
<mat-icon>person</mat-icon>
|
||||
{{ user }}
|
||||
{{ this.authService.getUsername() }}
|
||||
</button>
|
||||
<mat-menu #accountMenu="matMenu">
|
||||
<button mat-menu-item (click)="logOut()">
|
||||
|
||||
@@ -6,9 +6,10 @@ import {MatIcon} from "@angular/material/icon";
|
||||
import {MatToolbar} from "@angular/material/toolbar";
|
||||
import {filter, map, Subscription} from "rxjs";
|
||||
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 {HeaderService} from "./service/header.service";
|
||||
import {AuthService} from "./auth/auth.service";
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
@@ -19,11 +20,11 @@ import {HeaderService} from "./service/header.service";
|
||||
export class AppComponent implements OnInit {
|
||||
|
||||
header: string;
|
||||
user: string;
|
||||
userSubscription: Subscription;
|
||||
// user: string;
|
||||
// userSubscription: Subscription;
|
||||
|
||||
constructor(
|
||||
protected userService: UserService,
|
||||
protected authService: AuthService,
|
||||
private router: Router,
|
||||
protected activatedRoute: ActivatedRoute,
|
||||
private tournamentService: TournamentService,
|
||||
@@ -32,7 +33,7 @@ export class AppComponent implements OnInit {
|
||||
}
|
||||
|
||||
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(
|
||||
filter(event => event instanceof NavigationEnd),
|
||||
@@ -55,8 +56,8 @@ export class AppComponent implements OnInit {
|
||||
}
|
||||
|
||||
logOut() {
|
||||
this.userService.removeUser();
|
||||
this.router.navigate(['/auth/login']);
|
||||
this.authService.logout();
|
||||
this.router.navigate(['/login']);
|
||||
}
|
||||
|
||||
addTestData() {
|
||||
|
||||
@@ -13,6 +13,7 @@ import {ErrorInterceptor} from "./authentication/errorInterceptor";
|
||||
import {provideNgxMask} from "ngx-mask";
|
||||
import {UserService} from './authentication/user.service';
|
||||
import {provideAnimations} from "@angular/platform-browser/animations";
|
||||
import {AuthInterceptor} from "./auth/auth.interceptor";
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
@@ -28,8 +29,8 @@ export const appConfig: ApplicationConfig = {
|
||||
provideMomentDateAdapter(undefined, {useUtc: false}),
|
||||
{ provide: MAT_SNACK_BAR_DEFAULT_OPTIONS, useValue: { duration: 2500}},
|
||||
AuthGuard,
|
||||
{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true },
|
||||
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
|
||||
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
|
||||
// { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
|
||||
provideNgxMask(),
|
||||
]
|
||||
};
|
||||
|
||||
@@ -8,24 +8,24 @@ import {TournamentDrawComponent} from "./components/tournament-draw/tournament-d
|
||||
import {TournamentManageComponent} from "./components/tournament-manage/tournament-manage.component";
|
||||
import {MatchSheetsComponent} from "./components/match-sheets/match-sheets.component";
|
||||
import {RoundOverviewComponent} from "./components/round-overview/round-overview.component";
|
||||
import {AuthGuard} from "./authentication/authguard";
|
||||
import {LoginComponent} from "./components/login/login.component";
|
||||
import {TournamentPlayersComponent} from "./components/tournament-players/tournament-players.component";
|
||||
import {AuthGuard} from "./auth/auth-guard.service";
|
||||
|
||||
export const routes: Routes = [
|
||||
{ path: '', component: TournamentListComponent, canActivate: [AuthGuard], data: { header: 'Toernooien' }},
|
||||
{ path: 'tournaments', component: TournamentListComponent, canActivate: [AuthGuard], data: { header: 'Toernooien' }},
|
||||
{ path: 'tournaments/add', component: TournamentEditComponent, canActivate: [AuthGuard], data: { header: 'Nieuw Toernooi' }},
|
||||
{ path: 'tournaments/:id/edit', component: TournamentEditComponent, canActivate: [AuthGuard], data: { header: 'Bewerk Toernooi' }},
|
||||
{ path: 'tournaments/:id/registrations', component: TournamentPlayersComponent, canActivate: [AuthGuard], data: { header: 'Inschrijvingen' }},
|
||||
{ path: 'tournaments/:id/draw', component: TournamentDrawComponent, canActivate: [AuthGuard], data: { header: 'Toernooi loten' }},
|
||||
{ path: '', component: TournamentListComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Toernooien' }},
|
||||
{ path: 'tournaments', component: TournamentListComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Toernooien' }},
|
||||
{ path: 'tournaments/add', component: TournamentEditComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Nieuw 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: { role: 'ROLE_USER', header: 'Inschrijvingen' }},
|
||||
{ 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/:tab', component: TournamentManageComponent, canActivate: [AuthGuard], data: { header: 'Toernooien' }},
|
||||
{ path: 'players', component: PlayerListComponent, canActivate: [AuthGuard], data: { header: 'Spelers' }},
|
||||
{ path: 'players/add', component: PlayerEditComponent, canActivate: [AuthGuard], data: { header: 'Nieuwe Speler' }},
|
||||
{ path: 'players/:id/edit', component: PlayerEditComponent, canActivate: [AuthGuard], data: { header: 'Bewerk Speler' }},
|
||||
{ path: 'tournaments/:id/manage/:tab', component: TournamentManageComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Toernooien' }},
|
||||
{ path: 'players', component: PlayerListComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Spelers' }},
|
||||
{ path: 'players/add', component: PlayerEditComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Nieuwe 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: 'tournaments/:id/rounds/:roundId/matchsheets', component: MatchSheetsComponent, canActivate: [AuthGuard]},
|
||||
{ path: 'tournaments/:id/rounds/:roundId/overview', component: RoundOverviewComponent, canActivate: [AuthGuard], data: { header: 'Rondeoverzicht' }},
|
||||
{ path: 'auth/login', component: LoginComponent, data: { header: 'Inloggen'}}
|
||||
{ path: 'tournaments/:id/rounds/:roundId/overview', component: RoundOverviewComponent, canActivate: [AuthGuard], data: { role: 'ROLE_USER', header: 'Rondeoverzicht' }},
|
||||
{ path: 'login', component: LoginComponent, data: { header: 'Inloggen'}}
|
||||
];
|
||||
|
||||
22
src/app/auth/auth-guard.service.ts
Normal file
22
src/app/auth/auth-guard.service.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
35
src/app/auth/auth.interceptor.ts
Normal file
35
src/app/auth/auth.interceptor.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
86
src/app/auth/auth.service.ts
Normal file
86
src/app/auth/auth.service.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,23 @@
|
||||
<mat-card>
|
||||
<mat-card-content>
|
||||
<form class="form-horizontal" [formGroup]="form">
|
||||
<form class="form-horizontal" (ngSubmit)="login()">
|
||||
<div class="row">
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Gebruikersnaam</mat-label>
|
||||
<input matInput placeholder="Gebruikersnaam" formControlName="username" required>
|
||||
<input matInput name="username" placeholder="Gebruikersnaam" required [(ngModel)]="username">
|
||||
</mat-form-field>
|
||||
</div>
|
||||
<div class="row">
|
||||
<mat-form-field appearance="outline">
|
||||
<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>
|
||||
</div>
|
||||
<button class="w-100 mt-2" mat-button mat-flat-button color="primary"
|
||||
(click)="login()" [disabled]="form.invalid">
|
||||
(click)="login()">
|
||||
Inloggen
|
||||
</button>
|
||||
</form>
|
||||
<p>{{message}}</p>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
|
||||
@@ -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 {ActivatedRoute, Router, RouterLink} from '@angular/router';
|
||||
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 {LoginCredentials} from "../../authentication/loginCredentials";
|
||||
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({
|
||||
@@ -23,6 +26,7 @@ import {User} from "../../authentication/user";
|
||||
MatInput,
|
||||
MatLabel,
|
||||
MatCard,
|
||||
FormsModule,
|
||||
],
|
||||
standalone: true,
|
||||
styleUrls: ['./login.component.scss']
|
||||
@@ -32,48 +36,46 @@ export class LoginComponent implements OnInit {
|
||||
private returnUrl: string;
|
||||
private ipAddress: string;
|
||||
|
||||
constructor(
|
||||
private route: ActivatedRoute,
|
||||
private fb: FormBuilder,
|
||||
private authenticationService: AuthenticationService,
|
||||
private router: Router,
|
||||
private userPersistenceService: UserService,
|
||||
) {
|
||||
this.initializeForm();
|
||||
username: string = "";
|
||||
password: string = "";
|
||||
message: string = "";
|
||||
|
||||
constructor(private authService: AuthService,
|
||||
private route: ActivatedRoute,
|
||||
private router: Router,
|
||||
private snackBar: MatSnackBar) {
|
||||
}
|
||||
|
||||
private initializeForm() {
|
||||
this.form = this.fb.group({
|
||||
username: ['', [Validators.required]],
|
||||
password: ['', [Validators.required]],
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
|
||||
}
|
||||
|
||||
login() {
|
||||
if (this.form.invalid) {
|
||||
return;
|
||||
}
|
||||
public login(): void {
|
||||
console.log('Na inloggen door naar' + this.returnUrl);
|
||||
sessionStorage.removeItem("app.token");
|
||||
|
||||
let loginCredentials = new LoginCredentials();
|
||||
loginCredentials = {
|
||||
...loginCredentials,
|
||||
...this.form.value,
|
||||
};
|
||||
this.authService.login(this.username, this.password)
|
||||
.subscribe({
|
||||
next: (token) => {
|
||||
console.log('Login successful');
|
||||
sessionStorage.setItem("app.token", token);
|
||||
|
||||
this.authenticationService
|
||||
.login(loginCredentials)
|
||||
.subscribe(
|
||||
{
|
||||
next: (user: User) => {
|
||||
this.userPersistenceService.setUser(user);
|
||||
this.router.navigate([this.returnUrl]);
|
||||
}
|
||||
const decodedToken = jwtDecode<JwtPayload>(token);
|
||||
// @ts-ignore
|
||||
sessionStorage.setItem("app.roles", decodedToken.scope);
|
||||
|
||||
// this.router.navigateByUrl("/persons");
|
||||
console.log('Let us go to {url}', 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")
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -45,7 +45,6 @@ export class PlayerEditComponent implements OnInit {
|
||||
player: Player;
|
||||
isEditMode: boolean = false;
|
||||
|
||||
|
||||
constructor(
|
||||
private playerService: PlayerService,
|
||||
private route: ActivatedRoute,
|
||||
|
||||
Reference in New Issue
Block a user