diff options
author | Sonja Galovic <galovicsonja@gmail.com> | 2022-03-15 21:32:58 +0100 |
---|---|---|
committer | Sonja Galovic <galovicsonja@gmail.com> | 2022-03-15 21:32:58 +0100 |
commit | d6c8dc0a22cfe3cb0ed1579f5dc7c4c0e6d9b3de (patch) | |
tree | d5e8d368d08f2168e66438f486706af530b3b9c4 /frontend/src/app/_services | |
parent | ca592566e80a7a83fff85e0b5a11bcca06f7e017 (diff) | |
parent | f6496f86182902f2a6e5e34554ae93116d04c5b6 (diff) |
Merge branch 'dev' of http://gitlab.pmf.kg.ac.rs/igrannonica/neuronstellar into dev
# Conflicts:
# frontend/src/app/_pages/add-model/add-model.component.html
Diffstat (limited to 'frontend/src/app/_services')
-rw-r--r-- | frontend/src/app/_services/auth.service.ts | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/frontend/src/app/_services/auth.service.ts b/frontend/src/app/_services/auth.service.ts index c96c2dae..afc1567b 100644 --- a/frontend/src/app/_services/auth.service.ts +++ b/frontend/src/app/_services/auth.service.ts @@ -3,6 +3,7 @@ import { HttpClient, HttpHeaders } from '@angular/common/http'; import { JwtHelperService } from '@auth0/angular-jwt'; import { CookieService } from 'ngx-cookie-service'; import { API_SETTINGS } from 'src/config'; +import shared from '../Shared'; const jwtHelper = new JwtHelperService(); @@ -11,6 +12,8 @@ const jwtHelper = new JwtHelperService(); }) export class AuthService { + shared = shared; + constructor(private http: HttpClient, private cookie: CookieService) { } login(username: string, password: string) { @@ -28,4 +31,49 @@ export class AuthService { } return false; } + + lastToken?: string; + refresher: any; + + enableAutoRefresh() { + this.lastToken = this.cookie.get('token'); + let exp = jwtHelper.getTokenExpirationDate(this.lastToken); + if (!exp) { + exp = new Date(); + } + this.refresher = setTimeout(() => { + console.log('refreshing token!'); + this.http.post(`${API_SETTINGS.apiURL}/auth/renewJwt`, {}, { headers: this.authHeader(), responseType: 'text' }).subscribe((response) => { + this.authenticate(response); + }); + }, exp.getTime() - new Date().getTime()); + } + + authenticate(token: string) { + let exp = jwtHelper.getTokenExpirationDate(token); + if (!exp) { + exp = new Date(); + } + this.cookie.set('token', token, exp); + this.updateUser(); + } + + updateUser() { + if (this.cookie.check('token')) { + const token = this.cookie.get('token'); + this.shared.loggedIn = this.isAuthenticated(); + this.enableAutoRefresh(); + } + } + + logOut() { + this.cookie.delete('token'); + if (this.refresher) + clearTimeout(this.refresher); + this.shared.loggedIn = false; + } + + authHeader() { + return new HttpHeaders().set("Authorization", "Bearer " + this.cookie.get('token')); + } } |