import http.client import json import os from time import sleep from urllib.parse import urlencode class NotAuthenticated(Exception): pass class Authorization: token = "" lock = False @classmethod def __authorize(cls) -> None: cls.token = "" conn = http.client.HTTPSConnection(os.environ.get("AUTH0_HOST")) payload = { "client_id": os.environ.get("CLIENT_ID"), "client_secret": os.environ.get("CLIENT_SECRET"), "audience": os.environ.get("AUDIENCE"), "grant_type": os.environ.get("GRANT_TYPE"), "username": os.environ.get("USERNAME"), "password": os.environ.get("PASSWORD"), "realm": os.environ.get("REALM"), } headers = {"content-type": "application/x-www-form-urlencoded"} conn.request("POST", "/oauth/token", urlencode(payload), headers) res = conn.getresponse() data = res.read() data = json.loads(data.decode("utf-8")) try: cls.token = "{} {}".format(data["token_type"], data["access_token"]) except KeyError: raise NotAuthenticated("Authorization failed") @classmethod def get_token(cls) -> str: while cls.lock: sleep(1) if not cls.token: cls.lock = True cls.__authorize() cls.lock = False return cls.token