How to check if an auth token is valid before instantiating a new faunadb.Client?

Hi, this question has been asked in a related topic (no worries, you couldn’t know)

The short answer:

The answer is no at this point you simply get ‘unauthorized’ if you try to use it and do something. There is no built-in method to verify the secret.

Question:

I just wanted to ask, what is your use-case? The client itself is lightweight, it’s just a wrapper that contains the secret and knows how to send a request to FaunaDB, it does not open a connection. So in essence, sending a request to FaunaDB that does something very simple that results in unauthorised tells you that you are logged out.

Is what you want one of the following?

  • Know if a secret is invalid without sending a request?
  • Differentiate between unauthorised due to a role vs an invalid token.

A possible workaround for the second:

Disclaimer: this only makes sense if you are trying to do something moderately complex, ignore if the question was just for convenience.

If you really need that, you could however if you want something like that take the Session approach where you actually store documents yourself for a ‘session’. For example:

You can easily add a ‘valid_until’ or calculate on the fly whether the ts is still valid on such a document. In your roles you could fetch the session via Identity() , verify whether it is still valid and then get the actual account (since we keep a reference in the session) to continue your business logic.

I actually use that approach to implement refresh tokens since refresh tokens are one-use only in my implementation and I don’t want to just remove them. Instead I want to make sure they are not usable anymore yet they can still be used to attempt a call. That way I can detect whether someone tries to use the same refresh token twice (that typically means a token got leaked). To do that I have a document in the account_sessions collection, create a token for that document instead of directly on the account. Once the token is used for a refresh, that document is retrieved via Identity() and updated (I set the used to true). If a call happens again I could take actions such as:

  • Logout the user completely
  • Lock the users account.