You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
50 lines
1.2 KiB
50 lines
1.2 KiB
|
2 years ago
|
import { Injectable } from '@angular/core';
|
||
|
|
import { HttpClient, HttpHeaders } from "@angular/common/http";
|
||
|
|
import { Observable } from 'rxjs';
|
||
|
|
import { jwtDecode } from "jwt-decode";
|
||
|
|
|
||
|
|
@Injectable({
|
||
|
|
providedIn: 'root'
|
||
|
|
})
|
||
|
|
export class AuthService {
|
||
|
|
serverEndpoint = "http://localhost:3000/"
|
||
|
|
|
||
|
|
constructor(private httpClient: HttpClient) { }
|
||
|
|
|
||
|
|
login(username: string, password: string): Observable<any> {
|
||
|
|
const headers = new HttpHeaders();
|
||
|
|
headers.append('Content-Type', 'application/json');
|
||
|
|
return this.httpClient.post(this.serverEndpoint+"auth/login", { username, password }, { headers })
|
||
|
|
}
|
||
|
|
|
||
|
|
testProfile(): Observable<any> {
|
||
|
|
console.log("SendTestProfile")
|
||
|
|
return this.httpClient.get(this.serverEndpoint+"auth/profile")
|
||
|
|
}
|
||
|
|
|
||
|
|
logout(): void {
|
||
|
|
// Clear the token from local storage
|
||
|
|
localStorage.removeItem('token');
|
||
|
|
}
|
||
|
|
|
||
|
|
isAuthenticated(): boolean {
|
||
|
|
const token = localStorage.getItem('token');
|
||
|
|
|
||
|
|
if (!token) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
try {
|
||
|
|
const decoded: any = jwtDecode(token);
|
||
|
|
|
||
|
|
// Check if the token is expired
|
||
|
|
const isTokenExpired = decoded.exp < Date.now() / 1000;
|
||
|
|
|
||
|
|
return !isTokenExpired;
|
||
|
|
} catch (error) {
|
||
|
|
console.error('Error decoding JWT:', error);
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|