einbau von rollen, neue Admin Ansicht
This commit is contained in:
@@ -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 {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { HttpClient, HttpHeaders } from '@angular/common/http';
|
||||
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
|
||||
import { Injectable } from '@angular/core';
|
||||
import { PaymentMethod } from '@stripe/stripe-js';
|
||||
import { catchError, forkJoin, lastValueFrom, map, Observable, of, Subject } from 'rxjs';
|
||||
import urlcat from 'urlcat';
|
||||
import { User } from '../../../../bizmatch-server/src/models/db.model';
|
||||
import { CombinedUser, KeycloakUser, ResponseUsersArray, StripeSubscription, StripeUser, UserListingCriteria } from '../../../../bizmatch-server/src/models/main.model';
|
||||
import { CombinedUser, FirebaseUserInfo, KeycloakUser, ResponseUsersArray, StripeSubscription, StripeUser, UserListingCriteria, UserRole, UsersResponse } from '../../../../bizmatch-server/src/models/main.model';
|
||||
import { environment } from '../../environments/environment';
|
||||
|
||||
@Injectable({
|
||||
@@ -56,6 +56,41 @@ export class UserService {
|
||||
// -------------------------------
|
||||
// ADMIN SERVICES
|
||||
// -------------------------------
|
||||
/**
|
||||
* Ruft alle Benutzer mit Paginierung ab
|
||||
*/
|
||||
getAllUsers(maxResults?: number, pageToken?: string): Observable<UsersResponse> {
|
||||
let params = new HttpParams();
|
||||
|
||||
if (maxResults) {
|
||||
params = params.set('maxResults', maxResults.toString());
|
||||
}
|
||||
|
||||
if (pageToken) {
|
||||
params = params.set('pageToken', pageToken);
|
||||
}
|
||||
|
||||
return this.http.get<UsersResponse>(`${this.apiBaseUrl}/bizmatch/auth`, { params });
|
||||
}
|
||||
|
||||
/**
|
||||
* Ruft Benutzer mit einer bestimmten Rolle ab
|
||||
*/
|
||||
getUsersByRole(role: UserRole): Observable<{ users: FirebaseUserInfo[] }> {
|
||||
return this.http.get<{ users: FirebaseUserInfo[] }>(`${this.apiBaseUrl}/bizmatch/auth/role/${role}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ändert die Rolle eines Benutzers
|
||||
*/
|
||||
setUserRole(uid: string, role: UserRole): Observable<{ success: boolean }> {
|
||||
return this.http.post<{ success: boolean }>(`${this.apiBaseUrl}/${uid}/bizmatch/auth/role`, { role });
|
||||
}
|
||||
|
||||
// -------------------------------
|
||||
// OLDADMIN SERVICES
|
||||
// -------------------------------
|
||||
|
||||
getKeycloakUsers(): Observable<KeycloakUser[]> {
|
||||
return this.http.get<KeycloakUser[]>(`${this.apiBaseUrl}/bizmatch/auth/user/all`).pipe(
|
||||
catchError(error => {
|
||||
|
||||
Reference in New Issue
Block a user