Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions client/src/utils/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,34 @@
// JwtPayload: A type definition representing the structure of a JSON Web Token payload.
// jwtDecode: A function used to decode a JSON Web Token (JWT) and extract its payload.
import { type JwtPayload, jwtDecode } from 'jwt-decode';
import type { UserData } from '../interfaces/UserData';

// Extending the JwtPayload type to include additional data fields specific to the application.
interface ExtendedJwt extends JwtPayload {
data:{
id: number;
username: string;
email: string;
};
}

class AuthService {
// This method decodes the JWT token to get the user's profile information.
getProfile() {
// Decode the JSON Web Token (JWT) using the jwtDecode function, specifying the expected payload type as UserData.
// The getToken() method is called to retrieve the JWT, which is then passed to jwtDecode to extract and return its payload.
return jwtDecode<UserData>(this.getToken());
// jwtDecode is a function that is used to decode the JWT token and return its payload.
return jwtDecode<ExtendedJwt>(this.getToken());
}

// This method checks if the user is logged in by verifying the presence and validity of the JWT token.
loggedIn() {
const token = this.getToken();
// Returns true if the token exists and is not expired.
return !!token && !this.isTokenExpired(token);
}

// This method checks if the provided token is expired.
isTokenExpired(token: string) {
try {
// Attempt to decode the provided token using jwtDecode, expecting a JwtPayload type.
// jwtDecode decodes the token to check its expiration date.
const decoded = jwtDecode<JwtPayload>(token);

// Check if the decoded token has an 'exp' (expiration) property and if it is less than the current time in seconds.
Expand All @@ -32,16 +43,20 @@ class AuthService {
}
}

// This method retrieves the JWT token from local storage.
getToken(): string {
const loggedUser = localStorage.getItem('id_token') || '';
// Returns the token stored in local storage.
return loggedUser;
}

// This method logs in the user by storing the JWT token in local storage and redirecting to the home page.
login(idToken: string) {
localStorage.setItem('id_token', idToken);
window.location.assign('/');
}

// This method logs out the user by removing the JWT token from local storage and redirecting to the home page.
logout() {
localStorage.removeItem('id_token');
window.location.assign('/');
Expand Down