diff options
author | Danijel Andjelkovic <adanijel99@gmail.com> | 2022-03-15 16:06:39 +0100 |
---|---|---|
committer | Danijel Andjelkovic <adanijel99@gmail.com> | 2022-03-15 16:06:39 +0100 |
commit | 6938b1f8fd0a8d27b9fdcc5bc114ffabcd4bac68 (patch) | |
tree | 0725c5ffedd201603b574294be6218b754cdd898 /frontend/src/app/_services | |
parent | 4791e1ba6d4c3c737e675f54a947251c3d42163d (diff) | |
parent | a9287af015228a73b5053acdef421d9d63ba766b (diff) |
Merge branch 'frontendNaslovna' of http://gitlab.pmf.kg.ac.rs/igrannonica/neuronstellar into dev
Diffstat (limited to 'frontend/src/app/_services')
-rw-r--r-- | frontend/src/app/_services/auth.service.ts | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/frontend/src/app/_services/auth.service.ts b/frontend/src/app/_services/auth.service.ts index c96c2dae..e6611880 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,47 @@ 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(); + } + console.log(exp, exp?.getTime()); + 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) { + const user = jwtHelper.decodeToken(token); + this.cookie.set('token', token, user.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')); + } } |