feat(Login): add example jwt token

This commit is contained in:
2026-02-14 17:49:49 -05:00
parent c593dd0273
commit 173ddfd05f
6 changed files with 160 additions and 34 deletions

49
src/services/auth.js Normal file
View File

@@ -0,0 +1,49 @@
class AuthService {
static TOKEN_KEY = 'access_token';
static REFRESH_KEY = 'refresh_token';
static login(credentials) {
const url = `${import.meta.env.VITE_DJANGO_BASE_URL}/api/token/`;
return fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(credentials),
})
.then(r => r.json())
.then(data => {
localStorage.setItem(this.TOKEN_KEY, data.access);
localStorage.setItem(this.REFRESH_KEY, data.refresh);
return data;
});
}
static getAccessToken() {
return localStorage.getItem(this.TOKEN_KEY);
}
static getRefreshToken() {
return localStorage.getItem(this.REFRESH_KEY);
}
static async refresh() {
const refresh = this.getRefreshToken();
if (!refresh) throw new Error('No refresh token');
const url = `${import.meta.env.VITE_DJANGO_BASE_URL}/api/token/refresh/`;
const resp = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh }),
});
const data = await resp.json();
localStorage.setItem(this.TOKEN_KEY, data.access);
return data.access;
}
static logout() {
localStorage.removeItem(this.TOKEN_KEY);
localStorage.removeItem(this.REFRESH_KEY);
}
}
export default AuthService;