0

我正在尝试找到/创建一种正确(最佳)的方式来获取和使用 Angular 应用程序中的自定义声明。我通过云功能添加了管理员自定义声明。我现在想要的(以及我试图做的)现在是:

  1. 在一项服务中获取索赔(和登录用户)(例如auth.service
  2. 允许需要读取声明的所有其他组件通过该服务中的简单 API 执行此操作
  3. 不让其他组件订阅 authState 或其他任何内容(只需同步读取 my 的属性auth.service

我为什么要这个?- 因为我相信它更具可读性和更易于维护

authState(通过只在一个地方(例如)读取(订阅authService.ts),从而使维护更容易,并允许其他组件从authService.ts属性/字段同步读取声明)


所以,我现在正在做的代码(它不工作......见POINTS_IN_CODE):

auth.service.ts

    // imports omitted for brevity...
    
    @Injectable()
    export class AuthService {
    
      user: Observable<User> = of(null);
      uid: string;
      claims: any = {};
      claimsSubject = new BehaviorSubject(0);
    
      constructor(private afAuth: AngularFireAuth,
                  private afStore: AngularFirestore,
                  private functions: AngularFireFunctions) {
    
        this.afAuth.authState
          .subscribe(
            async authUser => {
              if (authUser) { // logged in
                console.log(`Auth Service says: ${authUser.displayName} is logged in.`);
                this.uid = authUser.uid;
                this.claims = (await authUser.getIdTokenResult()).claims;
                // POINT_IN_CODE_#1
                this.claimsSubject.next(1);

                const userDocumentRef = this.afStore.doc<User>(`users/${authUser.uid}`);
                // if provider is Google (or Facebook <later> (OR any other 3rd party))
                // document doesn't exist on the first login and needs to be created
                if (authUser.providerData[0].providerId === 'google.com') {
                  userDocumentRef.get()
                  .subscribe( async snapshot => {
                    if ( ! snapshot.exists) { // if the document does not exist
                      console.log(`\nNew document being created for: ${authUser.displayName}...`); // create a user document
                      await userDocumentRef.set({name: authUser.displayName, email: authUser.email, provider: 'google.com'});
                    }
                  });
                }
                this.user = userDocumentRef.valueChanges();
              }
              else { // logged out
                console.log('Auth Service says: no User is logged in.');
              }
            }
         );
    
      }
    
      login(email, password): Promise<any> {
        return this.afAuth.auth.signInWithEmailAndPassword(email, password);
      }

      hasClaim(claim): boolean {
        return this.hasAnyClaim([claim]);
      }
    
      hasAnyClaim(paramClaims): boolean {
        for (let paramClaim of paramClaims) {
          if (this.claims[paramClaim]) {
            return true;
          }
        }
        return false;
      }
      
    }

登录组件.ts

    // imports...
    
    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css']
    })
    export class LoginComponent implements OnInit {
    
      form: FormGroup;
      hide = true;
      errorMessage = '';
      loading = false;
    
      constructor(private fb: FormBuilder,
                  public authService: AuthService,
                  private router: Router) {}
    
      ngOnInit() {
        this.logout();
    
        this.form = this.fb.group({
          username: ['test@test.te', Validators.compose([Validators.required, Validators.email])],
          password: ['Asdqwe123', Validators.compose([Validators.required])]
        });
      }
    
      submit() {
        this.loading = true;
        this.authService.login(this.form.value.username, this.form.value.password)
          .then(resp => {
            this.loading = false;
            // POINT_IN_CODE_#2

            // what I am doing right now, and what doesn't work...
            this.authService.user
              .subscribe(
                resp => {
                  if (this.authService.hasClaim('admin')) {
                    this.router.navigate(['/admin']);
                  }
                  else {
                    this.router.navigate(['/items']);
                  }
                }
              );
    
            // POINT_IN_CODE_#3
            //this.authService.claimsSubject
            // .subscribe(
            //   num => {
            //     if (num === 1) {
            //       if (this.authService.hasClaim('admin')) {
            //         this.router.navigate(['/admin']);
            //       }
            //       else {
            //         this.router.navigate(['/items']);
            //       }
            //     }
            //   });
      }
    
      logout() {
        this.authService.logout();
      }
    }

POINTS_IN_CODE

auth.service.tsat POINT_IN_CODE_#1- 我有想法从这个主题发出claimsSubject并在login.component.tsatPOINT_IN_CODE_#3订阅它并知道,如果它的值为1,则声明auth.service.ts已从authState.

在我知道我可以从中得到索赔,login.component.ts但它只是“感觉”不正确......这就是这个问题的主要内容......POINT_IN_CODE_#2resp.getIdTokenResult

我可能要问的具体问题是:

admin如果他有“管理员”自定义声明,我希望能够在登录页面后重定向用户。

正如我上面所说的(如果可能并且如果它是好的/提高可读性/提高维护能力),我想这样做,而不是直接订阅authState,而是通过auth.service.ts.

例如,我会使用相同的“逻辑”来制作一个AuthGuard只会调用authService.hasClaim('admin')的,而不必订阅authState自己来进行检查。

注意 我想知道我做的方式是否好,是否有任何警告或只是简单的改进。欢迎所有建议和评论,所以请发表评论,尤其是我的为什么我想要这个?部分!

Edit-1: 添加了打字稿代码突出显示并指出了我的代码中不能按我想要的方式工作的确切位置。

编辑 2: 编辑了一些关于我的 authService.user 为空的原因的评论......(我运行了一些代码,在登录组件中检查之前将其设置为空......)

4

1 回答 1

0

好的,所以...我找到了一种方法。

首先,澄清一下我“觉得”订阅authState每个需要从中了解某些内容的组件(无论是用户的登录状态、用户文档还是声明)的想法是错误的:

维护(尤其是更改)每个组件中的代码将非常困难,因为我必须更新有关数据检索的任何逻辑。此外,每个组件都必须自己检查数据(例如检查声明是否包含'admin'),并且肯定只能在用户登录/注销时完成一次并传播给需要的人它。

在我提出的解决方案中,这正是我所做的。有关用户声明和登录状态的所有内容均由authService.

我设法通过使用RxJS Subjects做到了这一点。

我的服务、登录组件和导航栏组件的打字稿代码现在如下所示:

auth.service.ts

// imports...

@Injectable()
export class AuthService {

  uid: string = null;
  user: User = null;
  claims: any = {};
  isAdmin = false;

  isLoggedInSubject = new Subject<boolean>();
  userSubject = new Subject();
  claimsSubject = new Subject();
  isAdminSubject = new Subject<boolean>();

  constructor(private afAuth: AngularFireAuth,
              private afStore: AngularFirestore,
              private router: Router,
              private functions: AngularFireFunctions) {

    // the only subsription to authState
    this.afAuth.authState
      .subscribe(
        authUser => {

          if (authUser) { // logged in
            this.isLoggedInSubject.next(true);
            this.uid = authUser.uid;

            this.claims = authUser.getIdTokenResult()
              .then( idTokenResult => {
                this.claims = idTokenResult.claims;
                this.isAdmin = this.hasClaim('admin');
                this.isAdminSubject.next(this.isAdmin);
                this.claimsSubject.next(this.claims);
              });

            this.afStore.doc<User>(`users/${authUser.uid}`).get()
              .subscribe( (snapshot: DocumentSnapshot<User>)  => {
                this.user = snapshot.data();
                this.userSubject.next(this.user);
              });
          }
          else { // logged out
            console.log('Auth Service says: no User is logged in.');
          }
        }
     );
  }

  login(email, password): Promise<any> {
    return this.afAuth.auth.signInWithEmailAndPassword(email, password);
  }

  logout() {
    this.resetState();
    this.afAuth.auth.signOut();
    console.log('User just signed out.');
  }

  hasClaim(claim): boolean {
    return !!this.claims[claim];
  }

  resetState() {
    this.uid = null;
    this.claims = {};
    this.user = null;
    this.isAdmin = false;

    this.isLoggedInSubject.next(false);
    this.isAdminSubject.next(false);
    this.claimsSubject.next(this.claims);
    this.userSubject.next(this.user);
  }

}


登录组件.ts

// imports

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  providers = AuthProvider;
  form: FormGroup;

  hide = true;
  errorMessage = '';
  loading = false;

  constructor(private fb: FormBuilder,
              public authService: AuthService, // public - since we want to bind it to the HTML
              private router: Router,
              private afStore: AngularFirestore) {}

  ngOnInit() {
    this.form = this.fb.group({
      username: ['test@test.te', Validators.compose([Validators.required, Validators.email])],
      password: ['Asdqwe123', Validators.compose([Validators.required])]
    });
  }


  /**
   * Called after the user successfully logs in via Google. User is created in CloudFirestore with displayName, email etc.
   * @param user - The user received from the ngx-auth-firebase upon successful Google login.
   */
  loginWithGoogleSuccess(user) {
    console.log('\nprovidedLoginWithGoogle(user)');
    console.log(user);
    this.doClaimsNavigation();
  }

  loginWithGoogleError(err) {
    console.log('\nloginWithGoogleError');
    console.log(err);
  }

  submit() {
    this.loading = true;
    this.authService.login(this.form.value.username, this.form.value.password)
      .then(resp => {
        this.loading = false;
        this.doClaimsNavigation();
      })
      .catch(error => {
        this.loading = false;
        const errorCode = error.code;

        if (errorCode === 'auth/wrong-password') {
          this.errorMessage = 'Wrong password!';
        }
        else if (errorCode === 'auth/user-not-found') {
          this.errorMessage = 'User with given username does not exist!';
        } else {
          this.errorMessage = `Error: ${errorCode}.`;
        }

        this.form.reset({username: this.form.value.username, password: ''});
      });

  }


  /**
   * Subscribes to claimsSubject (BehaviorSubject) of authService and routes the app based on the current user's claims.
   *
   *
   * Ensures that the routing only happens AFTER the claims have been loaded to the authService's "claim" property/field.
   */
  doClaimsNavigation() {
    console.log('\nWaiting for claims navigation...')
    this.authService.isAdminSubject
      .pipe(take(1)) // completes the observable after 1 take ==> to not run this after user logs out... because the subject will be updated again
      .subscribe(
        isAdmin => {
          if (isAdmin) {
            this.router.navigate(['/admin']);
          }
          else {
            this.router.navigate(['/items']);
          }
        }
      )
  }

}


导航栏.component.ts

    // imports

    @Component({
      selector: 'app-nav-bar',
      templateUrl: './nav-bar.component.html',
      styleUrls: ['./nav-bar.component.css']
    })
    export class NavBarComponent implements OnInit {

      navColor = 'primary';
      isLoggedIn = false;
      userSubscription = null;
      isAdmin = false;
      user = null;

      loginClicked = false;
      logoutClicked = false;

      constructor(private authService: AuthService,
                  private router: Router) {

        this.authService.isLoggedInSubject
          .subscribe( isLoggedIn => {
            this.isLoggedIn = isLoggedIn;
          });

        this.authService.isAdminSubject
          .subscribe( isAdmin => {
            this.isAdmin = isAdmin;
          });

        this.authService.userSubject
          .subscribe( user => {
            this.user = user;
          });
         }

      ngOnInit() {}

    }

我希望它可以帮助那些分享我关于到处订阅的“坏感觉”的人authState

注意: 我会将其标记为已接受的答案,但请随时发表评论和提问。

于 2020-04-03T19:48:22.983 回答