feat: implement authentication with JWT and user management

This commit is contained in:
Constantin Simonis 2025-05-07 13:42:04 +02:00
commit 35d8fbaea0
No known key found for this signature in database
GPG key ID: 3878FF77C24AF4D2
42 changed files with 989 additions and 397 deletions

View file

@ -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);
}
}