einbau von rollen, neue Admin Ansicht

This commit is contained in:
2025-03-08 11:18:31 +01:00
parent dded8b8ca9
commit 5a56b3554d
29 changed files with 788 additions and 426 deletions

View File

@@ -3,10 +3,12 @@ import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { FirebaseApp } from '@angular/fire/app';
import { GoogleAuthProvider, UserCredential, createUserWithEmailAndPassword, getAuth, signInWithEmailAndPassword, signInWithPopup } from 'firebase/auth';
import { firstValueFrom } from 'rxjs';
import { BehaviorSubject, Observable, catchError, firstValueFrom, map, of, shareReplay, take, tap } from 'rxjs';
import { environment } from '../../environments/environment';
import { MailService } from './mail.service';
export type UserRole = 'admin' | 'pro' | 'guest';
@Injectable({
providedIn: 'root',
})
@@ -15,57 +17,90 @@ export class AuthService {
private auth = getAuth(this.app);
private http = inject(HttpClient);
private mailService = inject(MailService);
// Add a BehaviorSubject to track the current user role
private userRoleSubject = new BehaviorSubject<UserRole | null>(null);
public userRole$ = this.userRoleSubject.asObservable();
// Referenz für den gecachten API-Aufruf
private cachedUserRole$: Observable<UserRole | null> | null = null;
// Registrierung mit Email und Passwort
async registerWithEmail(email: string, password: string): Promise<UserCredential> {
// Bestimmen der aktuellen Umgebung/Domain für die Verifizierungs-URL
let verificationUrl = '';
// Prüfen der aktuellen Umgebung basierend auf dem Host
const currentHost = window.location.hostname;
if (currentHost.includes('localhost')) {
verificationUrl = 'http://localhost:4200/email-authorized';
} else if (currentHost.includes('dev.bizmatch.net')) {
verificationUrl = 'https://dev.bizmatch.net/email-authorized';
} else {
verificationUrl = 'https://www.bizmatch.net/email-authorized';
// Zeitraum in ms, nach dem der Cache zurückgesetzt werden soll (z.B. 5 Minuten)
private cacheDuration = 5 * 60 * 1000;
private lastCacheTime = 0;
constructor() {
// Load role from token when service is initialized
this.loadRoleFromToken();
}
// ActionCode-Einstellungen mit der dynamischen URL
const actionCodeSettings = {
url: `${verificationUrl}?email=${email}`,
handleCodeInApp: true
};
// Benutzer erstellen
const userCredential = await createUserWithEmailAndPassword(this.auth, email, password);
// E-Mail-Verifizierung mit den angepassten ActionCode-Einstellungen senden
if (userCredential.user) {
//await sendEmailVerification(userCredential.user, actionCodeSettings);
this.mailService.sendVerificationEmail(userCredential.user.email).subscribe({
next: () => {
console.log('Verification email sent successfully');
// Erfolgsmeldung anzeigen
},
error: (error) => {
console.error('Error sending verification email', error);
// Fehlermeldung anzeigen
private loadRoleFromToken(): void {
this.getToken().then(token => {
if (token) {
const role = this.extractRoleFromToken(token);
this.userRoleSubject.next(role);
} else {
this.userRoleSubject.next(null);
}
});
}
// Token, RefreshToken und ggf. photoURL speichern
const token = await userCredential.user.getIdToken();
localStorage.setItem('authToken', token);
localStorage.setItem('refreshToken', userCredential.user.refreshToken);
if (userCredential.user.photoURL) {
localStorage.setItem('photoURL', userCredential.user.photoURL);
private extractRoleFromToken(token: string): UserRole | null {
try {
const payloadBase64 = token.split('.')[1];
const payloadJson = atob(payloadBase64.replace(/-/g, '+').replace(/_/g, '/'));
const payload = JSON.parse(payloadJson);
return (payload.role as UserRole) || null;
} catch (e) {
return null;
}
}
// Registrierung mit Email und Passwort
async registerWithEmail(email: string, password: string): Promise<UserCredential> {
// Bestimmen der aktuellen Umgebung/Domain für die Verifizierungs-URL
let verificationUrl = '';
return userCredential;
}
// Prüfen der aktuellen Umgebung basierend auf dem Host
const currentHost = window.location.hostname;
if (currentHost.includes('localhost')) {
verificationUrl = 'http://localhost:4200/email-authorized';
} else if (currentHost.includes('dev.bizmatch.net')) {
verificationUrl = 'https://dev.bizmatch.net/email-authorized';
} else {
verificationUrl = 'https://www.bizmatch.net/email-authorized';
}
// ActionCode-Einstellungen mit der dynamischen URL
const actionCodeSettings = {
url: `${verificationUrl}?email=${email}`,
handleCodeInApp: true,
};
// Benutzer erstellen
const userCredential = await createUserWithEmailAndPassword(this.auth, email, password);
// E-Mail-Verifizierung mit den angepassten ActionCode-Einstellungen senden
if (userCredential.user) {
//await sendEmailVerification(userCredential.user, actionCodeSettings);
this.mailService.sendVerificationEmail(userCredential.user.email).subscribe({
next: () => {
console.log('Verification email sent successfully');
// Erfolgsmeldung anzeigen
},
error: error => {
console.error('Error sending verification email', error);
// Fehlermeldung anzeigen
},
});
}
// const token = await userCredential.user.getIdToken();
// localStorage.setItem('authToken', token);
// localStorage.setItem('refreshToken', userCredential.user.refreshToken);
// if (userCredential.user.photoURL) {
// localStorage.setItem('photoURL', userCredential.user.photoURL);
// }
return userCredential;
}
// Login mit Email und Passwort
loginWithEmail(email: string, password: string): Promise<UserCredential> {
@@ -77,6 +112,7 @@ async registerWithEmail(email: string, password: string): Promise<UserCredential
if (userCredential.user.photoURL) {
localStorage.setItem('photoURL', userCredential.user.photoURL);
}
this.loadRoleFromToken();
}
return userCredential;
});
@@ -93,6 +129,7 @@ async registerWithEmail(email: string, password: string): Promise<UserCredential
if (userCredential.user.photoURL) {
localStorage.setItem('photoURL', userCredential.user.photoURL);
}
this.loadRoleFromToken();
}
return userCredential;
});
@@ -103,9 +140,74 @@ async registerWithEmail(email: string, password: string): Promise<UserCredential
localStorage.removeItem('authToken');
localStorage.removeItem('refreshToken');
localStorage.removeItem('photoURL');
this.clearRoleCache();
this.userRoleSubject.next(null);
return this.auth.signOut();
}
isAdmin(): Observable<boolean> {
return this.getUserRole().pipe(
map(role => role === 'admin'),
// take(1) ist optional - es beendet die Subscription, nachdem ein Wert geliefert wurde
// Nützlich, wenn du die Methode in einem Template mit dem async pipe verwendest
take(1),
);
}
// Get current user's role from the server with caching
getUserRole(): Observable<UserRole | null> {
const now = Date.now();
// Cache zurücksetzen, wenn die Caching-Zeit abgelaufen ist oder kein Cache existiert
if (!this.cachedUserRole$ || now - this.lastCacheTime > this.cacheDuration) {
this.lastCacheTime = now;
this.cachedUserRole$ = this.http.get<{ role: UserRole | null }>(`${environment.apiBaseUrl}/bizmatch/auth/me/role`).pipe(
map(response => response.role),
tap(role => this.userRoleSubject.next(role)),
catchError(error => {
console.error('Error fetching user role', error);
return of(null);
}),
// Cache für mehrere Subscriber und behalte den letzten Wert
// Der Parameter 1 gibt an, dass der letzte Wert gecacht werden soll
// refCount: false bedeutet, dass der Cache nicht zurückgesetzt wird, wenn keine Subscriber mehr da sind
shareReplay({ bufferSize: 1, refCount: false }),
);
}
return this.cachedUserRole$;
}
clearRoleCache(): void {
this.cachedUserRole$ = null;
this.lastCacheTime = 0;
}
// Check if user has a specific role
hasRole(role: UserRole): Observable<boolean> {
return this.userRole$.pipe(
map(userRole => {
if (role === 'guest') {
// Any authenticated user can access guest features
return userRole !== null;
} else if (role === 'pro') {
// Both pro and admin can access pro features
return userRole === 'pro' || userRole === 'admin';
} else if (role === 'admin') {
// Only admin can access admin features
return userRole === 'admin';
}
return false;
}),
);
}
// Force refresh the token to get updated custom claims
async refreshUserClaims(): Promise<void> {
this.clearRoleCache();
if (this.auth.currentUser) {
await this.auth.currentUser.getIdToken(true);
const token = await this.auth.currentUser.getIdToken();
localStorage.setItem('authToken', token);
this.loadRoleFromToken();
}
}
// Prüft, ob ein Token noch gültig ist (über die "exp"-Eigenschaft)
private isTokenValid(token: string): boolean {
try {