Custom Claims refresh

When a user is newly registered, he gets an "organisation" which will be written to his custom claims through a cloud function.

The HomePage of my app (first Page that opens once after registration / after login) has some queries and in the firestore, the rules check if the user is allowed to see the data, based on his custom claims. All that works as expected.

The issue I have is, that the custom claims are not immediatly available after registration. The user needs to logout / login again.

I have a script that updates the user token, but if I run it onPageLoad, it does not finish in time before the queries to the firestore.

This is the code:

// Automatic FlutterFlow imports
import '/backend/backend.dart';
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/actions/index.dart'; // Imports other custom actions
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom action code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

import 'package:json_path/fun_extra.dart';

// Set your action name, define your arguments and return parameter,
// and then add the boilerplate code using the green button on the right!
import 'package:firebase_auth/firebase_auth.dart';

Future<String> refreshUserSession() async {
  User? user = FirebaseAuth.instance.currentUser;
  if (user != null) {
    // Renews the token and updates the session information
    String? token = await user.getIdToken(true);
    print("Token has been renewed: $token");
    // Perform further actions with the renewed token here
    return token ??
        "error"; // Returns an empty string if token is null
  } else
    return "No user logged in";
}

My current workaround is to run that script on a Landing Page (before my actual HomePage) and then add a delay of 1000ms, so the custom claims are available on the Homepage, but I want to skip that landing Page all together.

Does anyone have any idea how I could solve it?

Is there an action where I can wait for the return value of "refreshUserSession" to be updated and then redirect the user to the homepage?

3
2 replies