brewman/overlord/src/app/auth/login/login.component.ts

72 lines
2.0 KiB
TypeScript

import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {AuthService} from '../auth.service';
import {ActivatedRoute, Router} from '@angular/router';
import {ToasterService} from '../../core/toaster.service';
import {FormBuilder, FormGroup} from '@angular/forms';
import {CookieService} from '../../shared/cookie.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit, AfterViewInit {
@ViewChild('nameElement', { static: true }) nameElement: ElementRef;
form: FormGroup;
hide: boolean;
showOtp: boolean;
clientId: string;
private returnUrl: string;
constructor(private route: ActivatedRoute,
private auth: AuthService,
private router: Router,
private toaster: ToasterService,
private cs: CookieService,
private fb: FormBuilder
) {
this.hide = true;
this.showOtp = false;
this.createForm();
}
createForm() {
this.form = this.fb.group({
username: '',
password: '',
otp: ''
});
}
ngOnInit() {
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}
ngAfterViewInit() {
setTimeout(() => {
this.nameElement.nativeElement.focus();
}, 0);
}
login(): void {
const formModel = this.form.value;
const username = formModel.username;
const password = formModel.password;
const otp = formModel.otp;
this.auth.login(username, password, otp)
// .pipe(first())
.subscribe(
data => {
this.router.navigate([this.returnUrl]);
},
(error) => {
if (error.status === 401 && 'Client is not registered' === error.error.detail) {
this.showOtp = true;
this.clientId = this.cs.getCookie('client_id');
}
this.toaster.show('Danger', error.error.details);
}
)
}
}