Files
DiunaBI/Frontend/src/app/views/login/login-view.component.ts
2023-11-07 21:32:27 +01:00

101 lines
3.0 KiB
TypeScript

import { Component, NgZone, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from 'src/app/auth/auth.service';
import { NotificationsService } from 'src/app/services/notifications.service';
import { environment } from 'src/environments/environment';
import { MatCardModule } from '@angular/material/card';
import { NgIf } from '@angular/common';
import { MatBottomSheetModule } from '@angular/material/bottom-sheet';
@Component({
selector: 'diunabi-view-page',
templateUrl: './login-view.component.html',
styleUrls: ['./login-view.component.scss'],
standalone: true,
imports: [NgIf, MatCardModule, MatBottomSheetModule]
})
export class LoginViewComponent implements OnInit {
constructor(
private router$: Router,
private auth$: AuthService,
private ngZone$: NgZone,
private notifications$: NotificationsService
) { }
loading = false;
ngOnInit(): void {
this.auth$.isGoogleLibLoaded.subscribe((isLoaded) => {
if (isLoaded) {
this.initGoogleLogin();
}
});
}
initGoogleLogin() {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
google.accounts.id.initialize({
client_id: environment.google.clientId,
callback: this.handleCredentialResponse.bind(this),
auto_select: true,
cancel_on_tap_outside: true
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
google.accounts.id.renderButton(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
document.getElementById("google-button"),
{ theme: "outline", size: "large", width: "100%" }
);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
google.accounts.id.prompt();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async handleCredentialResponse(response: any) {
try {
this.auth$.retrieveUserFromCredentials(response.credential);
this.auth$.webCredentials = response.credential;
this.ngZone$.run(() => {
this.loading = true;
});
await this.auth$.getAPIToken();
this.ngZone$.run(() => {
this.router$.navigate(['/app']);
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
console.error('handleCredentialResponse', e);
this.ngZone$.run(() => {
this.loading = false;
});
if (e.status === 401) {
this.ngZone$.run(() => {
this.notifications$.add({
text: "User not exists in DiunaBI database.",
btn: "OK",
duration: 15000
});
});
} else {
this.ngZone$.run(() => {
this.notifications$.add({
text: "DiunaBI server not responded.",
btn: "OK",
duration: 15000
});
});
}
} finally {
this.loading = false;
}
}
}