Files
barker/bookie/src/app/auth/login/login.component.ts
T
2024-12-17 08:57:52 +05:30

93 lines
2.8 KiB
TypeScript

import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatDividerModule } from '@angular/material/divider';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
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'],
imports: [
MatCardModule,
ReactiveFormsModule,
MatFormFieldModule,
MatInputModule,
MatIconModule,
MatDividerModule,
MatButtonModule,
],
})
export class LoginComponent implements OnInit, AfterViewInit {
@ViewChild('nameElement', { static: true }) nameElement?: ElementRef;
form: FormGroup<{
username: FormControl<string>;
password: FormControl<string>;
}>;
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({
next: () => {
this.router.navigateByUrl(this.returnUrl);
},
error: (error) => {
if (error.status === 401 && error.detail === 'Device is not registered') {
this.unregisteredDevice = true;
this.deviceName = this.cs.getCookie('device');
}
this.toaster.show('Error', error.detail);
},
});
}
}