def __init__(self,
                 client_id,
                 client_secret,
                 refresh_token,
                 https_proxy=None):
        """Initializes a GoogleRefreshTokenClient.

    Args:
      client_id: A string containing your client ID.
      client_secret: A string containing your client secret.
      refresh_token: A string containing your refresh token.
      [optional]
      https_proxy: A string identifying the URL of a proxy that all HTTPS
          requests should be routed through.
    """
        self._oauthlib_client = oauth2.BackendApplicationClient(
            client_id,
            token={
                'access_token': 'None',
                'refresh_token': refresh_token,
                'token_type': 'Bearer',
                'expires_in': '-30'
            })
        self._client_secret = client_secret
        self.https_proxy = https_proxy
Beispiel #2
0
 def get_access_token(url: str, client_id: str, client_secret: str, audience: str) -> str:
     try:
         client = oauth2.BackendApplicationClient(client_id)
         client.prepare_request_body(include_client_id=True)
         with OAuth2Session(client=client) as session:
             response = session.post(url,
                                     data={
                                         "client_id": client_id,
                                         "client_secret": client_secret,
                                         "audience": audience
                                     })
             response.raise_for_status()
             return response.json()["access_token"]
     except HTTPError:
         raise InvalidOAuthCredentials(url=url, client_id=client_id, audience=audience)
async def periodic_new_users():
    client = oauth2.BackendApplicationClient(KEYCLOAK_CLIENT_ID)
    session = requests_oauthlib.OAuth2Session(
        client=client,
        token=token,
        auto_refresh_kwargs=extra,
        auto_refresh_url=KEYCLOAK_TOKEN_URL,
        token_updater=token_updater)

    slack_client = slack.WebClient(token=SLACK_API_TOKEN)

    while True:
        users = await keycloak_new_users(session)

        if users is not None:
            slack_client.chat_postMessage(channel=SLACK_CHANNEL, text=users)

        await asyncio.sleep(REGISTER_INTERVAL)
    def get_conn(self, headers: OptionalDictAny = None) -> requests_oauthlib.OAuth2Session:
        conn = self.get_connection(self.http_conn_id)

        # login and password are required
        assert conn.login and conn.password

        client = oauth2.BackendApplicationClient(client_id=conn.login)
        session = requests_oauthlib.OAuth2Session(client=client)

        # inject token to the session
        assert self.token_url
        session.fetch_token(
            token_url=self.token_url,
            client_id=conn.login,
            client_secret=conn.password,
            include_client_id=True
        )

        if conn.host and "://" in conn.host:
            self.base_url = conn.host
        else:
            # schema defaults to HTTPS
            schema = conn.schema if conn.schema else "https"
            host = conn.host if conn.host else ""
            self.base_url = schema + "://" + host

        if conn.port:
            self.base_url = self.base_url + ":" + str(conn.port)

        if conn.extra:
            try:
                session.headers.update(conn.extra_dejson)
            except TypeError:
                self.log.warn('Connection to %s has invalid extra field.', conn.host)
        if headers:
            session.headers.update(headers)

        return session
KEYCLOAK_EVENTS = f'{KEYCLOAK_URL.strip("/")}/admin/realms/{KEYCLOAK_REALM}/events'

SLACK_CHANNEL = os.environ['SLACK_CHANNEL']
SLACK_API_TOKEN = os.environ['SLACK_API_TOKEN']

extra = {
    'client_id': KEYCLOAK_CLIENT_ID,
    'client_secret': KEYCLOAK_CLIENT_SECRET,
}

token = {}

def token_updater(new_token):
    token = new_token

client = oauth2.BackendApplicationClient(KEYCLOAK_CLIENT_ID)
session = requests_oauthlib.OAuth2Session(
    client=client,
    token=token,
    auto_refresh_kwargs=extra,
    auto_refresh_url=KEYCLOAK_TOKEN_URL,
    token_updater=token_updater)

token = session.fetch_token(KEYCLOAK_TOKEN_URL, client_secret=KEYCLOAK_CLIENT_SECRET)

async def keycloak_new_users(session):
    try:
        response = session.get(KEYCLOAK_EVENTS, params={'type': 'REGISTER'})
    except Exception as e:
        logger.error(f'Error querying keycloak {str(e)}')