mbari-org / vars-gridview

VARS GridView is a tool for reviewing and correcting VARS localizations in bulk.
MIT License
1 stars 0 forks source link

Re-authenticate on JWT expiry #66

Open kevinsbarnard opened 6 months ago

kevinsbarnard commented 6 months ago

After 24 hours, JWTs from Annosaurus expire. In order to avoid closing and reopening VARS GridView once this happens, we should add a system to re-authenticate with the endpoints when the JWT is expired.

hohonuuli commented 6 months ago

Just a note that calling an endpoint with an expired JWT should return a 401 code. No need to check the JWT itself, just re-auth when you get 401s.

kevinsbarnard commented 6 months ago

That's what I was thinking; I wrote a decorator here that does this:

def reauthenciate(client: M3Client):
    """
    Decorator factory to reauthenticate an M3 client and retry if a request fails due to an expired token.

    Works by intercepting a requests.exceptions.HTTPError with status code 401.

    Args:
        client: The M3 client to reauthenticate. Assumes the API key has already been set.

    Returns:
        A decorator that reauthenticates the client and retries the request if it fails due to an expired token.
    """

    def decorator(f):
        def wrapper(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except requests.exceptions.HTTPError as e:
                if e.response.status_code == 401:
                    LOGGER.debug(f"Reauthenticating due to error 401: {e}")
                    client.authenticate()
                    return f(*args, **kwargs)
                else:
                    raise e

        return wrapper

    return decorator