Access the system by authenticating with the Firestore database collection

My goal is to develop a function that retrieves information from my collection in order to log into my application.

With the help of this service, I am able to fetch all the necessary data:

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

Now moving on to the implementation of the function:

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 understand that there may be some errors in the structure, but I believe it's close to being correct.

Answer №1

After successfully resolving the issue, I discovered that the solution only applies to accounts that have gone through authentication. Accounts solely stored in the database do not function properly. To address this, I must also include them in the authentication process.

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("Error in data");
                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);
      });
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

angular-universal | firestore-admin | code: 'app/invalid-authentication' | connection timeout

import * as admin from 'firebase-admin'; var serviceAccount = require('./keys/keyfile.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "https://test.firebaseio.com" }); var registrationT ...

Using Rxjs to handle several requests with various headers

I have a specific requirement where, if hasProcessado == true, 10 additional requests should be made before issuing the final request. If the final request fails, 3 more attempts are needed. Furthermore, when sending the last request, it is essential to n ...

HttpErrorResponse: unexpected internal server error

Just getting started with Angular 6. I created a post service using Spring Boot, and it works perfectly when tested with Postman. But testing it in a web browser results in the following error: HttpErrorResponse {headers: HttpHeaders, status: 500, statusT ...

Can projects be published on npm and installed from a specific directory?

Currently working on an Angular library project, I am exploring the possibility of publishing the entire library alongside a pre-built angular application either on gitlab or npm. However, my concern lies in ensuring that when a user installs the library v ...

What is the best way to transition a connected component from a class-based to a functional component in TypeScript?

I'm in the process of switching from a class-based component to a functional component. This is a connected component that uses mapState. Here is my initial setup: import { connect } from 'react-redux' import { fetchArticles } from '. ...

What purpose does @ViewChild serve if we are unable to modify or interact with its properties from the Parent Component?

I have two main components - home and about. Within both of these, I am including a third component called hearts. Currently, I am manipulating the value of the 'age' property in the hearts component (initially set to '23') using @ViewC ...

Upgrade Angular 8 by substituting interconnected filter and order pipelines with custom functions

According to the Angular documentation Filtering and sorting operations can be resource-intensive. When Angular invokes these pipe methods frequently, it can lead to a degraded user experience, especially with even moderately-sized lists. Misuse of filt ...

How do I modify a response within a subscribe in Angular?

Having a scenario where multiple components are utilizing a function that expects an array of objects to be returned. However, there is one specific case where I need to modify the array based on the return value from an observable before returning it: let ...

Is there a way to verify the presence of multiple array indices in React with TypeScript?

const checkInstruction = (index) => { if(inputData.info[index].instruction){ return ( <Text ref={instructionContainerRef} dangerouslySetInnerHTML={{ __html: replaceTextLinks(inputData.info[index].instruction) ...

Switching from lite-server to my own express server.js file for Angular 2: Step-by-step guide

Recently, I decided to take on the challenge of migrating my existing Angular 1.x project to Angular 2. While I wanted to switch to TypeScript and Angular 2 for the client side, I preferred to keep my existing server code intact. However, I encountered an ...

Tips for setting up a system where PHP serves as the backend and Angular acts as the

I am working on a project that utilizes Angular as the front end and PHP as the back end. Both are installed in separate domains, with the PHP project fully completed and operational. I have created an API in PHP which I plan to call from Angular. My ques ...

A Typescript type that verifies whether a provided key, when used in an object, resolves to an array

I have a theoretical question regarding creating an input type that checks if a specific enum key, when passed as a key to an object, resolves to an array. Allow me to illustrate this with an example: enum FormKeys { x = "x", y = "y&q ...

A guide on applying color from an API response to the border-color property in an Angular application

When I fetch categoryColor from the API Response, I set border-left: 3px solid {{element.categoryColor}} in inline style. Everything is functioning correctly with no development issues; however, in Visual Studio, the file name appears red as shown in the i ...

Utilize the datasource.filter method within an *ngFor loop

I have a table that filters based on certain search criteria, which I implemented using the example found at: https://material.angular.io/components/table/examples Now, I am wondering if it is possible to apply this filtering functionality to an *ngFor lo ...

Default Angular2 route component for the RC5 program

My PHP website already in place, and I started integrating Angular2 components into it. I've implemented a router script to handle loading different components based on the URL. However, upon navigating away from a component page, I encounter the fol ...

The npm crash is caused by Firestore addDoc

My approach to importing firestore looks like this: import { getFirestore, addDoc } from "firebase/firestore"; However, it seems to be causing issues with npm running my react app as it gets stuck during compilation and eventually shows the foll ...

Simultaneously iterate through two recursive arrays (each containing another array) using JavaScript

I have two sets of arrays composed of objects, each of which may contain another set of arrays. How can I efficiently iterate through both arrays and compare them? interface items { name:string; subItems:items[]; value:string; } Array A=['parent1&ap ...

Why am I receiving a peculiar type error with @types/jsonwebtoken version 7.2.1?

My current setup includes node v6.10.3, typescript v2.3.4, and jsonwebtoken v7.4.1. Everything was running smoothly until I decided to upgrade from @types/jsonwebtoken v7.2.0 to @types/jsonwebtoken v7.2.1. However, after this update, an error started poppi ...

An object resulting from the combination of two separate objects

After reading a helpful solution on StackOverflow about merging properties of JavaScript objects dynamically, I learned how to utilize the spread operator in Typescript. However, one question still remains unanswered - what will be the type of the object c ...

Removing Firebase Users using Angular2/Ionic2

I'm currently working with Ionic2/Angular2 and I've been searching for a guide on deleting users from Firebase. If anyone has any useful examples, I would greatly appreciate the assistance. Thank you. ...