Establish a user profile and define custom claims using Firebase Authentication

When a new user is registered, certain values for user access control are set up immediately.

The issue arises when the data set is only visible in the subsequent sessions after logging out of the authenticated user session that was created.

My challenge lies in retrieving claims right after creating a new user in Firebase Authentication, without the need to log out and back in to obtain this crucial data.

auth.service.ts

public user: any;
public firestoreCollection: string;
public admin: boolean;

constructor(private _angularFireauth: AngularFireAuth) {

    this.getUser().subscribe((user: firebase.User) => {

        this.user = user;

        if (this.user) {
            // Obtaining claims requires a logout() followed by login().
            user.getIdTokenResult().then(idTokenResult => {
                this.firestoreCollection = idTokenResult.claims.firestoreCollection;
                this.admin = idTokenResult.claims.admin;
            });
        }
    });
}

public getUser(): Observable<firebase.User> {
    return this._angularFireauth.authState;
}

public async createAccount(user: any): Promise<void> {
    const auth = await this._angularFireauth.auth
        .createUserWithEmailAndPassword(user.email, user.password);

    const userObject = {
        displayName: user.nome.trim(),
        photoURL: 'assets/images/avatars/profile.jpg'
    };

    await auth.user.updateProfile(userObject);

    const setUserControlAccess = firebase.functions()
        .httpsCallable('setUserControlAccess');

    await setUserControlAccess({
        admin: true, assinante: true, profissional: true,
        firestoreCollection: auth.user.uid,
        email: auth.user.email
    });

    // Attempted re-authentication to fetch claims.
    await this.reauthenticateUser(user.email, user.password);
}

Cloud Functions

 export const setUserControlAccess = functions.https.onCall(async (data, context) => {
     try {
        const customUserClaims = {
        admin: data.admin,
        firestoreCollection: data.firestoreCollection
    };

    const user = await admin.auth().getUserByEmail(data.email);
    await authentication.setCustomUserClaims(user.uid, customUserClaims);

} catch (error) {
    console.error(error);
    return error;
}
 });

Answer №1

When in need of immediate access to user roles, it is recommended to utilize a different method than custom claims. Storing this data in the database ensures quick availability and greater scalability. Custom claims are best suited for less frequently changing information, such as identifying application administrators. For further insights, check out the video Five tips to secure your app.

However, if necessary, you can trigger a refresh of the user's profile to fetch updated token changes (including claims). If that solution proves unsuccessful, the user may need to sign out and back in again.

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

TypeScript encountered an error: The get call is missing 0 type arguments

I encountered a typescript error stating "Expected 0 type arguments, but got 1" in the line where my get call is returning. Can you help me identify what is wrong with my get call in this code snippet? public get(params: SummaryParams): Observable&l ...

Learn how to configure settings in the config service by using Angular's APP_INITIALIZER feature

I am working on an Angular app where I need to implement runtime configuration in order to use the same build artifact for any target environment. The app should load settings from a backend .NET API, with the API URL specified in the config.json file loca ...

Nearly every category except for one from "any" (all varieties but one)

In Typescript, is it feasible to specify a type for a variable where the values can be any value except for one (or any other number of values)? For instance: let variable: NOT<any, 'number'> This variable can hold any type of value excep ...

When using Angular with mdbootstrap, the mdb-tabs directive will move to the end if the ngIf condition is true

Currently facing a challenge with a significant amount of code here. It is referenced as follows: "ng-uikit-pro-standard": "file:ng-uikit-pro-standard-8.3.0.tgz", I am attempting to display a tab between 1 and 3 if a certain condition ...

Angular 6: Harnessing the Power of Subject

In my angular applications, I have been utilizing the Subject feature from the rxjs library to create an event emitter. However, upon migrating to Angular 6, I encountered the issue that this module is no longer available. Cannot find module 'rxjs/Su ...

Using ngrx store select subscribe exclusively for designated actions

