aboutsummaryrefslogtreecommitdiff
path: root/frontend/src/app/_services
diff options
context:
space:
mode:
Diffstat (limited to 'frontend/src/app/_services')
-rw-r--r--frontend/src/app/_services/auth.service.ts46
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'));
+ }
}