feat: created TokenService and moved logic from AuthService and ApiService

This commit is contained in:
Chneemann 2025-03-24 09:10:25 +01:00
parent 2c102ddddc
commit a00863ef9e
9 changed files with 122 additions and 86 deletions

View file

@ -51,8 +51,7 @@
[style.background-color]="user.color"
>{{ user.initials }}</span
>} } @for (user of task.userData; track user) { @for (assigned of
task.assignees; track assigned.id) { @if (assigned.userId === user.id)
{
task.assignees; track assigned) { @if (assigned.userId === user.id) {
<span
class="footer-badged"
(mousemove)="openDialog(user.id, $event)"

View file

@ -2,15 +2,20 @@ import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, map, Observable, of } from 'rxjs';
import { AuthService } from '../services/auth.service';
import { TokenService } from '../services/token.service';
@Injectable({
providedIn: 'root',
})
export class AuthenticatedGuard {
constructor(private authService: AuthService, private router: Router) {}
constructor(
private authService: AuthService,
private tokenService: TokenService,
private router: Router
) {}
canActivate(): Observable<boolean> | Promise<boolean> | boolean {
const authToken = this.authService.checkAuthToken();
const authToken = this.tokenService.getAuthToken();
if (!authToken) {
this.router.navigate(['/login']);
return false;

View file

@ -3,15 +3,20 @@ import { Router } from '@angular/router';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { AuthService } from '../services/auth.service';
import { TokenService } from '../services/token.service';
@Injectable({
providedIn: 'root',
})
export class RedirectIfAuthenticatedGuard {
constructor(private authService: AuthService, private router: Router) {}
constructor(
private authService: AuthService,
private tokenService: TokenService,
private router: Router
) {}
canActivate(): Observable<boolean> | Promise<boolean> | boolean {
const authToken = this.authService.checkAuthToken();
const authToken = this.tokenService.getAuthToken();
if (!authToken) {
return true;
}

View file

@ -24,6 +24,5 @@ export interface Subtask {
}
export interface Assignee {
id: string;
userId: string;
}

View file

@ -1,9 +1,10 @@
import { Injectable, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { apiConfig } from '../environments/config';
import { Task } from '../interfaces/task.interface';
import { User } from '../interfaces/user.interface';
import { TokenService } from './token.service';
@Injectable({
providedIn: 'root',
@ -11,7 +12,7 @@ import { User } from '../interfaces/user.interface';
export class ApiService {
private apiUrl = apiConfig.apiUrl;
constructor(private http: HttpClient) {}
constructor(private http: HttpClient, private tokenService: TokenService) {}
// ------------- TASKS ------------- //
@ -43,4 +44,26 @@ export class ApiService {
params: { ids: userIds.join(',') },
});
}
// ------------- TOKEN ------------- //
private addAuthHeaders(headers: HttpHeaders): HttpHeaders {
const token = this.tokenService.getAuthToken();
if (token) {
return headers.set('Authorization', `Token ${token}`);
}
return headers;
}
post<T>(url: string, body: any): Observable<T> {
let headers = new HttpHeaders();
headers = this.addAuthHeaders(headers);
return this.http.post<T>(url, body, { headers });
}
get<T>(url: string): Observable<T> {
let headers = new HttpHeaders();
headers = this.addAuthHeaders(headers);
return this.http.get<T>(url, { headers });
}
}

View file

@ -1,4 +1,3 @@
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {
BehaviorSubject,
@ -9,102 +8,64 @@ import {
of,
} from 'rxjs';
import { apiConfig } from '../environments/config';
import { ApiService } from './api.service';
import { TokenService } from './token.service';
@Injectable({
providedIn: 'root',
})
export class AuthService {
private apiUrl = apiConfig.apiUrl;
private currentUserIdSubject = new BehaviorSubject<string | null>(null);
private currentUserIdSubject: BehaviorSubject<string | null> =
new BehaviorSubject<string | null>(null);
constructor(private http: HttpClient) {
const storedUserId =
localStorage.getItem('currentUserId') ||
sessionStorage.getItem('currentUserId');
this.currentUserIdSubject = new BehaviorSubject<string | null>(
storedUserId
);
constructor(
private apiService: ApiService,
private tokenService: TokenService
) {
this.currentUserIdSubject.next(this.tokenService.getUserId());
}
async login(body: any, storage: boolean) {
const data = (await lastValueFrom(
this.http.post(`${this.apiUrl}/auth/login/`, body)
)) as { token: string; user_id: string };
this.storeAuthToken(data.token, storage);
this.storeUserId(data.user_id, storage);
this.currentUserIdSubject.next(data.user_id);
try {
const data = await lastValueFrom(
this.apiService.post<{ token: string; userId: string }>(
`${this.apiUrl}/auth/login/`,
body
)
);
this.tokenService.storeAuthToken(data.token, storage);
this.tokenService.storeUserId(data.userId, storage);
this.currentUserIdSubject.next(data.userId);
} catch (error) {
console.error('Login failed:', error);
throw error;
}
}
async logout() {
const token = this.checkAuthToken();
if (!token) return;
try {
await lastValueFrom(
this.http.post(
`${this.apiUrl}/auth/logout/`,
{},
{ headers: { Authorization: `Token ${token}` } }
)
).catch((error) => console.error('Logout failed:', error));
this.apiService.post(`${this.apiUrl}/auth/logout/`, {})
);
this.tokenService.deleteAuthToken();
this.tokenService.deleteUserId();
this.currentUserIdSubject.next(null);
this.deleteAuthToken();
this.deleteUserId();
window.location.href = '/login';
} catch (error) {
console.error('Logout failed:', error);
}
}
checkAuthUser(): Observable<boolean> {
const headers = this.getAuthHeaders();
return this.http.get<any>(`${this.apiUrl}/auth/`, { headers }).pipe(
map(() => {
return true;
}),
return this.apiService.get(`${this.apiUrl}/auth/`).pipe(
map(() => true),
catchError(() => of(false))
);
}
private getAuthHeaders(): HttpHeaders {
let authToken = localStorage.getItem('authToken');
if (!authToken) {
authToken = sessionStorage.getItem('authToken');
}
return new HttpHeaders({
Authorization: `Token ${authToken}`,
});
}
private storeAuthToken(data: any, storage: boolean) {
storage
? localStorage.setItem('authToken', data.toString())
: sessionStorage.setItem('authToken', data.toString());
}
private storeUserId(userId: string, storage: boolean) {
if (storage) {
localStorage.setItem('currentUserId', userId);
} else {
sessionStorage.setItem('currentUserId', userId);
}
}
private deleteAuthToken() {
localStorage.removeItem('authToken');
sessionStorage.removeItem('authToken');
}
private deleteUserId() {
localStorage.removeItem('currentUserId');
sessionStorage.removeItem('currentUserId');
this.currentUserIdSubject.next(null);
}
checkAuthToken(): string | null {
return (
localStorage.getItem('authToken') || sessionStorage.getItem('authToken')
);
}
getCurrentUserId(): Observable<string | null> {
return this.currentUserIdSubject.asObservable();
}

View file

@ -0,0 +1,45 @@
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class TokenService {
private TOKEN_KEY = 'authToken';
private USER_ID_KEY = 'currentUserId';
storeAuthToken(token: string, persistent: boolean): void {
persistent
? localStorage.setItem(this.TOKEN_KEY, token)
: sessionStorage.setItem(this.TOKEN_KEY, token);
}
getAuthToken(): string | null {
return (
localStorage.getItem(this.TOKEN_KEY) ||
sessionStorage.getItem(this.TOKEN_KEY)
);
}
deleteAuthToken(): void {
localStorage.removeItem(this.TOKEN_KEY);
sessionStorage.removeItem(this.TOKEN_KEY);
}
storeUserId(userId: string, persistent: boolean): void {
persistent
? localStorage.setItem(this.USER_ID_KEY, userId)
: sessionStorage.setItem(this.USER_ID_KEY, userId);
}
getUserId(): string | null {
return (
localStorage.getItem(this.USER_ID_KEY) ||
sessionStorage.getItem(this.USER_ID_KEY)
);
}
deleteUserId(): void {
localStorage.removeItem(this.USER_ID_KEY);
sessionStorage.removeItem(this.USER_ID_KEY);
}
}

View file

@ -4,7 +4,6 @@ import { NavbarComponent } from './navbar/navbar.component';
import { CommonModule } from '@angular/common';
import { TranslateModule } from '@ngx-translate/core';
import { FirebaseService } from '../../../services/firebase.service';
import { Observable } from 'rxjs';
import { AuthService } from '../../../services/auth.service';
import { ApiService } from '../../../services/api.service';

View file

@ -70,7 +70,7 @@
@if (task.assignees.length > 0) {
<div class="assigned">
<p>{{ "addTask.assigned" | translate }}:</p>
@for (assigned of task.assignees; track assigned.id) { @for (user of
@for (assigned of task.assignees; track assigned) { @for (user of
task.userData; track user) { @if (assigned.userId === user.id) {
<div class="users">
<div