Login refactor

This commit is contained in:
Michał Zieliński
2023-11-07 14:29:58 +01:00
parent 05f67ff9f3
commit db09a8c90f
6 changed files with 19 additions and 25 deletions

View File

@@ -1,9 +1,8 @@
import { Component } from '@angular/core'; import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router'; import { RouterOutlet } from '@angular/router';
import { SwUpdate, VersionEvent, VersionReadyEvent } from '@angular/service-worker'; import { SwUpdate, VersionEvent } from '@angular/service-worker';
import { environment } from 'src/environments/environment'; import { environment } from 'src/environments/environment';
import { NotificationsService } from './services/notifications.service'; import { NotificationsService } from './services/notifications.service';
import { filter } from 'rxjs';
@Component({ @Component({
selector: 'diunabi-root', selector: 'diunabi-root',

View File

@@ -13,7 +13,7 @@ export class AuthGuard {
private router$: Router, private router$: Router,
) {} ) {}
canActivate(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { canActivate(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (this.auth$.user && this.auth$.user.googleCredentials) { if (this.auth$.user && this.auth$.webCredentials) {
if (this.loginUrl) { if (this.loginUrl) {
this.router$.navigate([this.loginUrl]); this.router$.navigate([this.loginUrl]);
this.loginUrl = null; this.loginUrl = null;

View File

@@ -4,17 +4,17 @@ import moment, { Moment } from 'moment';
import { environment } from 'src/environments/environment'; import { environment } from 'src/environments/environment';
import { User } from '../models/user.model'; import { User } from '../models/user.model';
import { from, Observable } from 'rxjs'; import { from, Observable } from 'rxjs';
import jwt_decode from "jwt-decode";
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class AuthService { export class AuthService {
// eslint-disable-next-line @typescript-eslint/no-explicit-any webCredentials!: string;
public googleCredential!: any;
apiToken!: string; apiToken!: string;
user!: User; user!: User;
expirationTime!: Moment; apiTokenExpirationTime!: Moment;
constructor( constructor(
private http$: HttpClient, private http$: HttpClient,
@@ -34,16 +34,24 @@ export class AuthService {
); );
}); });
} }
retrieveUserFromCredentials(credentials: string) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const responsePayload: any = jwt_decode(credentials);
this.user = new User({
userName: `${responsePayload.given_name} ${responsePayload.family_name}`,
email: responsePayload.email,
avatar: responsePayload.picture
});
}
getAPIToken(): Promise<void> { getAPIToken(): Promise<void> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const header = new HttpHeaders().set('Content-type', 'application/json'); const header = new HttpHeaders().set('Content-type', 'application/json');
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
this.http$.post<any>(`${environment.api.url}/auth/apiToken`, JSON.stringify(this.googleCredential), { headers: header }).subscribe({ this.http$.post<any>(`${environment.api.url}/auth/apiToken`, JSON.stringify(this.webCredentials), { headers: header }).subscribe({
next: (data) => { next: (data) => {
this.user.id = data.id; this.user.id = data.id;
this.apiToken = data.token; this.apiToken = data.token;
this.expirationTime = moment(data.expirationTime); this.apiTokenExpirationTime = moment(data.expirationTime);
resolve(data); resolve(data);
}, },
error: (e: HttpErrorResponse) => { error: (e: HttpErrorResponse) => {
@@ -53,7 +61,6 @@ export class AuthService {
); );
}); });
} }
getAPITokenObservable(): Observable<void> { getAPITokenObservable(): Observable<void> {
return from(this.getAPIToken()); return from(this.getAPIToken());
} }

View File

@@ -20,7 +20,7 @@ export class AuthInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> { intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
if (!request.url.includes('/auth/apiToken')) { if (!request.url.includes('/auth/apiToken')) {
if (this.auth$.expirationTime.isBefore(moment.utc())) { if (this.auth$.apiTokenExpirationTime.isBefore(moment.utc())) {
return this.auth$.getAPITokenObservable().pipe( return this.auth$.getAPITokenObservable().pipe(
mergeMap(() => { mergeMap(() => {
return next.handle(request.clone({ return next.handle(request.clone({

View File

@@ -2,7 +2,6 @@ export class User {
id!: string; id!: string;
email!: string; email!: string;
userName!: string; userName!: string;
googleCredentials!: string;
avatar?: string; avatar?: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(input: any) { constructor(input: any) {

View File

@@ -1,8 +1,6 @@
import { Component, NgZone, OnInit } from '@angular/core'; import { Component, NgZone, OnInit } from '@angular/core';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import jwt_decode from "jwt-decode";
import { AuthService } from 'src/app/auth/auth.service'; import { AuthService } from 'src/app/auth/auth.service';
import { User } from 'src/app/models/user.model';
import { NotificationsService } from 'src/app/services/notifications.service'; import { NotificationsService } from 'src/app/services/notifications.service';
import { environment } from 'src/environments/environment'; import { environment } from 'src/environments/environment';
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
@@ -54,25 +52,16 @@ export class LoginViewComponent implements OnInit {
// @ts-ignore // @ts-ignore
google.accounts.id.prompt(); google.accounts.id.prompt();
}; };
} }
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
async handleCredentialResponse(response: any) { async handleCredentialResponse(response: any) {
try { try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any this.auth$.retrieveUserFromCredentials(response.credential);
const responsePayload: any = jwt_decode(response.credential); this.auth$.webCredentials = response.credential;
this.auth$.user = new User({
googleCredentials: response.credential,
userName: `${responsePayload.given_name} ${responsePayload.family_name}`,
email: responsePayload.email,
avatar: responsePayload.picture
});
this.ngZone$.run(() => { this.ngZone$.run(() => {
this.loading = true; this.loading = true;
}); });
this.auth$.googleCredential = response.credential;
await this.auth$.getAPIToken(); await this.auth$.getAPIToken();
this.ngZone$.run(() => { this.ngZone$.run(() => {
this.router$.navigate(['/app']); this.router$.navigate(['/app']);