【发布时间】:2018-04-02 17:56:43
【问题描述】:
我设置了我的 AuthGuard,以防止未登录的用户或没有所需角色/权限的用户访问页面。
在大多数情况下,它工作得很好。只有一个小问题,在页面刷新时,用户被重定向到登录页面,这是主页。
我发现用户在刷新时未通过身份验证的问题。我已经设置了一些逻辑来检查用户是否是正确的角色或存在,如果是,检查用户权限,否则返回注册页面。
我唯一的问题是....我不确定如何在页面刷新之前获得相同的 url/路由。
这是我目前的设置:
export class AuthGuard implements CanActivate {
userPermissions;
returnUrl: string;
constructor(private authService: AuthService, private router: Router, private userService: AuthenticationService,
private rout: ActivatedRoute) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.authService.isAuthenticated()
.then((authenticated: boolean) => {
if (authenticated) {
return true;
} else {
// this.router.navigate(['/']);
const user = localStorage.getItem('username');
console.log(user);
this.userService.getUserPermissions(user).subscribe(data => {
this.userPermissions = data;
this.checkUserPermissions();
}, (err) => {
this.router.navigate(['/']);
});
}
});
}
checkUserPermissions() {
if (this.userPermissions._userPermissions._userPrivilegeKey === 100) {
localStorage.setItem('userRole', 'Sales');
// get return url from route parameters or default to '/'
this.returnUrl = this.rout.snapshot.queryParams['returnUrl'] || '/';
this.router.navigate([this.returnUrl]);
return true;
} else if (this.userPermissions._userPermissions._userPrivilegeKey === 400) {
localStorage.setItem('userRole', 'Admin');
this.returnUrl = this.rout.snapshot.queryParams['returnUrl'] || '/';
this.router.navigate([this.returnUrl]);
return true;
}
}
}
我研究过从 ActivatedRoute 设置一个快照,它将在页面刷新之前获取 returnUrl/Url,但我不确定应该在哪里设置它?
我是在主要组件 ngOnIt() 中初始化设置还是...?
【问题讨论】:
标签: angular typescript