【问题标题】:Authentication + Ionic + Firestore + Guard (canActivate) - Access Permission身份验证 + Ionic + Firestore + Guard (canActivate) - 访问权限
【发布时间】: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


    【解决方案1】:

    我使用 Angular,但我认为它是相似的。 您在服务和守卫中所做的方式都可以。 但是我不会在你的保护管道函数中做这么多的操作。 因为其中一些看起来与原始可观察对象无关。

    Firebase 身份验证提供了 authstate 方法供我们检查状态。 我所做的是检查用户的 id 是否未定义

    this.afAuth.authState.pipe(
          map((data) => {
            return data?.uid
          })
        ) 
    
    afAuth : AngularFireAuth
    

    在 guard.ts 中,我返回一个 Observable 对象。 这样路由守卫可以检查和重定向。 这就是我所做的, https://medium.com/p/angular-route-setting-login-and-route-guard-canactivate-fab53eb1715a

    【讨论】:

      猜你喜欢
      • 2019-06-17
      • 2019-06-28
      • 2019-01-21
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      • 2021-03-10
      • 2013-06-18
      • 1970-01-01
      相关资源
      最近更新 更多