py-learn / src /app /auth /auth.component.ts
Oviya
fix
b366f52
raw
history blame
2.24 kB
import { Component } from '@angular/core';
import { AuthService } from './auth.service';
import { Router } from '@angular/router';
type GradeLevel = 'lowergrade' | 'midgrade' | 'highergrade';
@Component({
selector: 'app-auth',
templateUrl: './auth.component.html',
styleUrl: './auth.component.css'
})
export class AuthComponent {
username: string = '';
password: string = '';
errorMessage: string = '';
showPassword: boolean = false;
constructor(private authService: AuthService, private router: Router) { }
//ngOnInit(): void {
// this.authService.checkSession();
//}
// ✅ Handle Login
login(): void {
this.authService.login(this.username, this.password).subscribe(
(response) => {
// 1) Prefer grade coming from backend if it exists
let level = this.normalizeGrade(
(response?.gradeLevel ?? response?.grade ?? response?.role ?? '')
);
// 2) Otherwise derive it from the USERNAME exactly as you requested
if (!level) level = this.normalizeGrade(this.username);
// 3) Persist for ApiService -> sets X-User per request
if (!level) level = 'highergrade'; // final fallback (optional)
localStorage.setItem('gradeLevel', level);
// 4) Proceed as before
this.authService.setLoggedIn(true);
this.authService.startAutoRefresh();
const redirectUrl = localStorage.getItem('redirectAfterLogin') || '/home';
localStorage.removeItem('redirectAfterLogin');
this.router.navigate([redirectUrl]);
},
() => {
this.errorMessage = 'Invalid username or password';
}
);
}
private normalizeGrade(v: string): GradeLevel | '' {
const s = (v || '').trim().toLowerCase();
if (s === 'lowergrade' || s === 'lower' || s === 'low' || s === 'l') return 'lowergrade';
if (s === 'midgrade' || s === 'mid' || s === 'm') return 'midgrade';
if (s === 'highergrade' || s === 'higher' || s === 'high' || s === 'h') return 'highergrade';
return '';
}
// ✅ Check if user is logged in
isLoggedIn(): boolean {
return this.authService.isLoggedIn();
}
togglePasswordVisibility(): void {
this.showPassword = !this.showPassword;
}
}