javascriptauthenticationauth0graphcool

How do identify a new user using auth0-js WebAuth?


I'm trying to keep things simple and using auth0-js WebAuth to authenticate users. However, as there is a redirect involved, I'm not in control of the sign-up functionality at that point.

My specific use-case is to call a createUser graphql mutation using Graphcool to create a user in my database, but I only want to do this if the user is a new user, obviously.

MY QUESTION: Using auth0-js, is it possible to identify if a user is a new or existing user in my client application after the redirect from Auth0 back to my client application (assuming authentication is successful)?


Solution

  • There are two general approaches here, and both require you to persist the Auth0 token in local storage after receiving it. You can use a middleware for your GraphQL client that checks local storage for a token for every request and includes it as the Authorization: Bearer <token> header if present.

    Let's now look at the two approaches.

    Always try to create the user

    Trying to create the user using the createUser mutation as soon as receiving the token is a fairly simple approach. This is how the mutation looks like:

    mutation signUp($token: String!) {
      createUser(authProvider: {
        auth0: {
          idToken: $token
        }
      }) {
        id
      }
    }
    

    Now, if the token is valid and matches the configuration of the Auth0 integration in Graphcool, there are two possible scenarios. Note, a token corresponds to a user if the auth0UserId it embeds matches.

    Check if the user is already signed in

    If you have a more elaborate sign up flow, you might want to redirect your users to a sign up form, which is not really possible with the first approach. Instead, we can check if the currently used token corresponds to a registered user before proceeding. You can use the user query to do that:

    query {
      user {
        id
      }
    }
    

    Again, there are the same two scenarios as above:

    Compare this to this FAQ article in the Graphcool documentation.