import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { ToasterService } from '../../core/toaster.service'; import { CookieService } from '../../shared/cookie.service'; import { AuthService } from '../auth.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<{ username: FormControl; password: FormControl; }>; hide: boolean; unregisteredDevice: boolean; deviceName: string; private returnUrl: string; constructor( private route: ActivatedRoute, private auth: AuthService, private router: Router, private toaster: ToasterService, private cs: CookieService, ) { this.hide = true; this.unregisteredDevice = false; this.deviceName = ''; this.returnUrl = ''; // Create form this.form = new FormGroup({ username: new FormControl('', { validators: Validators.required, nonNullable: true }), password: new FormControl('', { validators: Validators.required, nonNullable: true }), }); } ngOnInit() { this.returnUrl = this.route.snapshot.queryParams['returnUrl'] ?? '/'; } ngAfterViewInit() { setTimeout(() => { if (this.nameElement !== undefined) { this.nameElement.nativeElement.focus(); } }, 0); } login(): void { const formModel = this.form.value; const username = formModel.username ?? ''; const password = formModel.password ?? ''; this.auth .login(username.trim(), password.trim()) // .pipe(first()) .subscribe( () => { this.router.navigateByUrl(this.returnUrl); }, (error) => { if (error.status === 401 && error.error.detail === 'Device is not registered') { this.unregisteredDevice = true; this.deviceName = this.cs.getCookie('device'); } this.toaster.show('Error', error.error.detail); }, ); } }