#28 fix(login): handle bad credentials.
This commit is contained in:
@@ -2,19 +2,34 @@ class AuthService {
|
||||
static TOKEN_KEY = 'access_token';
|
||||
static REFRESH_KEY = 'refresh_token';
|
||||
|
||||
static login(credentials) {
|
||||
static async login(credentials) {
|
||||
const url = `${import.meta.env.VITE_DJANGO_BASE_URL}/api/token/`;
|
||||
return fetch(url, {
|
||||
|
||||
const resp = await 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;
|
||||
});
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
let errMsg = resp.statusText;
|
||||
try {
|
||||
const errData = await resp.json();
|
||||
errMsg = errData?.detail ?? errData?.message ?? errMsg;
|
||||
} catch (_) {
|
||||
|
||||
}
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
|
||||
const data = await resp.json();
|
||||
|
||||
if (data.access && data.refresh) {
|
||||
localStorage.setItem(this.TOKEN_KEY, data.access);
|
||||
localStorage.setItem(this.REFRESH_KEY, data.refresh);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
static getAccessToken() {
|
||||
@@ -35,6 +50,12 @@ class AuthService {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refresh }),
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
const errData = await resp.json().catch(() => ({}));
|
||||
throw new Error(errData?.detail ?? resp.statusText);
|
||||
}
|
||||
|
||||
const data = await resp.json();
|
||||
localStorage.setItem(this.TOKEN_KEY, data.access);
|
||||
return data.access;
|
||||
|
||||
Reference in New Issue
Block a user