feat: created TokenService and moved logic from AuthService and ApiService
This commit is contained in:
parent
2c102ddddc
commit
a00863ef9e
9 changed files with 122 additions and 86 deletions
|
|
@ -51,8 +51,7 @@
|
||||||
[style.background-color]="user.color"
|
[style.background-color]="user.color"
|
||||||
>{{ user.initials }}</span
|
>{{ user.initials }}</span
|
||||||
>} } @for (user of task.userData; track user) { @for (assigned of
|
>} } @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
|
<span
|
||||||
class="footer-badged"
|
class="footer-badged"
|
||||||
(mousemove)="openDialog(user.id, $event)"
|
(mousemove)="openDialog(user.id, $event)"
|
||||||
|
|
|
||||||
|
|
@ -2,15 +2,20 @@ import { Injectable } from '@angular/core';
|
||||||
import { Router } from '@angular/router';
|
import { Router } from '@angular/router';
|
||||||
import { catchError, map, Observable, of } from 'rxjs';
|
import { catchError, map, Observable, of } from 'rxjs';
|
||||||
import { AuthService } from '../services/auth.service';
|
import { AuthService } from '../services/auth.service';
|
||||||
|
import { TokenService } from '../services/token.service';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class AuthenticatedGuard {
|
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 {
|
canActivate(): Observable<boolean> | Promise<boolean> | boolean {
|
||||||
const authToken = this.authService.checkAuthToken();
|
const authToken = this.tokenService.getAuthToken();
|
||||||
if (!authToken) {
|
if (!authToken) {
|
||||||
this.router.navigate(['/login']);
|
this.router.navigate(['/login']);
|
||||||
return false;
|
return false;
|
||||||
|
|
|
||||||
|
|
@ -3,15 +3,20 @@ import { Router } from '@angular/router';
|
||||||
import { Observable, of } from 'rxjs';
|
import { Observable, of } from 'rxjs';
|
||||||
import { map, catchError } from 'rxjs/operators';
|
import { map, catchError } from 'rxjs/operators';
|
||||||
import { AuthService } from '../services/auth.service';
|
import { AuthService } from '../services/auth.service';
|
||||||
|
import { TokenService } from '../services/token.service';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class RedirectIfAuthenticatedGuard {
|
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 {
|
canActivate(): Observable<boolean> | Promise<boolean> | boolean {
|
||||||
const authToken = this.authService.checkAuthToken();
|
const authToken = this.tokenService.getAuthToken();
|
||||||
if (!authToken) {
|
if (!authToken) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,5 @@ export interface Subtask {
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Assignee {
|
export interface Assignee {
|
||||||
id: string;
|
|
||||||
userId: string;
|
userId: string;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,10 @@
|
||||||
import { Injectable, signal } from '@angular/core';
|
import { Injectable, signal } from '@angular/core';
|
||||||
import { HttpClient } from '@angular/common/http';
|
import { HttpClient, HttpHeaders } from '@angular/common/http';
|
||||||
import { Observable } from 'rxjs';
|
import { Observable } from 'rxjs';
|
||||||
import { apiConfig } from '../environments/config';
|
import { apiConfig } from '../environments/config';
|
||||||
import { Task } from '../interfaces/task.interface';
|
import { Task } from '../interfaces/task.interface';
|
||||||
import { User } from '../interfaces/user.interface';
|
import { User } from '../interfaces/user.interface';
|
||||||
|
import { TokenService } from './token.service';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
|
|
@ -11,7 +12,7 @@ import { User } from '../interfaces/user.interface';
|
||||||
export class ApiService {
|
export class ApiService {
|
||||||
private apiUrl = apiConfig.apiUrl;
|
private apiUrl = apiConfig.apiUrl;
|
||||||
|
|
||||||
constructor(private http: HttpClient) {}
|
constructor(private http: HttpClient, private tokenService: TokenService) {}
|
||||||
|
|
||||||
// ------------- TASKS ------------- //
|
// ------------- TASKS ------------- //
|
||||||
|
|
||||||
|
|
@ -43,4 +44,26 @@ export class ApiService {
|
||||||
params: { ids: userIds.join(',') },
|
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 });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,3 @@
|
||||||
import { HttpClient, HttpHeaders } from '@angular/common/http';
|
|
||||||
import { Injectable } from '@angular/core';
|
import { Injectable } from '@angular/core';
|
||||||
import {
|
import {
|
||||||
BehaviorSubject,
|
BehaviorSubject,
|
||||||
|
|
@ -9,102 +8,64 @@ import {
|
||||||
of,
|
of,
|
||||||
} from 'rxjs';
|
} from 'rxjs';
|
||||||
import { apiConfig } from '../environments/config';
|
import { apiConfig } from '../environments/config';
|
||||||
|
import { ApiService } from './api.service';
|
||||||
|
import { TokenService } from './token.service';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class AuthService {
|
export class AuthService {
|
||||||
private apiUrl = apiConfig.apiUrl;
|
private apiUrl = apiConfig.apiUrl;
|
||||||
|
private currentUserIdSubject = new BehaviorSubject<string | null>(null);
|
||||||
|
|
||||||
private currentUserIdSubject: BehaviorSubject<string | null> =
|
constructor(
|
||||||
new BehaviorSubject<string | null>(null);
|
private apiService: ApiService,
|
||||||
|
private tokenService: TokenService
|
||||||
constructor(private http: HttpClient) {
|
) {
|
||||||
const storedUserId =
|
this.currentUserIdSubject.next(this.tokenService.getUserId());
|
||||||
localStorage.getItem('currentUserId') ||
|
|
||||||
sessionStorage.getItem('currentUserId');
|
|
||||||
this.currentUserIdSubject = new BehaviorSubject<string | null>(
|
|
||||||
storedUserId
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async login(body: any, storage: boolean) {
|
async login(body: any, storage: boolean) {
|
||||||
const data = (await lastValueFrom(
|
try {
|
||||||
this.http.post(`${this.apiUrl}/auth/login/`, body)
|
const data = await lastValueFrom(
|
||||||
)) as { token: string; user_id: string };
|
this.apiService.post<{ token: string; userId: string }>(
|
||||||
this.storeAuthToken(data.token, storage);
|
`${this.apiUrl}/auth/login/`,
|
||||||
this.storeUserId(data.user_id, storage);
|
body
|
||||||
this.currentUserIdSubject.next(data.user_id);
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
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() {
|
async logout() {
|
||||||
const token = this.checkAuthToken();
|
try {
|
||||||
if (!token) return;
|
|
||||||
|
|
||||||
await lastValueFrom(
|
await lastValueFrom(
|
||||||
this.http.post(
|
this.apiService.post(`${this.apiUrl}/auth/logout/`, {})
|
||||||
`${this.apiUrl}/auth/logout/`,
|
);
|
||||||
{},
|
|
||||||
{ headers: { Authorization: `Token ${token}` } }
|
this.tokenService.deleteAuthToken();
|
||||||
)
|
this.tokenService.deleteUserId();
|
||||||
).catch((error) => console.error('Logout failed:', error));
|
this.currentUserIdSubject.next(null);
|
||||||
|
|
||||||
this.deleteAuthToken();
|
|
||||||
this.deleteUserId();
|
|
||||||
window.location.href = '/login';
|
window.location.href = '/login';
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Logout failed:', error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
checkAuthUser(): Observable<boolean> {
|
checkAuthUser(): Observable<boolean> {
|
||||||
const headers = this.getAuthHeaders();
|
return this.apiService.get(`${this.apiUrl}/auth/`).pipe(
|
||||||
return this.http.get<any>(`${this.apiUrl}/auth/`, { headers }).pipe(
|
map(() => true),
|
||||||
map(() => {
|
|
||||||
return true;
|
|
||||||
}),
|
|
||||||
catchError(() => of(false))
|
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> {
|
getCurrentUserId(): Observable<string | null> {
|
||||||
return this.currentUserIdSubject.asObservable();
|
return this.currentUserIdSubject.asObservable();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
45
src/app/services/token.service.ts
Executable file
45
src/app/services/token.service.ts
Executable 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -4,7 +4,6 @@ import { NavbarComponent } from './navbar/navbar.component';
|
||||||
import { CommonModule } from '@angular/common';
|
import { CommonModule } from '@angular/common';
|
||||||
import { TranslateModule } from '@ngx-translate/core';
|
import { TranslateModule } from '@ngx-translate/core';
|
||||||
import { FirebaseService } from '../../../services/firebase.service';
|
import { FirebaseService } from '../../../services/firebase.service';
|
||||||
import { Observable } from 'rxjs';
|
|
||||||
import { AuthService } from '../../../services/auth.service';
|
import { AuthService } from '../../../services/auth.service';
|
||||||
import { ApiService } from '../../../services/api.service';
|
import { ApiService } from '../../../services/api.service';
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -70,7 +70,7 @@
|
||||||
@if (task.assignees.length > 0) {
|
@if (task.assignees.length > 0) {
|
||||||
<div class="assigned">
|
<div class="assigned">
|
||||||
<p>{{ "addTask.assigned" | translate }}:</p>
|
<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) {
|
task.userData; track user) { @if (assigned.userId === user.id) {
|
||||||
<div class="users">
|
<div class="users">
|
||||||
<div
|
<div
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue