Login using firestore collection

Viewed 21

I'm trying to create a function where I grab the info of my collection to login into my application

I can already get all the information using this service:

    getUsersLocal(): Observable<AdminUser[]> {
    const booksRef = collection(this.firestore, 'admin-roles');
    return collectionData(booksRef, { idField: 'id' }) as Observable<AdminUser[]>;
  }

now to the function part:

login(): void{
    if(this.loginForm?.valid){
      let adminLogin: Admin = this.loginForm.value;
      this.admin.getUsersLocal().subscribe({
        next: response => {
          if(this.email === adminEmail && this.password === adminPassword){
            this.route.navigate(['/admin']);
          }
        } else {
          window.alert("Usuário não encontrado")
        }
      })     
    }
  }

I know that it is wrong the construction, but I think it's somewhat around that.

1 Answers

Well i've managed to solve the problem. But it only works with accounts that passed through the authentication. The ones stored only on the database don't work. So I need to add them to the authentication also

login(email: string, password: string) {
    this.auth
      .signInWithEmailAndPassword(email, password)
      .then(
        (res: any) => {
          let user = res.user;
          this.db.collection("admin-roles").doc(user.uid).get().subscribe({
            next: userResponse => {
              user = userResponse.data();
              if(user.role == undefined){
                window.alert("Erro nos dados");
                this.router.navigate(["/login"]);
              }else if (user.role.includes('admin')) {
                this.router.navigate(['/admin'])
              }else{
                this.router.navigate(["/login"]);
              }
            }
          });
        },  
        (error: FirebaseError) => {
          throw error;
        }        
      )
      .catch((error) => {
        this.emitError(error.message);
      });
  }
Related