mirror of
https://gitverse.ru/kpa39l/telepost.git
synced 2026-09-29 18:05:08 +00:00
51 lines
1.1 KiB
JavaScript
51 lines
1.1 KiB
JavaScript
// 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;
|
|
}
|
|
} |