Fixed authguard

This commit is contained in:
2025-09-30 22:59:13 +02:00
parent cdf27f1948
commit f2ee2b467d
6 changed files with 49 additions and 39 deletions

View File

@@ -1,4 +1,4 @@
import {ApplicationConfig, provideZoneChangeDetection} from '@angular/core'; import {ApplicationConfig, inject, provideAppInitializer, provideZoneChangeDetection} from '@angular/core';
import {provideRouter} from '@angular/router'; import {provideRouter} from '@angular/router';
import {routes} from './app.routes'; import {routes} from './app.routes';
@@ -10,15 +10,21 @@ import {MAT_SNACK_BAR_DEFAULT_OPTIONS} from "@angular/material/snack-bar";
import {AuthGuard} from "./authentication/authguard"; import {AuthGuard} from "./authentication/authguard";
import {TokenInterceptor} from "./authentication/tokenInterceptor"; import {TokenInterceptor} from "./authentication/tokenInterceptor";
import {ErrorInterceptor} from "./authentication/errorInterceptor"; import {ErrorInterceptor} from "./authentication/errorInterceptor";
import {provideEnvironmentNgxMask, provideNgxMask} from "ngx-mask"; import {provideNgxMask} from "ngx-mask";
import {UserService} from './authentication/user.service';
import {provideAnimations} from "@angular/platform-browser/animations";
export const appConfig: ApplicationConfig = { export const appConfig: ApplicationConfig = {
providers: [ providers: [
provideAppInitializer(() => {
const userService = inject(UserService);
userService.initializeUser();
}),
provideZoneChangeDetection({eventCoalescing: true}), provideZoneChangeDetection({eventCoalescing: true}),
provideRouter(routes), provideRouter(routes),
provideClientHydration(), provideClientHydration(),
provideHttpClient(withFetch(), withInterceptorsFromDi()), provideHttpClient(withFetch(), withInterceptorsFromDi()),
provideAnimationsAsync(), provideAnimations(),
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,
@@ -27,3 +33,4 @@ export const appConfig: ApplicationConfig = {
provideNgxMask(), provideNgxMask(),
] ]
}; };

View File

@@ -1,6 +1,7 @@
import {Injectable} from "@angular/core"; import {Injectable} from "@angular/core";
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from "@angular/router"; import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from "@angular/router";
import {UserService} from "./user.service"; import {UserService} from "./user.service";
import {delay, map, Observable, of} from "rxjs";
@Injectable() @Injectable()
export class AuthGuard implements CanActivate { export class AuthGuard implements CanActivate {
@@ -10,14 +11,12 @@ export class AuthGuard implements CanActivate {
private userService: UserService private userService: UserService
) {} ) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.userService.getUser()) { if (this.userService.getUser()) {
return true; return true;
} }
this.router.navigate(['/auth/login'], { queryParams: { returnUrl: state.url } });
this.router.navigate(['/auth/login'], {
queryParams: { returnUrl: state.url },
});
return false; return false;
} }
} }

View File

@@ -1,16 +1,17 @@
import {EventEmitter, Injectable, Output} from "@angular/core"; import { Injectable } from "@angular/core";
import {SsrCookieService} from "ngx-cookie-service-ssr"; import { SsrCookieService } from "ngx-cookie-service-ssr";
import {Router} from "@angular/router"; import { Router } from "@angular/router";
import {User} from "./user"; import { User } from "./user";
import {BehaviorSubject} from "rxjs"; import { BehaviorSubject } from "rxjs";
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class UserService { export class UserService {
user?: User; private user?: User;
private userEmitter = new BehaviorSubject<string>('');
private initialized = false;
private userEmitter = new BehaviorSubject('');
currentUser = this.userEmitter.asObservable(); currentUser = this.userEmitter.asObservable();
constructor( constructor(
@@ -18,30 +19,44 @@ export class UserService {
private router: Router, private router: Router,
) {} ) {}
public getUser(): User | undefined { initializeUser() {
const user = this.cookieService.get('swissuser'); if (this.initialized) return;
if (user) { try {
this.user = JSON.parse(user); const userCookie = this.cookieService.get('swissuser');
this.userEmitter.next(JSON.parse(user).username); if (userCookie && userCookie.trim() !== '') {
this.user = JSON.parse(userCookie);
if (this.user?.username) {
this.userEmitter.next(this.user.username);
} else {
this.userEmitter.next('');
}
} else { } else {
this.user = undefined; this.user = undefined;
this.userEmitter.next('');
}
} catch (error) {
console.error('Error parsing user cookie:', error);
this.user = undefined;
this.userEmitter.next('');
} }
this.initialized = true;
}
public getUser(): User | undefined {
this.initializeUser();
return this.user; return this.user;
} }
public isLoggedIn(): boolean { public isLoggedIn(): boolean {
const user = this.cookieService.get('swissuser'); this.initializeUser();
return !!this.user;
return !(user == undefined || false || user == "");
} }
public setUser(user: User) { public setUser(user: User) {
this.cookieService.set('swissuser', JSON.stringify(user)); this.cookieService.set('swissuser', JSON.stringify(user));
this.user = user; this.user = user;
this.userEmitter.next(this.user.username); this.userEmitter.next(this.user.username);
} }

View File

@@ -124,7 +124,7 @@
</ng-template> </ng-template>
@if (this.activeMatches().length > 0) { @if (this.activeMatches().length > 0) {
<h6 class="mt-3">Actieve wedstrijden</h6> <h6 class="mt-3"></h6>
@for (activeMatch of this.activeMatches(); track activeMatch.match.id) { @for (activeMatch of this.activeMatches(); track activeMatch.match.id) {
<mat-expansion-panel> <mat-expansion-panel>

View File

@@ -34,25 +34,15 @@ import {MatTab, MatTabGroup, MatTabLabel} from "@angular/material/tabs";
standalone: true, standalone: true,
styleUrl: './tournament-players.component.scss' styleUrl: './tournament-players.component.scss'
}) })
export class TournamentPlayersComponent implements OnInit { export class TournamentPlayersComponent {
@Input() tournament: Tournament; @Input() tournament: Tournament;
constructor( constructor(
private tournamentService: TournamentService, private tournamentService: TournamentService,
private _snackBar: MatSnackBar, private _snackBar: MatSnackBar,
private route: ActivatedRoute,
private router: Router,
) {} ) {}
ngOnInit() {
console.log('Tournament received from parent:', this.tournament);
// const id = this.route.snapshot.paramMap.get('id');
// this.tournamentService.getById(Number(id)).subscribe(data => {
// this.tournament = data;
// });
}
playerPaid($event: MatSlideToggleChange, playerId: number) { playerPaid($event: MatSlideToggleChange, playerId: number) {
this.tournamentService.playerPaid(this.tournament.id, playerId, $event.checked).subscribe(() => { this.tournamentService.playerPaid(this.tournament.id, playerId, $event.checked).subscribe(() => {
this._snackBar.open('Opgeslagen.'); this._snackBar.open('Opgeslagen.');

View File

@@ -1,4 +1,3 @@
// header.service.ts
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs'; import { BehaviorSubject } from 'rxjs';