Пример #1
0
def on_refresh_oauth_token(app: Application, server: AnyServer,
                           oauth_session: OAuth2Session):
    try:
        server_info = app.server_db.get_server_info(server)
    except Exception as e:
        logger.error("error getting server info", exc_info=True)
        enter_error_state_threadsafe(app, e)
        return
    try:
        oauth_session.refresh_token(token_url=server_info.token_endpoint)
    except InvalidOauthGrantError as e:
        logger.warning(f'Error refreshing OAuth token: {e}')
        app.interface_transition_threadsafe('oauth_refresh_failed')
    else:
        app.interface_transition_threadsafe('oauth_refresh_success')
Пример #2
0
def validate(oauth: OAuth2Session, can_refresh=True):
    try:
        r = requests.get(
            'https://id.twitch.tv/oauth2/validate',
            headers={'Authorization': f'OAuth {oauth.token["access_token"]}'})
        # print(r.text)
        r.raise_for_status()
    except requests.HTTPError as e:
        if can_refresh:
            token = oauth.refresh_token(oauth.auto_refresh_url)
            token_saver(token)
            oauth_ = get_session(config.twitch_client_id,
                                 config.twitch_client_secret,
                                 'https://iarazumov.com/oauth/twitch')
            validate(oauth_, False)
        else:
            logging.fatal("Validation failed: " + str(e))
            raise RuntimeError("Validation failed")
Пример #3
0
async def get_access_token(oauth: OAuth2Session):
    """Tries to get the saved access token and refreshes it if it's expired.

    Arguments:
        oauth {OAuth2Session} -- OAuth client

    Returns:
        str -- the access token
    """
    from app.config.pickle import access_code_pickle_path
    from app.config.podbean import client_id, client_secret

    [access_code_pickle_path, client_id, client_secret] = await asyncio.gather(
        access_code_pickle_path(), client_id(), client_secret()
    )

    token_info = await load_pickle(access_code_pickle_path)
    expires_at = datetime.fromtimestamp(token_info["expires_at"])
    logging.debug(
        f"Saved access token in access_code.pickle expires at '{expires_at}'."
    )
    if expires_at <= datetime.now():  # expired?
        logging.info(
            f"Stored access token has expired '{token_info['access_token']}'. Refreshing with refresh token '{token_info['refresh_token']}'..."
        )

        # refresh the token
        new_token_info = oauth.refresh_token(
            token_url=token_url,
            refresh_token=token_info["refresh_token"],
            auth=(client_id, client_secret),
        )
        new_token_info["expires_at"] = (
            datetime.timestamp(datetime.now()) + new_token_info["expires_in"]
        )
        token_info.update(new_token_info)

        # save info into pickle
        await save_pickle(access_code_pickle_path, token_info)
    else:
        logging.debug(f"Access token is not expired.")

    return token_info["access_token"]