Is it possible to filter a store.select subscription by actions, similar to how we do with Effects? Here is an example of the code in question: this.store .select(mySelector) .subscribe(obj => { //FILTER SUBSCRIPTION BY ACTION this.object = ob ...

What is causing the issue in locating the assert package for VS Code and TypeScript?

My main issue lies with the pre-installed node libraries (path, fs, assert). Let me outline the process that leads to this problem: Begin by launching Visual Studio. Select File > Open Folder, then pick the root core-demo folder. In the file panel, loc ...

Utilizing Angular2 (Frontend) and Spring Boot (Backend) for Excel file uploading

As someone who is new to Angular 2, I am currently attempting to upload an Excel file from the Angular 2 frontend. My goal is to upload the Excel file from the Angular 2 frontend, send it to the Spring Boot backend for necessary modifications, and th ...

Create a fresh type by dynamically adjusting/filtering its attributes

Suppose we have a type defined as follows: type PromiseFunc = () => Promise<unknown>; type A = { key1: string; key2: string; key3: PromiseFunc; key4: string; key5: PromiseFunc; key6: SomeOtherType1[]; key7: SomeOtherType2[]; key8: ...

Why is the entire rxjs library included in the Angular 9 build bundle?

When I create a new Angular 9.1.1 project and build it without adding any code, the final bundle includes the entire rxjs library. Here is a screenshot from webpack-bundle analyzer The package.json file contains the following dependencies: "dependenci ...

Solving runtime JavaScript attribute issues by deciphering TypeScript compiler notifications

Here is a code snippet I am currently working with: <div class="authentication-validation-message-container"> <ng-container *ngIf="email.invalid && (email.dirty || email.touched)"> <div class="validation-error-message" *ngIf=" ...

Harnessing the power of Heatmaps in Angular 6

Currently, I am developing a data visualization project using angular6. I would greatly appreciate any assistance on how to incorporate heatmaps into the angular6 application. Thank you in advance for your help! ...

The Angular frontend implemented with Nginx fails to establish a connection with the Django Rest Framework (DR

I've set up a drf backend and angular frontend on the same aws instance, utilizing Nginx and gunicorn for the drf, and Nginx for the angular. While the drf API tested fine using Postman, the angular frontend is unable to connect to the API. The site l ...

Displaying buttons based on the existence of a token in Angular - A guide

Can you assist me with a coding issue I'm facing? I have implemented three methods: login, logout, and isAuthenticated. My goal is to securely store the token in localStorage upon login, and display only the Logout button when authenticated. However, ...

Automatically assign the creation date and modification date to an entity in jhipster

I am currently working on automatically setting the creation date and date of the last change for an entity in JHipster, utilizing a MySQL Database. Below is my Java code snippet for the entity: @GeneratedValue(strategy = GenerationType.AUTO) @Column(nam ...

Ensure that the initial step in Android involves calling FirebaseApp.initializeApp(Context)

I've encountered a problem and checked various answers on this platform, but none seem to provide a suitable solution. Initially, I was using an older version of Firebase which worked without any issues. However, when I attempted to upgrade followin ...

Leveraging Nextjs Link alongside MUI Link or MUI Button within a different functional component (varieties)

Currently in my development setup, I am utilizing Next.js (10.2) and Material-UI (MUI) with Typescript. In the process, I have implemented a custom Link component: Link.tsx (/components) [...] On top of that, I have created another iteration which functi ...

To enable the "Select All" functionality in ag-grid's infinite scrolling feature in Angular 4, utilize the header check box

Is there a way to add a checkbox in the header of ag-grid for selecting all options when using an infinite row model? It seems that the headerCheckboxSelection=true feature is not supported in this model. Are there any alternative methods to include a che ...

The latest version of npm packages is not displayed when you hover over them in Visual Studio Code

Previously in package.json, I was able to check the latest versions of packages by hovering over each package version as a "tooltip", but that feature seems to have disappeared now. I am using VSC version 1.19.2. I am navigating through a proxy. I ha ...

Adding a datepicker popup to an input field in angular2 with the format of YYYY-MM-DD hh:mm:ss is as simple as following

Can someone help me with adding a datepicker popup to an input field in Angular, using the format YYYY-MM-DD hh:mm:ss? I have tried the following code in my .html file but it doesn't seem to be working. <input [(ngModel)]="date2" ngui-datetime-pi ...