Skip to content

Instantly share code, notes, and snippets.

@hn4002
Last active June 10, 2024 23:12
Show Gist options
  • Select an option

  • Save hn4002/6173ae43d8353f0da3d7d2f853479d17 to your computer and use it in GitHub Desktop.

Select an option

Save hn4002/6173ae43d8353f0da3d7d2f853479d17 to your computer and use it in GitHub Desktop.
Check refresh token expiration time and show an error/warning accordingly.

This is what I do when I do manual auth:

    def _create_token_meta_file(self):
        # Create a file to save the timestamp for the last time the refresh token was generated
        meta_path = pathlib.Path(self._token_path).with_suffix(".meta.json")
        # First delete the meta file if it exists
        if os.path.exists(meta_path):
            os.remove(meta_path)
        # Now create the meta file with the current timestamp
        curr_dt = datetime.datetime.now(pytz.timezone('US/Eastern'))
        data = {
            'last_refresh_time': curr_dt.isoformat()
        }
        with open(meta_path, "w") as f:
            f.write(json.dumps(data, indent=4))

This generates this file in the same location as the token file:

{
    "last_refresh_time": "2024-06-05T18:06:09.417915-04:00"
}

This is how I query for it when any page on my webapp is rendered:

    def check_refresh_token_validity(self):
        """Check if refresh token is going to expire soon.
        If it is going to expire in less than 1 hour, then show an errorMessage.
        If it is giong to expire in less than 12 hours, then show a warnMessage.
        return:     (warnMessage, errorMessage)
        """
        meta_path = pathlib.Path(self._token_path).with_suffix(".meta.json")
        if not os.path.exists(meta_path):
            return None, "Token Meta file not found"
        # Meta file has the following format:
        # {
        #     "last_refresh_time": "2024-06-05T18:06:09.417915-04:00"
        # }
        with open(meta_path, 'r') as f:
            data = json.load(f)
            last_refresh_time = data['last_refresh_time']
            last_refresh_time_dt = datetime.datetime.fromisoformat(last_refresh_time)
            expiration_time_dt = last_refresh_time_dt + datetime.timedelta(days=7)
            curr_time = datetime.datetime.now(pytz.timezone('US/Eastern'))
            time_left = expiration_time_dt - curr_time
            time_left_secs = time_left.total_seconds()
            if time_left_secs < 0:
                return None, "The refresh token has expired."
            if time_left_secs < 2*3600:
                return None, "The refresh token is going to expire in less than 2 hours."
            if time_left_secs < 12*3600:
                return f"The refresh token is going to expire in {round(time_left_secs/3600)} hours.", None

        return None, None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment