簡體   English   中英

身份驗證 + Ionic + Firestore + Guard (canActivate) - 訪問權限

[英]Authentication + Ionic + Firestore + Guard (canActivate) - Access Permission

我正在 Ionic 中創建一個應用程序,它使用 Firebase 對用戶進行身份驗證。 成功執行身份驗證后,將其數據保存在 Firestore 中。 用戶 Firestore 上的集合中的一項是“activeUser: Boolean”,我可以在登錄后通過“AngularFirestore”插件的可觀察 (user$) 返回來監控它。

我創建了一個 canActivate 類型的 Guard 文件,以便在 Firestore 更改為“False”並且用戶嘗試導航到另一個頁面時從 Firestore 監視“activeUser”標志,它將被“注銷”並通知其用戶已已被管理員停用。

我是 Ionic 的新手,我對 Guards 和 Observables 等一些主題有疑問。 如果下面的代碼是合理的或者有一些我們可以改進的地方,我希望你能幫助我。

另一個問題與 Observables 有關。 我可以在應用程序需要時訂閱 observable USER$ 嗎? 我應該注意性能嗎? 我在哪里取消訂閱 ionic?

如果有人有使用 Guard 和 Firestore 的代碼示例或一些教程鏈接,我將不勝感激。

感謝大家的幫助

身份驗證.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;
        }
      })
    );
  }
}

我用的是Angular,但我覺得差不多。 你在服務和守衛中所做的方式都很好。 但是我不會在你的后衛 pipe function 中做這么多的操作。 因為其中一些看起來與原始可觀察的 object 無關。

Firebase 身份驗證為我們提供了 authstate 方法來檢查 state。 我所做的是檢查用戶的 id 是否未定義

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

afAuth:AngularFireAuth

在guard.ts 中,我返回一個 Observable<boolean | 網址樹> object。 這樣路由守衛就可以檢查和重定向。 這就是我所做的, https://medium.com/p/angular-route-setting-login-and-route-guard-canactivate-fab53eb1715a

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM