mirror of
https://gitverse.ru/kpa39l/telepost.git
synced 2026-09-30 02:15:13 +00:00
Initial commit
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
// Utility functions for authentication checks
|
||||
|
||||
/**
|
||||
* Check if user is authenticated by checking for token in localStorage
|
||||
* @returns {boolean} - True if user is authenticated, false otherwise
|
||||
*/
|
||||
export function isAuthenticated() {
|
||||
const token = localStorage.getItem('token');
|
||||
return !!token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current user's token
|
||||
* @returns {string|null} - Token if exists, null otherwise
|
||||
*/
|
||||
export function getToken() {
|
||||
return localStorage.getItem('token');
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear authentication data
|
||||
*/
|
||||
export function logout() {
|
||||
localStorage.removeItem('token');
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate token by making a request to the backend
|
||||
* @returns {Promise<boolean>} - Promise that resolves to true if token is valid, false otherwise
|
||||
*/
|
||||
export async function validateToken() {
|
||||
const token = getToken();
|
||||
if (!token) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/v1/auth/me', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
return response.ok;
|
||||
} catch (error) {
|
||||
console.error('Error validating token:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user