【发布时间】:2022-01-10 18:54:15
【问题描述】:
在 Angular-13 项目中,我拥有三个角色:管理员、教师和学生。用户只能拥有一个角色。
我的用户模型的响应如下所示:
user.ts:
export interface IResponse<T> {
message: string;
code: number;
results: T;
}
export interface IUser {
token?: string;
roles?: string[];
}
授权服务:
export class AuthService {
baseUrl = environment.apiUrl;
constructor(private http: HttpClient, private router: Router) { }
login(model: any){
return this.http.post<IResponse<IUser>>(this.baseUrl+'auth/login', model).pipe(
tap((response)=>{
const user = response.results;
return user;
})
)
}
getToken(): string | null {
return localStorage.getItem('token');
}
isLoggedIn() string | null {
return this.getToken();
}
}
当用户登录时,令牌和角色存储在localStorage中。此外,用户还会根据角色重定向到仪表板。
login.component:
login(){
this.authService.login(this.loginForm.value).subscribe({
next: (res: any) => {
if (res.result.roles[0] == 'Admin'){
this .router.vavigateByUrl('/admin-dashboard');
} else if (res.result.roles[0] == 'Teacher'){
this .router.vavigateByUrl('/teacher-dashboard');
}else {
this .router.vavigateByUrl('student-dashboard');
}
localStorage.setItem('token', JSON.stringify(res.result.token));
localStorage.setItem('role', JSON.stringify(res.result.role[0]));
}
})
}
auth.guards:
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private toastr: ToastrService, private router: Router) { }
canActivate(route: ActivateRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
if (!this.authService.isLoggedIn()) {
this.toastr.info('Please Log In');
this.router.navigate(['/login']);
return false;
}
this.authService.isLoggedIn()
return true
}
}
app-routing.module:
const routes: Routes = [
{path: '', redirectTo: 'login', pathMatch: 'full'},
{path: 'teacher-dashboard', canActivate: [AuthGuard], loadChildren: () => import('./feature/teacher/teacher.module').then(m => m.TeacherModule)},
{path: 'login', loadChildren: () => import('./feature/login/login.module').then(m => m.AuthModule)},
{path: 'student-dashboard', canActivate: [AuthGuard], loadChildren: () => import('./feature/student/student.module').then(m => m.StudentModule)},
{path: 'admin-dashboard', canActivate: [AuthGuard], loadChildren: () => import('./feature/admin/admin.module').then(m => m.AdminModule)},
];
如上所示,我已经使用 AuthGuard 保护了路由。我如何仍然使用 Role 保护路由,以便学生不会进入教师仪表板、管理员仪表板,反之亦然?
谢谢
【问题讨论】: