feat: add GitHub OAuth2 authentication support

This commit is contained in:
Constantin Simonis 2025-05-21 10:33:30 +02:00
commit cc1979a068
No known key found for this signature in database
GPG key ID: 3878FF77C24AF4D2
24 changed files with 845 additions and 8 deletions

View file

@ -1,7 +1,7 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable, tap } from 'rxjs';
import { Router } from '@angular/router';
import { Router, ActivatedRoute } from '@angular/router';
import { LoginRequest } from '../model/auth/LoginRequest';
import { RegisterRequest } from '../model/auth/RegisterRequest';
import { AuthResponse } from '../model/auth/AuthResponse';
@ -17,20 +17,41 @@ const USER_KEY = 'user';
export class AuthService {
private authUrl = `${environment.apiUrl}/auth`;
private userUrl = `${environment.apiUrl}/users`;
private oauthUrl = `${environment.apiUrl}/oauth2`;
userSubject: BehaviorSubject<User | null>;
constructor(
private http: HttpClient,
private router: Router
private router: Router,
private route: ActivatedRoute
) {
this.userSubject = new BehaviorSubject<User | null>(this.getUserFromStorage());
// Check for token in URL (OAuth callback) on initialization
this.route.queryParams.subscribe(params => {
const token = params['token'];
if (token) {
this.handleOAuthCallback(token);
}
});
if (this.getToken()) {
this.loadCurrentUser();
}
}
private handleOAuthCallback(token: string): void {
this.setToken(token);
this.loadCurrentUser();
// Clean up the URL by removing the token
this.router.navigate([], {
relativeTo: this.route,
queryParams: {},
replaceUrl: true
});
}
public get currentUserValue(): User | null {
return this.userSubject.value;
}
@ -48,6 +69,16 @@ export class AuthService {
return this.http.post<User>(`${this.authUrl}/register`, registerRequest);
}
githubAuth(code: string): Observable<AuthResponse> {
return this.http.post<AuthResponse>(`${this.oauthUrl}/github/callback`, { code }).pipe(
tap((response) => {
console.log(response.token);
this.setToken(response.token);
this.loadCurrentUser();
})
);
}
logout(): void {
localStorage.removeItem(TOKEN_KEY);
localStorage.removeItem(USER_KEY);