Home > front end >  listening for changes of custom claim of user
listening for changes of custom claim of user

Time:10-13

I'm using the custom claim of firebase functions to set access control for users in my app after the user login using a phone number UI shows some pages specified for the user with no role specified so when the Admin upgrades the user rule UI gets updated to show another paged specified for the upgraded user. Everything is working fine with me but I'm having a problem with updating the UI while the user is logged in (i.e) the user has to log out so updating the UI work !!, I used setState() to detect the role of the user and update the UI according to it but that doesn't seem to work correctly.

Future<Map<dynamic, dynamic>> get currentUserClaims async {
final user = FirebaseAuth.instance.currentUser;
// If refresh is set to true, a refresh of the id token is forced.
final idTokenResult = await user.getIdTokenResult(false);
return idTokenResult.claims;

}

updateUI() async {
 var isClient = ( await currentUserClaims)['client'] == true;

setState(() {
  if(isClient){
    // check if the user is client or not (access all pages in the app as a client)
    _visible_for_client =  true;
    _visible_subscribe =  false;
    _visible_sign_out =  true;
    print('is client');

  } else if(currentUser != null){
    // if the currentUser is not a client then he's just a registered (visitor) but with limited 
     //access (access specific pages in the app)

    _visible_for_visitor =  true;
    _visible_subscribe =  false;
    _visible_sign_out =  true;
    print('is visitor ');
  }
});

}

thanks for any help in advance.

CodePudding user response:

All custom claims for a user are part of their ID token, which the client first gets when the user signs in and which is then refreshed once every hour. So by default you'll either have to wait for up to an hour, or sign out and in again to get the updated ID token and claims.

But when you call user.getIdTokenResult(true), you are forcing the SDK to refresh its ID token right away. So that'd be a way to get the updated claims before the SDK auto-refreshes the token on its own.

  • Related