【发布时间】:2021-07-31 05:06:56
【问题描述】:
我正在 Ionic 中创建一个使用 Firebase 对用户进行身份验证的应用程序。成功执行身份验证后,将其数据保存在 Firestore 中。用户 Firestore 上的集合中的一项是“activeUser: Boolean”,我可以在登录后通过“AngularFirestore”插件的可观察 (user$) 返回进行监控。
我创建了一个 canActivate 类型的 Guard 文件,以便在 Firestore 更改为“False”并且用户尝试导航到另一个页面时监控 Firestore 中的“activeUser”标志,它将被“注销”并通知其用户已被管理员停用。
我是 Ionic 的新手,我对 Guards 和 Observables 等一些主题有疑问。如果下面的代码是合理的或者有一些我们可以改进的地方,我希望你能帮助我。
另一个问题与 Observables 有关。我可以在应用程序需要时订阅 observable USER$ 吗?我应该注意性能吗?我在哪里可以取消订阅 ionic?
如果有人有使用 Guard 和 Firestore 的代码示例或一些教程链接,我将不胜感激。
感谢大家的帮助
authentication.Service.ts
/**
* Funcao que fica 'ouvindo' o estado da autenticado
* e obtem os dados armazenados no firestore referente
* ao usuario logado.
**/
this.user$ = this.afAuth.authState.pipe(
switchMap(user => {
if (user) {
return this.afStore.doc<IUser>(`users/${user.uid}`).valueChanges();
} else {
return of(null);
}
})
);
user-active.guard.ts
export class UserDisabledGuard implements CanActivate {
constructor(private authService: AuthenticationService, private router: Router) { }
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> {
return this.authService.user$.pipe(
filter(val => val !== null),
take(1),
map(response => {
if (response.activeUser) {
this.authService.logout();
Storage.remove({ key: TOKEN_KEY });
this.authService.isAuthenticated.next(false);
this.router.navigateByUrl('/login');
return false;
} else {
return true;
}
})
);
}
}
【问题讨论】:
标签: ionic-framework firebase-authentication angular-router-guards