52 lines
1.2 KiB
JavaScript
52 lines
1.2 KiB
JavaScript
|
|
/**
|
||
|
|
* AuthService
|
||
|
|
* Manages authentication tokens securely using localStorage.
|
||
|
|
*
|
||
|
|
* Methods:
|
||
|
|
* addToken(token) — store JWT token
|
||
|
|
* getToken() — retrieve JWT token
|
||
|
|
* deleteToken() — remove JWT token
|
||
|
|
*
|
||
|
|
* Usage:
|
||
|
|
* import AuthService from '@/app/services/AuthService';
|
||
|
|
* AuthService.addToken(token);
|
||
|
|
* const token = AuthService.getToken();
|
||
|
|
* AuthService.deleteToken();
|
||
|
|
*/
|
||
|
|
const TOKEN_KEY = 'auth_token';
|
||
|
|
|
||
|
|
const AuthService = Object.freeze({
|
||
|
|
/**
|
||
|
|
* Store token in localStorage
|
||
|
|
* @param {string} token — JWT string
|
||
|
|
*/
|
||
|
|
addToken(token) {
|
||
|
|
if (!token || typeof token !== 'string') {
|
||
|
|
console.error('[AuthService] addToken: invalid token', token);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
localStorage.setItem(TOKEN_KEY, token);
|
||
|
|
console.log('[AuthService] Token stored');
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Retrieve token from localStorage
|
||
|
|
* @returns {string|null}
|
||
|
|
*/
|
||
|
|
getToken() {
|
||
|
|
const token = localStorage.getItem(TOKEN_KEY);
|
||
|
|
console.log('[AuthService] getToken:', token ? '***exists***' : null);
|
||
|
|
return token;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Remove token from localStorage
|
||
|
|
*/
|
||
|
|
deleteToken() {
|
||
|
|
localStorage.removeItem(TOKEN_KEY);
|
||
|
|
console.log('[AuthService] Token deleted');
|
||
|
|
},
|
||
|
|
});
|
||
|
|
|
||
|
|
export default AuthService;
|