feat: implement authentication with JWT and user management
This commit is contained in:
parent
c4c762cafe
commit
35d8fbaea0
42 changed files with 989 additions and 397 deletions
|
@ -8,8 +8,12 @@ export const routes: Routes = [
|
|||
component: LandingComponent,
|
||||
},
|
||||
{
|
||||
path: 'auth/callback',
|
||||
loadComponent: () => import('./feature/login-success/login-success.component'),
|
||||
path: 'login',
|
||||
loadComponent: () => import('./feature/auth/login/login.component').then(m => m.LoginComponent),
|
||||
},
|
||||
{
|
||||
path: 'register',
|
||||
loadComponent: () => import('./feature/auth/register/register.component').then(m => m.RegisterComponent),
|
||||
},
|
||||
{
|
||||
path: 'home',
|
||||
|
@ -24,7 +28,6 @@ export const routes: Routes = [
|
|||
{
|
||||
path: 'game/slots',
|
||||
loadComponent: () => import('./feature/game/slots/slots.component'),
|
||||
canActivate: [authGuard],
|
||||
},
|
||||
{
|
||||
path: 'game/lootboxes',
|
||||
|
|
113
frontend/src/app/feature/auth/login/login.component.ts
Normal file
113
frontend/src/app/feature/auth/login/login.component.ts
Normal file
|
@ -0,0 +1,113 @@
|
|||
import { Component } from '@angular/core';
|
||||
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||
import { Router, RouterLink } from '@angular/router';
|
||||
import { LoginRequest } from '../../../model/auth/LoginRequest';
|
||||
import { AuthService } from '../../../service/auth.service';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
@Component({
|
||||
selector: 'app-login',
|
||||
standalone: true,
|
||||
imports: [CommonModule, ReactiveFormsModule, RouterLink],
|
||||
template: `
|
||||
<div class="min-h-screen bg-gray-900 flex items-center justify-center">
|
||||
<div class="max-w-md w-full bg-gray-800 rounded-lg shadow-lg p-8">
|
||||
<h2 class="text-2xl font-bold text-white mb-6 text-center">Login to Casino</h2>
|
||||
|
||||
<div *ngIf="errorMessage" class="bg-red-600 text-white p-4 rounded mb-4">
|
||||
{{ errorMessage }}
|
||||
</div>
|
||||
|
||||
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()" class="space-y-6">
|
||||
<div>
|
||||
<label for="usernameOrEmail" class="block text-sm font-medium text-gray-300">Username or Email</label>
|
||||
<input
|
||||
id="usernameOrEmail"
|
||||
type="text"
|
||||
formControlName="usernameOrEmail"
|
||||
class="mt-1 block w-full bg-gray-700 border-gray-600 text-white rounded-md shadow-sm py-2 px-3"
|
||||
placeholder="Enter your username or email">
|
||||
|
||||
<div *ngIf="form['usernameOrEmail'].touched && form['usernameOrEmail'].errors" class="text-red-500 mt-1 text-sm">
|
||||
<span *ngIf="form['usernameOrEmail'].errors?.['required']">Username or email is required</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label for="password" class="block text-sm font-medium text-gray-300">Password</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
formControlName="password"
|
||||
class="mt-1 block w-full bg-gray-700 border-gray-600 text-white rounded-md shadow-sm py-2 px-3"
|
||||
placeholder="Enter your password">
|
||||
|
||||
<div *ngIf="form['password'].touched && form['password'].errors" class="text-red-500 mt-1 text-sm">
|
||||
<span *ngIf="form['password'].errors?.['required']">Password is required</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<button
|
||||
type="submit"
|
||||
[disabled]="loginForm.invalid || isLoading"
|
||||
class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
|
||||
{{ isLoading ? 'Logging in...' : 'Login' }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="mt-6 text-center">
|
||||
<p class="text-sm text-gray-400">
|
||||
Don't have an account?
|
||||
<a routerLink="/register" class="font-medium text-indigo-400 hover:text-indigo-300">Register</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
})
|
||||
export class LoginComponent {
|
||||
loginForm: FormGroup;
|
||||
errorMessage = '';
|
||||
isLoading = false;
|
||||
|
||||
constructor(
|
||||
private fb: FormBuilder,
|
||||
private authService: AuthService,
|
||||
private router: Router
|
||||
) {
|
||||
this.loginForm = this.fb.group({
|
||||
usernameOrEmail: ['', [Validators.required]],
|
||||
password: ['', [Validators.required]]
|
||||
});
|
||||
}
|
||||
|
||||
get form() {
|
||||
return this.loginForm.controls;
|
||||
}
|
||||
|
||||
onSubmit(): void {
|
||||
if (this.loginForm.invalid) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isLoading = true;
|
||||
this.errorMessage = '';
|
||||
|
||||
const loginRequest: LoginRequest = {
|
||||
usernameOrEmail: this.form['usernameOrEmail'].value,
|
||||
password: this.form['password'].value
|
||||
};
|
||||
|
||||
this.authService.login(loginRequest).subscribe({
|
||||
next: () => {
|
||||
this.router.navigate(['/home']);
|
||||
},
|
||||
error: err => {
|
||||
this.isLoading = false;
|
||||
this.errorMessage = err.error?.message || 'Failed to login. Please check your credentials.';
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
144
frontend/src/app/feature/auth/register/register.component.ts
Normal file
144
frontend/src/app/feature/auth/register/register.component.ts
Normal file
|
@ -0,0 +1,144 @@
|
|||
import { Component } from '@angular/core';
|
||||
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||
import { Router, RouterLink } from '@angular/router';
|
||||
import { RegisterRequest } from '../../../model/auth/RegisterRequest';
|
||||
import { AuthService } from '../../../service/auth.service';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
@Component({
|
||||
selector: 'app-register',
|
||||
standalone: true,
|
||||
imports: [CommonModule, ReactiveFormsModule, RouterLink],
|
||||
template: `
|
||||
<div class="min-h-screen bg-gray-900 flex items-center justify-center">
|
||||
<div class="max-w-md w-full bg-gray-800 rounded-lg shadow-lg p-8">
|
||||
<h2 class="text-2xl font-bold text-white mb-6 text-center">Create Account</h2>
|
||||
|
||||
<div *ngIf="errorMessage" class="bg-red-600 text-white p-4 rounded mb-4">
|
||||
{{ errorMessage }}
|
||||
</div>
|
||||
|
||||
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()" class="space-y-6">
|
||||
<div>
|
||||
<label for="email" class="block text-sm font-medium text-gray-300">Email</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
formControlName="email"
|
||||
class="mt-1 block w-full bg-gray-700 border-gray-600 text-white rounded-md shadow-sm py-2 px-3"
|
||||
placeholder="Enter your email">
|
||||
|
||||
<div *ngIf="form['email'].touched && form['email'].errors" class="text-red-500 mt-1 text-sm">
|
||||
<span *ngIf="form['email'].errors?.['required']">Email is required</span>
|
||||
<span *ngIf="form['email'].errors?.['email']">Please enter a valid email address</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label for="username" class="block text-sm font-medium text-gray-300">Username</label>
|
||||
<input
|
||||
id="username"
|
||||
type="text"
|
||||
formControlName="username"
|
||||
class="mt-1 block w-full bg-gray-700 border-gray-600 text-white rounded-md shadow-sm py-2 px-3"
|
||||
placeholder="Choose a username">
|
||||
|
||||
<div *ngIf="form['username'].touched && form['username'].errors" class="text-red-500 mt-1 text-sm">
|
||||
<span *ngIf="form['username'].errors?.['required']">Username is required</span>
|
||||
<span *ngIf="form['username'].errors?.['minlength']">Username must be at least 3 characters</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label for="password" class="block text-sm font-medium text-gray-300">Password</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
formControlName="password"
|
||||
class="mt-1 block w-full bg-gray-700 border-gray-600 text-white rounded-md shadow-sm py-2 px-3"
|
||||
placeholder="Create a password">
|
||||
|
||||
<div *ngIf="form['password'].touched && form['password'].errors" class="text-red-500 mt-1 text-sm">
|
||||
<span *ngIf="form['password'].errors?.['required']">Password is required</span>
|
||||
<span *ngIf="form['password'].errors?.['minlength']">Password must be at least 6 characters</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<button
|
||||
type="submit"
|
||||
[disabled]="registerForm.invalid || isLoading"
|
||||
class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
|
||||
{{ isLoading ? 'Creating account...' : 'Register' }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="mt-6 text-center">
|
||||
<p class="text-sm text-gray-400">
|
||||
Already have an account?
|
||||
<a routerLink="/login" class="font-medium text-indigo-400 hover:text-indigo-300">Login</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
})
|
||||
export class RegisterComponent {
|
||||
registerForm: FormGroup;
|
||||
errorMessage = '';
|
||||
isLoading = false;
|
||||
|
||||
constructor(
|
||||
private fb: FormBuilder,
|
||||
private authService: AuthService,
|
||||
private router: Router
|
||||
) {
|
||||
this.registerForm = this.fb.group({
|
||||
email: ['', [Validators.required, Validators.email]],
|
||||
username: ['', [Validators.required, Validators.minLength(3)]],
|
||||
password: ['', [Validators.required, Validators.minLength(6)]]
|
||||
});
|
||||
}
|
||||
|
||||
get form() {
|
||||
return this.registerForm.controls;
|
||||
}
|
||||
|
||||
onSubmit(): void {
|
||||
if (this.registerForm.invalid) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isLoading = true;
|
||||
this.errorMessage = '';
|
||||
|
||||
const registerRequest: RegisterRequest = {
|
||||
email: this.form['email'].value,
|
||||
username: this.form['username'].value,
|
||||
password: this.form['password'].value
|
||||
};
|
||||
|
||||
this.authService.register(registerRequest).subscribe({
|
||||
next: () => {
|
||||
// After registration, log in the user
|
||||
this.authService.login({
|
||||
usernameOrEmail: registerRequest.email,
|
||||
password: registerRequest.password
|
||||
}).subscribe({
|
||||
next: () => {
|
||||
this.router.navigate(['/home']);
|
||||
},
|
||||
error: err => {
|
||||
this.isLoading = false;
|
||||
this.errorMessage = 'Registration successful but failed to login automatically. Please log in manually.';
|
||||
}
|
||||
});
|
||||
},
|
||||
error: err => {
|
||||
this.isLoading = false;
|
||||
this.errorMessage = err.error?.message || 'Failed to register. Please try again.';
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
|
@ -51,7 +51,7 @@ export default class BlackjackComponent implements OnInit {
|
|||
debtAmount = signal(0);
|
||||
|
||||
ngOnInit(): void {
|
||||
this.userService.currentUser$.subscribe((user) => {
|
||||
this.userService.getCurrentUser().subscribe((user) => {
|
||||
if (user) {
|
||||
this.balance.set(user.balance);
|
||||
}
|
||||
|
@ -83,7 +83,7 @@ export default class BlackjackComponent implements OnInit {
|
|||
|
||||
if (isGameOver) {
|
||||
console.log('Game is over, state:', game.state);
|
||||
this.userService.refreshCurrentUser();
|
||||
// this.userService.refreshCurrentUser();
|
||||
timer(1500).subscribe(() => {
|
||||
this.showGameResult.set(true);
|
||||
console.log('Game result dialog shown after delay');
|
||||
|
@ -97,7 +97,7 @@ export default class BlackjackComponent implements OnInit {
|
|||
this.blackjackService.startGame(bet).subscribe({
|
||||
next: (game) => {
|
||||
this.updateGameState(game);
|
||||
this.userService.refreshCurrentUser();
|
||||
// this.userService.refreshCurrentUser();
|
||||
this.isActionInProgress.set(false);
|
||||
},
|
||||
error: (error) => {
|
||||
|
@ -116,7 +116,7 @@ export default class BlackjackComponent implements OnInit {
|
|||
next: (game) => {
|
||||
this.updateGameState(game);
|
||||
if (game.state !== 'IN_PROGRESS') {
|
||||
this.userService.refreshCurrentUser();
|
||||
// this.userService.refreshCurrentUser();
|
||||
}
|
||||
this.isActionInProgress.set(false);
|
||||
},
|
||||
|
@ -141,7 +141,7 @@ export default class BlackjackComponent implements OnInit {
|
|||
this.blackjackService.stand(this.currentGameId()!).subscribe({
|
||||
next: (game) => {
|
||||
this.updateGameState(game);
|
||||
this.userService.refreshCurrentUser();
|
||||
// this.userService.refreshCurrentUser();
|
||||
this.isActionInProgress.set(false);
|
||||
},
|
||||
error: (error) => {
|
||||
|
@ -184,7 +184,7 @@ export default class BlackjackComponent implements OnInit {
|
|||
onCloseGameResult(): void {
|
||||
console.log('Closing game result dialog');
|
||||
this.showGameResult.set(false);
|
||||
this.userService.refreshCurrentUser();
|
||||
// this.userService.refreshCurrentUser();
|
||||
}
|
||||
|
||||
onCloseDebtDialog(): void {
|
||||
|
@ -195,11 +195,11 @@ export default class BlackjackComponent implements OnInit {
|
|||
if (error instanceof HttpErrorResponse) {
|
||||
if (error.status === 400 && error.error?.error === 'Invalid state') {
|
||||
this.gameInProgress.set(false);
|
||||
this.userService.refreshCurrentUser();
|
||||
// this.userService.refreshCurrentUser();
|
||||
} else if (error.status === 500) {
|
||||
console.log('Server error occurred. The game may have been updated in another session.');
|
||||
this.gameInProgress.set(false);
|
||||
this.userService.refreshCurrentUser();
|
||||
// this.userService.refreshCurrentUser();
|
||||
if (this.currentGameId()) {
|
||||
this.refreshGameState(this.currentGameId()!);
|
||||
}
|
||||
|
|
|
@ -10,9 +10,14 @@
|
|||
<div class="welcome-bonus">200% bis zu 500€</div>
|
||||
<p class="bonus-description">+ 200 Freispiele</p>
|
||||
|
||||
<button class="w-full sm:w-auto button-primary px-6 sm:px-8 py-3 shadow-lg">
|
||||
Bonus Sichern
|
||||
</button>
|
||||
<div class="flex justify-center space-x-4 mt-6">
|
||||
<a routerLink="/register" class="w-full sm:w-auto button-primary px-6 sm:px-8 py-3 shadow-lg">
|
||||
Konto erstellen
|
||||
</a>
|
||||
<a routerLink="/login" class="w-full sm:w-auto bg-slate-700 text-white hover:bg-slate-600 px-6 sm:px-8 py-3 shadow-lg rounded">
|
||||
Anmelden
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="relative mb-16">
|
||||
|
|
|
@ -1,11 +1,12 @@
|
|||
import { ChangeDetectionStrategy, Component, OnDestroy, OnInit } from '@angular/core';
|
||||
import { NgFor } from '@angular/common';
|
||||
import { NavbarComponent } from '@shared/components/navbar/navbar.component';
|
||||
import { RouterLink } from '@angular/router';
|
||||
|
||||
@Component({
|
||||
selector: 'app-landing-page',
|
||||
standalone: true,
|
||||
imports: [NavbarComponent, NgFor],
|
||||
imports: [NavbarComponent, NgFor, RouterLink],
|
||||
templateUrl: './landing.component.html',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
export interface User {
|
||||
authentikId: string;
|
||||
id: number;
|
||||
email: string;
|
||||
username: string;
|
||||
balance: number;
|
||||
}
|
||||
|
|
4
frontend/src/app/model/auth/AuthResponse.ts
Normal file
4
frontend/src/app/model/auth/AuthResponse.ts
Normal file
|
@ -0,0 +1,4 @@
|
|||
export interface AuthResponse {
|
||||
token: string;
|
||||
tokenType: string;
|
||||
}
|
4
frontend/src/app/model/auth/LoginRequest.ts
Normal file
4
frontend/src/app/model/auth/LoginRequest.ts
Normal file
|
@ -0,0 +1,4 @@
|
|||
export interface LoginRequest {
|
||||
usernameOrEmail: string;
|
||||
password: string;
|
||||
}
|
5
frontend/src/app/model/auth/RegisterRequest.ts
Normal file
5
frontend/src/app/model/auth/RegisterRequest.ts
Normal file
|
@ -0,0 +1,5 @@
|
|||
export interface RegisterRequest {
|
||||
email: string;
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
|
@ -1,208 +1,96 @@
|
|||
import { inject, Injectable } from '@angular/core';
|
||||
import { AuthConfig, OAuthEvent, OAuthService } from 'angular-oauth2-oidc';
|
||||
import { UserService } from './user.service';
|
||||
import { User } from '../model/User';
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { BehaviorSubject, Observable, tap } from 'rxjs';
|
||||
import { Router } from '@angular/router';
|
||||
import { LoginRequest } from '../model/auth/LoginRequest';
|
||||
import { RegisterRequest } from '../model/auth/RegisterRequest';
|
||||
import { AuthResponse } from '../model/auth/AuthResponse';
|
||||
import { User } from '../model/User';
|
||||
import { environment } from '../../environments/environment';
|
||||
import { catchError, from, of } from 'rxjs';
|
||||
|
||||
const TOKEN_KEY = 'auth-token';
|
||||
const USER_KEY = 'auth-user';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class AuthService {
|
||||
private readonly authConfig: AuthConfig = {
|
||||
issuer: 'https://oauth.simonis.lol/application/o/casino-dev/',
|
||||
clientId: environment.OAUTH_CLIENT_ID,
|
||||
dummyClientSecret: environment.OAUTH_CLIENT_SECRET,
|
||||
scope: `openid email profile ${environment.OAUTH_CLIENT_ID}`,
|
||||
responseType: 'code',
|
||||
redirectUri: window.location.origin + '/auth/callback',
|
||||
postLogoutRedirectUri: '',
|
||||
redirectUriAsPostLogoutRedirectUriFallback: false,
|
||||
oidc: true,
|
||||
requestAccessToken: true,
|
||||
tokenEndpoint: 'https://oauth.simonis.lol/application/o/token/',
|
||||
userinfoEndpoint: 'https://oauth.simonis.lol/application/o/userinfo/',
|
||||
strictDiscoveryDocumentValidation: false,
|
||||
skipIssuerCheck: true,
|
||||
disableAtHashCheck: true,
|
||||
requireHttps: false,
|
||||
showDebugInformation: false,
|
||||
sessionChecksEnabled: false,
|
||||
};
|
||||
|
||||
private userService: UserService = inject(UserService);
|
||||
private oauthService: OAuthService = inject(OAuthService);
|
||||
private router: Router = inject(Router);
|
||||
|
||||
private user: User | null = null;
|
||||
|
||||
constructor() {
|
||||
this.oauthService.configure(this.authConfig);
|
||||
this.setupEventHandling();
|
||||
|
||||
const hasAuthParams =
|
||||
window.location.search.includes('code=') ||
|
||||
window.location.search.includes('token=') ||
|
||||
window.location.search.includes('id_token=');
|
||||
|
||||
if (hasAuthParams) {
|
||||
this.processCodeFlow();
|
||||
} else {
|
||||
this.checkExistingSession();
|
||||
private authUrl = `${environment.apiUrl}/api/auth`;
|
||||
private userUrl = `${environment.apiUrl}/api/users`;
|
||||
|
||||
private currentUserSubject: BehaviorSubject<User | null>;
|
||||
public currentUser: Observable<User | null>;
|
||||
|
||||
constructor(private http: HttpClient, private router: Router) {
|
||||
this.currentUserSubject = new BehaviorSubject<User | null>(this.getUserFromStorage());
|
||||
this.currentUser = this.currentUserSubject.asObservable();
|
||||
|
||||
// Check if token exists and load user data
|
||||
if (this.getToken()) {
|
||||
this.loadCurrentUser();
|
||||
}
|
||||
}
|
||||
|
||||
private processCodeFlow() {
|
||||
this.oauthService
|
||||
.tryLogin({
|
||||
onTokenReceived: () => {
|
||||
this.handleSuccessfulLogin();
|
||||
},
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('Error processing code flow:', err);
|
||||
});
|
||||
|
||||
public get currentUserValue(): User | null {
|
||||
return this.currentUserSubject.value;
|
||||
}
|
||||
|
||||
private checkExistingSession() {
|
||||
this.oauthService
|
||||
.loadDiscoveryDocumentAndTryLogin()
|
||||
.then((isLoggedIn) => {
|
||||
if (isLoggedIn && !this.user) {
|
||||
this.handleSuccessfulLogin();
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('Error during initial login attempt:', err);
|
||||
});
|
||||
}
|
||||
|
||||
private setupEventHandling() {
|
||||
this.oauthService.events.subscribe((event: OAuthEvent) => {
|
||||
if (event.type === 'token_received') {
|
||||
this.handleSuccessfulLogin();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private handleSuccessfulLogin() {
|
||||
const claims = this.oauthService.getIdentityClaims();
|
||||
|
||||
if (claims && (claims['sub'] || claims['email'])) {
|
||||
this.processUserProfile(claims);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
from(this.oauthService.loadUserProfile())
|
||||
.pipe(
|
||||
catchError((error) => {
|
||||
console.error('Error loading user profile:', error);
|
||||
if (this.oauthService.hasValidAccessToken()) {
|
||||
this.oauthService.getAccessToken();
|
||||
const minimalProfile = {
|
||||
sub: 'user-' + Math.random().toString(36).substring(2, 10),
|
||||
preferred_username: 'user' + Date.now(),
|
||||
};
|
||||
return of({ info: minimalProfile });
|
||||
}
|
||||
return of(null);
|
||||
})
|
||||
)
|
||||
.subscribe((profile) => {
|
||||
if (profile) {
|
||||
this.processUserProfile(profile);
|
||||
} else {
|
||||
this.router.navigate(['/']);
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Exception in handleSuccessfulLogin:', err);
|
||||
if (this.oauthService.hasValidAccessToken()) {
|
||||
this.router.navigate(['/home']);
|
||||
} else {
|
||||
this.router.navigate(['/']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private processUserProfile(profile: unknown) {
|
||||
this.fromUserProfile(profile as Record<string, unknown>).subscribe({
|
||||
next: (user) => {
|
||||
this.user = user;
|
||||
this.router.navigate(['home']);
|
||||
},
|
||||
error: (err) => {
|
||||
console.error('Error creating/retrieving user:', err);
|
||||
if (this.oauthService.hasValidAccessToken()) {
|
||||
this.router.navigate(['/home']);
|
||||
} else {
|
||||
this.router.navigate(['/']);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
login() {
|
||||
try {
|
||||
this.oauthService
|
||||
.loadDiscoveryDocument()
|
||||
.then(() => {
|
||||
this.oauthService.initLoginFlow();
|
||||
|
||||
login(loginRequest: LoginRequest): Observable<AuthResponse> {
|
||||
return this.http.post<AuthResponse>(`${this.authUrl}/login`, loginRequest)
|
||||
.pipe(
|
||||
tap(response => {
|
||||
this.setToken(response.token);
|
||||
this.loadCurrentUser();
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('Error loading discovery document:', err);
|
||||
this.oauthService.initLoginFlow();
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Exception in login:', err);
|
||||
const redirectUri = this.authConfig.redirectUri || window.location.origin + '/auth/callback';
|
||||
const scope = this.authConfig.scope || 'openid email profile';
|
||||
const authUrl = `${this.authConfig.issuer}authorize?client_id=${this.authConfig.clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${encodeURIComponent(scope)}`;
|
||||
window.location.href = authUrl;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
logout() {
|
||||
try {
|
||||
this.user = null;
|
||||
|
||||
this.oauthService.logOut(true);
|
||||
|
||||
if (window.location.href.includes('id_token') || window.location.href.includes('logout')) {
|
||||
window.location.href = window.location.origin;
|
||||
}
|
||||
|
||||
localStorage.removeItem('access_token');
|
||||
localStorage.removeItem('id_token');
|
||||
localStorage.removeItem('refresh_token');
|
||||
sessionStorage.removeItem('access_token');
|
||||
sessionStorage.removeItem('id_token');
|
||||
sessionStorage.removeItem('refresh_token');
|
||||
|
||||
this.router.navigate(['/']);
|
||||
} catch (err) {
|
||||
console.error('Exception in logout:', err);
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
this.router.navigate(['/']);
|
||||
}
|
||||
|
||||
register(registerRequest: RegisterRequest): Observable<User> {
|
||||
return this.http.post<User>(`${this.authUrl}/register`, registerRequest);
|
||||
}
|
||||
|
||||
isLoggedIn() {
|
||||
return this.oauthService.hasValidAccessToken();
|
||||
|
||||
logout(): void {
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
localStorage.removeItem(USER_KEY);
|
||||
this.currentUserSubject.next(null);
|
||||
this.router.navigate(['/']);
|
||||
}
|
||||
|
||||
private fromUserProfile(profile: Record<string, unknown>) {
|
||||
return this.userService.getOrCreateUser(profile);
|
||||
|
||||
isLoggedIn(): boolean {
|
||||
return !!this.getToken();
|
||||
}
|
||||
|
||||
getAccessToken() {
|
||||
return this.oauthService.getAccessToken();
|
||||
|
||||
getToken(): string | null {
|
||||
return localStorage.getItem(TOKEN_KEY);
|
||||
}
|
||||
|
||||
getUser() {
|
||||
return this.user;
|
||||
|
||||
private setToken(token: string): void {
|
||||
localStorage.setItem(TOKEN_KEY, token);
|
||||
}
|
||||
|
||||
private setUser(user: User): void {
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(user));
|
||||
this.currentUserSubject.next(user);
|
||||
}
|
||||
|
||||
private getUserFromStorage(): User | null {
|
||||
const user = localStorage.getItem(USER_KEY);
|
||||
return user ? JSON.parse(user) : null;
|
||||
}
|
||||
|
||||
private loadCurrentUser(): void {
|
||||
this.http.get<User>(`${this.userUrl}/me`)
|
||||
.subscribe({
|
||||
next: (user) => {
|
||||
this.setUser(user);
|
||||
},
|
||||
error: () => {
|
||||
this.logout();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
getUser(): User | null {
|
||||
return this.currentUserValue;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,25 +1,24 @@
|
|||
import { inject, Injectable } from '@angular/core';
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { BehaviorSubject, catchError, EMPTY, Observable, tap } from 'rxjs';
|
||||
import { User } from '../model/User';
|
||||
import { environment } from '@environments/environment';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class UserService {
|
||||
private http: HttpClient = inject(HttpClient);
|
||||
private apiUrl = `${environment.apiUrl}/api/users`;
|
||||
private currentUserSubject = new BehaviorSubject<User | null>(null);
|
||||
public currentUser$ = this.currentUserSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
this.getCurrentUser().subscribe();
|
||||
constructor(private http: HttpClient) {}
|
||||
|
||||
public getUserById(id: number): Observable<User> {
|
||||
return this.http.get<User>(`${this.apiUrl}/${id}`);
|
||||
}
|
||||
|
||||
public getUser(id: string): Observable<User | null> {
|
||||
return this.http.get<User | null>(`/backend/user/${id}`).pipe(
|
||||
catchError(() => EMPTY),
|
||||
tap((user) => this.currentUserSubject.next(user))
|
||||
);
|
||||
public getUserByUsername(username: string): Observable<User> {
|
||||
return this.http.get<User>(`${this.apiUrl}/username/${username}`);
|
||||
}
|
||||
|
||||
public getCurrentUser(): Observable<User | null> {
|
||||
|
@ -52,20 +51,4 @@ export class UserService {
|
|||
})
|
||||
.pipe(tap((user) => this.currentUserSubject.next(user)));
|
||||
}
|
||||
|
||||
public getOrCreateUser(profile: Record<string, unknown>): Observable<User> {
|
||||
const info = profile['info'] as Record<string, unknown> | undefined;
|
||||
const id = (info?.['sub'] as string) || (profile['sub'] as string);
|
||||
const username =
|
||||
(info?.['preferred_username'] as string) ||
|
||||
(profile['preferred_username'] as string) ||
|
||||
(profile['email'] as string) ||
|
||||
(profile['name'] as string);
|
||||
|
||||
if (!id || !username) {
|
||||
throw new Error('Invalid user profile data');
|
||||
}
|
||||
|
||||
return this.createUser(id, username);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -12,7 +12,8 @@
|
|||
|
||||
<div class="hidden md:flex items-center space-x-4">
|
||||
@if (!isLoggedIn) {
|
||||
<button (click)="login()" class="button-primary px-4 py-1.5">Anmelden</button>
|
||||
<a routerLink="/login" class="button-primary px-4 py-1.5">Anmelden</a>
|
||||
<a routerLink="/register" class="bg-emerald-700 text-white hover:bg-emerald-600 px-4 py-1.5 rounded">Registrieren</a>
|
||||
}
|
||||
@if (isLoggedIn) {
|
||||
<div
|
||||
|
@ -66,7 +67,8 @@
|
|||
<a routerLink="/games" class="nav-mobile-link">Spiele</a>
|
||||
<div class="pt-2 space-y-2">
|
||||
@if (!isLoggedIn) {
|
||||
<button (click)="login()" class="button-primary w-full py-1.5">Anmelden</button>
|
||||
<a routerLink="/login" class="button-primary w-full py-1.5 block text-center">Anmelden</a>
|
||||
<a routerLink="/register" class="bg-emerald-700 text-white hover:bg-emerald-600 w-full py-1.5 rounded block text-center">Registrieren</a>
|
||||
}
|
||||
@if (isLoggedIn) {
|
||||
<button (click)="logout()" class="button-primary w-full py-1.5">Abmelden</button>
|
||||
|
|
|
@ -26,10 +26,13 @@ export class NavbarComponent implements OnInit, OnDestroy {
|
|||
|
||||
private userService = inject(UserService);
|
||||
private userSubscription: Subscription | undefined;
|
||||
private authSubscription: Subscription | undefined;
|
||||
public balance = signal(0);
|
||||
|
||||
ngOnInit() {
|
||||
this.userSubscription = this.userService.currentUser$.subscribe((user) => {
|
||||
// Subscribe to auth changes
|
||||
this.authSubscription = this.authService.currentUser.subscribe(user => {
|
||||
this.isLoggedIn = !!user;
|
||||
this.balance.set(user?.balance ?? 0);
|
||||
console.log('Updated navbar balance:', user?.balance);
|
||||
});
|
||||
|
@ -41,13 +44,8 @@ export class NavbarComponent implements OnInit, OnDestroy {
|
|||
if (this.userSubscription) {
|
||||
this.userSubscription.unsubscribe();
|
||||
}
|
||||
}
|
||||
|
||||
login() {
|
||||
try {
|
||||
this.authService.login();
|
||||
} catch (error) {
|
||||
console.error('Login failed:', error);
|
||||
if (this.authSubscription) {
|
||||
this.authSubscription.unsubscribe();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,21 +1,33 @@
|
|||
import { HttpInterceptorFn } from '@angular/common/http';
|
||||
import { inject } from '@angular/core';
|
||||
import { OAuthStorage } from 'angular-oauth2-oidc';
|
||||
import { AuthService } from '../../service/auth.service';
|
||||
|
||||
export const httpInterceptor: HttpInterceptorFn = (req, next) => {
|
||||
const oauthStorage = inject(OAuthStorage);
|
||||
const authService = inject(AuthService);
|
||||
const token = authService.getToken();
|
||||
|
||||
if (oauthStorage.getItem('access_token')) {
|
||||
// Always add CORS headers
|
||||
if (token) {
|
||||
return next(
|
||||
req.clone({
|
||||
setHeaders: {
|
||||
Authorization: 'Bearer ' + oauthStorage.getItem('access_token'),
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Referrer-Policy': 'no-referrer',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
|
||||
'Access-Control-Allow-Headers': '*'
|
||||
},
|
||||
})
|
||||
);
|
||||
} else {
|
||||
return next(req);
|
||||
return next(
|
||||
req.clone({
|
||||
setHeaders: {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
|
||||
'Access-Control-Allow-Headers': '*'
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
};
|
||||
|
|
|
@ -1,7 +1,5 @@
|
|||
export const environment = {
|
||||
STRIPE_KEY:
|
||||
'pk_test_51QrePYIvCfqz7ANgMizBorPpVjJ8S6gcaL4yvcMQnVaKyReqcQ6jqaQEF7aDZbDu8rNVsTZrw8ABek4ToxQX7KZe00jpGh8naG',
|
||||
OAUTH_CLIENT_ID: 'MDqjm1kcWKuZfqHJXjxwAV20i44aT7m4VhhTL3Nm',
|
||||
OAUTH_CLIENT_SECRET:
|
||||
'GY2F8te6iAVYt1TNAUVLzWZEXb6JoMNp6chbjqaXNq4gS5xTDL54HqBiAlV1jFKarN28LQ7FUsYX4SbwjfEhZhgeoKuBnZKjR9eiu7RawnGgxIK9ffvUfMkjRxnmiGI5',
|
||||
apiUrl: 'http://localhost:8080',
|
||||
};
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
{
|
||||
"/backend": {
|
||||
"/api": {
|
||||
"target": "http://localhost:8080/",
|
||||
"secure": false,
|
||||
"logLevel": "debug",
|
||||
"pathRewrite": {
|
||||
"^/backend": ""
|
||||
"^/api": ""
|
||||
},
|
||||
"changeOrigin": true
|
||||
}
|
||||
|
|
Reference in a new issue