Fix AuthService

This commit is contained in:
Itay Mizeretz 2018-02-22 15:22:35 +02:00
parent df95cc73c5
commit 52d75de864
1 changed files with 21 additions and 5 deletions

View File

@ -7,7 +7,7 @@ export default class AuthService {
if (this.AUTH_ENABLED) { if (this.AUTH_ENABLED) {
return this._login(username, password); return this._login(username, password);
} else { } else {
return {}; return {result: true};
} }
}; };
@ -28,7 +28,14 @@ export default class AuthService {
}) })
}).then(response => response.json()) }).then(response => response.json())
.then(res => { .then(res => {
this._setToken(res['access_token']); if (res.hasOwnProperty('access_token')) {
this._setToken(res['access_token']);
return {result: true};
} else {
this._removeToken();
return {result: false};
}
}) })
}; };
@ -45,21 +52,26 @@ export default class AuthService {
return fetch(url, { return fetch(url, {
headers, headers,
...options ...options
}).then(res => {
if (res.status === 401) {
this._removeToken();
}
return res;
}); });
}; };
loggedIn() { loggedIn() {
if (!this.AUTH_ENABLED) { if (!this.AUTH_ENABLED) {
return true; return true;
} }
const token = this._getToken(); const token = this._getToken();
return (token && !this._isTokenExpired(token)); return ((token !== null) && !this._isTokenExpired(token));
} }
logout() { logout() {
if (this.AUTH_ENABLED) { if (this.AUTH_ENABLED) {
localStorage.removeItem('jwt'); this._removeToken();
} }
} }
@ -76,6 +88,10 @@ export default class AuthService {
localStorage.setItem('jwt', idToken); localStorage.setItem('jwt', idToken);
} }
_removeToken() {
localStorage.removeItem('jwt');
}
_getToken() { _getToken() {
return localStorage.getItem('jwt') return localStorage.getItem('jwt')
} }