Refreshing token implemented in LoginGuard (#1246)

This commit is contained in:
piotrpekala7 2022-02-08 14:06:20 +01:00 committed by GitHub
parent 60a9e45e4a
commit 108f95de59
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 36 additions and 3 deletions

View File

@ -72,6 +72,8 @@ export class LoginComponent implements OnInit {
this.loginService.login(this.server, username, password).subscribe(async (response: AuthResponse) => {
let server = this.server;
server.authToken = response.access_token;
server.username = username;
server.password = password;
await this.serverService.update(server);
if (this.returnUrl.length <= 1) {

View File

@ -1,17 +1,37 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { Server } from 'app/models/server';
import { LoginService } from '@services/login.service';
import { Server } from '../models/server';
import { ServerService } from '../services/server.service';
@Injectable()
export class LoginGuard implements CanActivate {
constructor(
private serverService: ServerService,
private loginService: LoginService,
private router: Router
) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
async canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const server_id = next.paramMap.get('server_id');
let server = await this.serverService.get(parseInt(server_id, 10));
try {
await this.loginService.getLoggedUser(server).toPromise();
} catch (e) {
if (e.status === 401) {
server.tokenExpired = true;
await this.serverService.update(server)
try {
let response = await this.loginService.login(server, server.username, server.password).toPromise();
server.authToken = response.access_token;
server.tokenExpired = false;
await this.serverService.update(server)
} catch (e) {
throw e;
}
}
}
return this.serverService.get(parseInt(server_id, 10)).then((server: Server) => {
if (server.authToken) return true;
this.router.navigate(['/server', server.id, 'login'], { queryParams: { returnUrl: state.url }});

View File

@ -13,4 +13,7 @@ export class Server {
ubridge_path: string;
status: ServerStatus;
protocol: ServerProtocol;
username: string;
password: string;
tokenExpired: boolean;
}

View File

@ -88,6 +88,10 @@ export class ServerErrorHandler {
err = ServerError.fromError('Server is unreachable', error);
}
if (error.status === 401) {
window.location.reload();
}
return throwError(err);
}
}
@ -223,7 +227,7 @@ export class HttpServer {
options.headers = {};
}
if (server.authToken) {
if (server.authToken && !server.tokenExpired) {
options.headers['Authorization'] = `Bearer ${server.authToken}`;
}

View File

@ -20,4 +20,8 @@ export class LoginService {
return this.httpServer.post<AuthResponse>(server, '/users/login', payload, options);
}
getLoggedUser(server: Server) {
return this.httpServer.get(server, "/users/me");
}
}