【发布时间】:2017-07-24 05:09:39
【问题描述】:
我一直在兜圈子,试图弄清楚这一点。我需要根据用户角色保护路由。
constructor(private af: AngularFire, private db: AngularFireDatabase, private router: Router, private auth: AngularFireAuth) {
af.auth.subscribe(user => {
if (user) {
this.getUserRole(user);
} else {
console.log('no user');
}
});
}
这至少得到了角色:
getUserRole(user): any {
this.db.list('users', {
query: {
orderByKey: true,
equalTo: user.uid
}
}).subscribe(user => console.log(user[0].role));
}
这是一个基于用户是否登录的有效 CanActivate,但显然角色无关紧要。
canActivate(route:ActivatedRouteSnapshot,
state:RouterStateSnapshot):Observable<boolean> {
return this.af.auth.take(1)
.map(authSate => !!authSate)
.do( authenticated => {
console.log(authenticated)
if (!authenticated)
this.router.navigate(['/login'])
})
}
我不知道如何考虑用户角色。我的设置非常基本......它的/users/$uid/role。
这是我尝试过的其他方法:
导出类 AuthService {
static UNKNOWN_USER = new AuthInfo(null, null);
authInfo$: BehaviorSubject<AuthInfo> = new BehaviorSubject<AuthInfo>(AuthService.UNKNOWN_USER);
constructor(private af: AngularFire, private db: AngularFireDatabase, private router: Router, private auth: AngularFireAuth) {
af.auth.subscribe(user => {
if (user) {
let getRole = this.db.list('users', {
query: {
orderByKey: true,
equalTo: user.uid
}
}).subscribe(snap => {
if (snap.length === 0) {
return;
} else {
let role = "";
role = snap[0].role
const authInfo = new AuthInfo(user.uid, role);
this.authInfo$.next(authInfo);
}
});
} else {
console.log('no user');
}
});
}
这里是 AuthInfo 类:
导出类 AuthInfo {
constructor(public $uid: string, public role: string) { }
isLoggedIn() {
console.log('from authinfo', !!this.$uid)
//tells us if user is logged in or not
return !!this.$uid;
}
isGroupALoggedIn() {
//tells us if user is logged in or not
return !!this.$uid && this.role === "GroupA";
}
isGroupBLoggedIn() {
//tells us if user is logged in or not
return !!this.$uid && this.role === "GroupB";
}
}
这是来自 Home 组件的测试:
导出类 HomeComponent 实现 OnInit {
authInfo: AuthInfo
constructor(private authService: AuthService) { }
ngOnInit() {
//returns boolean
this.authService.authInfo$.subscribe(authInfo => {
console.log(authInfo);
this.authInfo = authInfo
});
}
}
这也可以,但我不知道如何将它与 CanActivate 联系起来
【问题讨论】:
标签: angular firebase firebase-authentication rxjs