DEV Community

Thibault Couraud for Potloc

Posted on

OAuth Tokens & Potlock gem

A bit of context πŸ‘‹πŸ½

When calling Apis that use OAuth as authentication process, you need to generate an access token. And to get an access token, we have to use a refresh token stored in the server.

Here's the OAuth workflow to generate this access token:

Image source:

So what was the need? πŸ€”

An access token expires after a certain time, in minutes, hours, days, depending on the provider. So we need to refresh it time to time.

The issue was that different processes were refreshing the token at the same time, invalidating other's freshly generated access token.

So we had to find a way to be sure that only one process can refresh the token.

Here comes the gem πŸš€

Today we introduce our new gem: Potlock - a Distributed Read-Write lock using redis

(available on Github here: GitHub - potloc/potlock)

This brand new gem only allows one simultaneous reader or writer. And if the lock is taken, any readers or writers who come along will have to wait.

Here's an example of how we use this gem at Potloc:

def token
  lock = "snapchat_api")

  # Fetch the token, refresh it if not present
  token = lock.fetch { refresh_token! }

  # A token is invalid when empty or expired
  raise InvalidToken unless valid?(token)

rescue InvalidToken => _e
  # Generate and save a new token
  lock.set { refresh_token! }
  token = lock.get
Enter fullscreen mode Exit fullscreen mode

This way, we are sure that all the processes will have the same valid access token and won't overwrite it at the same time πŸŽ‰

Interested in what we do at Potloc? Come join us! We are hiring πŸš€

Top comments (0)