Can't use Auth.userAttributes with federated sign in

Viewed 1191

In my app, users are only allowed to sign in using google. However, I need to keep track of which users are considered "admins" in my system, and allow admins to promote other users to also be admins. For this, I have a custom attribute in my Cognito user pool called 'admin'.

However, when I tried using Auth.userAttributes, I ran into the error that it expects a CognitoUser object, and Auth.currentAuthenticatedUser isn't returning a CognitoUser object. After some researching, it looks like it just returns whatever it gets from the federated sign in process. Looking at my user pool, it would seem users also aren't being assigned anything at all for my custom attribute.

I'm thinking I may need to use lambda triggers? But which triggers do I use, and how do I get Auth.currentAuthenticatedUser to return a CognitoUser object? I'm thinking I'll at least need a trigger to check if a user is signing in for the first time, and to set the admin attribute to 0. But then do I use Auth.signIn? Also, from https://github.com/aws-amplify/amplify-js/blob/a047ce73/packages/auth/src/Auth.ts#L1191, the source code for Auth.currentAuthenticatedUser, it looks like it only looks for the user in the user pool if the cache doesn't have any entry for 'aws-amplify-federatedInfo', which is added when I use Auth.federatedSignIn. So do I need to clear that?

Thanks in advance. Any info or advice is appreciated.

1 Answers

Tricky! I agree this should be easier. I'd leave the cache alone. Try bypassing the cache.

import { Auth } from 'aws-amplify';

Auth.currentAuthenticatedUser({
    bypassCache: true  // If set to true, this call will send a request to Cognito to get the latest user data
}).then(user => console.log(user))
.catch(err => console.log(err));

Why? currentAuthenticatedUser() is returning a FederatedUser when this is somewhat helpful because the ideal response would be a CognitoUser. bypassCache alters the response of currentAuthenticatedUser().

May your app bring great felicity!

Related