AltitudeWeb/frontend/src/app/shared-components/login/login.component.ts

88 lines
2.5 KiB
TypeScript

import {Component} from '@angular/core';
import {MatDialogActions, MatDialogContent, MatDialogRef, MatDialogTitle} from '@angular/material/dialog';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {MatButtonModule} from '@angular/material/button';
import {MatInputModule} from '@angular/material/input';
import {MatFormFieldModule} from '@angular/material/form-field';
import {NgIf} from '@angular/common';
import {MatSnackBar} from '@angular/material/snack-bar';
import {AuthService} from '@services/auth.service';
@Component({
selector: 'app-login',
standalone: true,
imports: [
ReactiveFormsModule,
MatButtonModule,
MatInputModule,
MatFormFieldModule,
MatDialogTitle,
MatDialogContent,
MatDialogActions,
NgIf
],
templateUrl: './login.component.html',
styleUrl: './login.component.scss'
})
export class LoginDialogComponent {
public loginForm: FormGroup;
constructor(
public dialogRef: MatDialogRef<LoginDialogComponent>,
private fb: FormBuilder,
private authService: AuthService,
private snackBar: MatSnackBar
) {
this.loginForm = this.fb.group({
code: ['', [
Validators.required,
Validators.minLength(8),
Validators.maxLength(8),
Validators.pattern('^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]+$')
]]
});
}
onCancel(): void {
this.dialogRef.close();
}
onSubmit(): void {
if (!this.loginForm.valid) {
this.snackBar.open('Invalid code', '', {duration: 2000});
return;
}
this.snackBar.open('Logging in...', '', {duration: 2000});
this.authService.login(this.loginForm.value.code).subscribe({
next: (jwt) => {
this.dialogRef.close(jwt);
},
error: () => {
this.loginForm.get('code')?.setErrors({
invalid: true
});
}
});
}
onKeyDown(event: KeyboardEvent): void {
if (event.key.length === 1 && event.key >= 'a' && event.key <= 'z') {
event.preventDefault();
const input = event.target as HTMLInputElement;
const start = input.selectionStart || 0;
const end = input.selectionEnd || 0;
const value = this.loginForm.get('code')?.value || '';
const newValue =
value.substring(0, start) +
event.key.toUpperCase() +
value.substring(end);
this.loginForm.get('code')?.setValue(newValue);
setTimeout(() => {
input.setSelectionRange(start + 1, start + 1);
});
}
}
}