I have a project with ASP.NET Core as backend and Angular-13 as frontend.
I have this reponse on POSTMAN when user successfully logs in:
{
"status_code": 200,
"message": "Successfully Logged In",
"result": {
"token": "gggggffffffffffffdddddddddddd",
"user": {
"id": 3,
"user_name": "smith",
"last_login": "2022-01-03T12:35:26.0305649"
},
"roles": [
"Teacher"
],
}
}
This is the Angular code:
user.ts:
export interface IResponse<T> {
message: string;
error: boolean;
code: number;
results: T;
}
export interface IUser {
userName?: string;
lastLogin?: Date;
token?: string;
roles?: string[];
expires?: Date;
}
auth.service.ts:
export class AuthService {
baseUrl = environment.apiUrl;
private currentUserSource = new ReplaySubject<IUser>(1);
currentUser$ = this.currentUserSource.asObservable();
constructor(private http: HttpClient, private router: Router) { }
login(model: any){
return this.http.post(this.baseUrl 'auth/login', model).pipe(
map((res: IUser)=>{
const user = res;
if(user){
this.setCurrentUser(user);
}
})
)
}
setCurrentUser(user: IUser){
if(user){
user.roles = [];
const roles = this.getDecodedToken(user.token).role;//copy token to jwt.io see .role
Array.isArray(roles) ? user.roles = roles : user.roles.push(roles);
localStorage.setItem('user', JSON.stringify(user));
this.currentUserSource.next(user);
}
}
getDecodedToken(token: string) {
return JSON.parse(atob(token.split('.')[1]));
}
}
On Angular frontend, I have two dashboards: teacher-dashboard and student-dashboard
auth.component:
createForm() {
this.loginForm = new FormGroup({
UserName: new FormControl('', Validators.required),
Password: new FormControl('', [Validators.required, Validators.minLength(6), Validators.maxLength(80)])
})
}
login(){
this.authService.login(this.loginForm.value).subscribe(res=>{
this.router.navigateByUrl('/');
}, error=>{
this.toastr.error(error.error);
})
}
If user successfully logs in. If the user's role is Teacher it should redirect to teacher-dashboard and if the role is student, it should redirect to student-dashboard.
How do I achieve this?
Thanks
CodePudding user response:
First, you might want to use guards
ng g guard isTeacher
ng g guard isStudent
For each guard, inject a service then return true false based on logic.
If you use component on routing, use canActivate.
If you use loadChildren, use canLoad.
{
path: '/teacher',
canLoad: [isTeacher],
loadChildren: () => import('teacher.module').then(m => m.somethingmodule),
}
{
path: '/teacher',
canActivate: [isTeacher],
component: teacherComp,
}
Same goes for students.
Why use guards? So if you are a student, you can not navigate by mistake or view teacher components. It still can be bypassed since it's all frontend but still.
