Exemplo n.º 1
0
def get_mgmt_token():
    get_token = GetToken(AUTH0_DOMAIN)
    token = get_token.client_credentials(
        NON_INTERACTIVE_CLIENT_ID, NON_INTERACTIVE_CLIENT_SECRET,
        'https://{}/api/v2/'.format(AUTH0_DOMAIN))

    return token['access_token']
Exemplo n.º 2
0
def role_updating():
    role_id = request.json['id']
    role_name = request.json['name']
    role_desc = request.json['desc']

    get_token = GetToken(DOMAIN)

    token = get_token.client_credentials(M2M_ID, M2M_SEC,
                                         '{}/api/v2/'.format(AUTH0_DOMAIN))
    mgmt_api_token = token['access_token']
    auth0 = Auth0(DOMAIN, mgmt_api_token)

    roles = auth0.roles

    try:
        resp = roles.update(id=role_id,
                            body={
                                'name': role_name,
                                'description': role_desc
                            })
    except exceptions.Auth0Error:
        return {
            'resp': {
                'error': 'Role id, {0}, doesn\'t exist'.format(role_id)
            }
        }

    return {
        'resp': {
            'id': resp['id'],
            'name': resp['name'],
            'desc': resp['description']
        }
    }
def get_auth0_client(config):
    get_token = GetToken(config['domain'])
    token = get_token.client_credentials(config['non_interactive_client_id'],
                                         config['non_interactive_client_secret'],
                                         'https://{}/api/v2/'.format(config['domain']))
    mgmt_api_token = token['access_token']
    return Auth0(config['domain'], mgmt_api_token)
Exemplo n.º 4
0
def create_client(jupyterhub_endpoint):
    DOMAIN = os.environ["AUTH0_DOMAIN"]
    CLIENT_ID = os.environ["AUTH0_CLIENT_ID"]
    CLIENT_SECRET = os.environ["AUTH0_CLIENT_SECRET"]

    get_token = GetToken(DOMAIN)
    token = get_token.client_credentials(CLIENT_ID, CLIENT_SECRET,
                                         "https://{}/api/v2/".format(DOMAIN))
    mgmt_api_token = token["access_token"]

    auth0 = Auth0(DOMAIN, mgmt_api_token)

    credentials = auth0.clients.create({
        "name":
        f"QHub - {jupyterhub_endpoint}",
        "description":
        f"QHub - {jupyterhub_endpoint}",
        "callbacks": [f"https://{jupyterhub_endpoint}/hub/oauth_callback"],
        "app_type":
        "regular_web",
    })

    return {
        "auth0_subdomain": ".".join(DOMAIN.split(".")[:-2]),
        "client_id": credentials["client_id"],
        "client_secret": credentials["client_secret"],
        "scope": ["openid", "email", "profile"],
        "oauth_callback_url":
        f"https://{jupyterhub_endpoint}/hub/oauth_callback",
    }
Exemplo n.º 5
0
 def get_token(self):
     audience = settings.AUTH0_MANAGEMENT_API_AUDIENCE
     get_token = GetToken(self.domain)
     token = get_token.client_credentials(self.client_id,
                                          self.client_secret, audience)
     mgmt_api_token = token['access_token']
     return mgmt_api_token
Exemplo n.º 6
0
 def auth0(self):
     if not hasattr(self, '_auth0'):
         gt = GetToken(self.domain)
         creds = gt.client_credentials(self.client_id, self.client_secret,
                                       f'https://{self.domain}/api/v2/')
         self._auth0 = Auth0(self.domain, creds['access_token'])
     return self._auth0
Exemplo n.º 7
0
def get_auth0():
    """
    Retrieve instantiated auth0 client.

    This also uses the cache so we're not re-instantiating for every update.
    """
    auth0_api_access_token = cache.get('auth0_api_access_token')
    if not auth0_api_access_token:
        client = GetToken(api_settings.AUTH0_DOMAIN, )
        response = client.client_credentials(
            api_settings.AUTH0_CLIENT_ID,
            api_settings.AUTH0_CLIENT_SECRET,
            api_settings.AUTH0_AUDIENCE,
        )
        cache.set(
            'auth0_api_access_token',
            response['access_token'],
            timeout=response['expires_in'],
        )
        auth0_api_access_token = response['access_token']
    auth0 = Auth0(
        api_settings.AUTH0_DOMAIN,
        auth0_api_access_token,
    )
    return auth0
Exemplo n.º 8
0
 def get_token(domain, client_id, client_secret):
     gt = GetToken(domain)
     creds = gt.client_credentials(
         client_id, client_secret,
         f'https://{domain}/api/v2/'
     )
     return creds['access_token']
Exemplo n.º 9
0
def user_creation():
    user_email = request.json['email']
    user_name = request.json['name']
    user_username = request.json['username']
    user_first = user_name.split()[0]
    user_last = user_name.split()[1]
    user_password = request.json['password']

    get_token = GetToken(DOMAIN)
    token = get_token.client_credentials(M2M_ID, M2M_SEC,
                                         '{}/api/v2/'.format(AUTH0_DOMAIN))
    mgmt_api_token = token['access_token']
    auth0 = Auth0(DOMAIN, mgmt_api_token)

    users = auth0.users
    try:
        resp = users.create({
            'email': user_email,
            'name': user_name,
            'given_name': user_first,
            'family_name': user_last,
            'username': user_username,
            'connection': 'LoginSystem',
            'password': user_password
        })
    except exceptions.Auth0Error:
        return {'resp': {'error': 'User already exists'}}

    return {'resp': resp}
class AdminTokenMgr(object):
    def __init__(self, domain=None, client_id=None, client_secret=None, token_data=None, *args, **kwargs):
        auth0: Auth0
        self.domain = domain if domain else env.str('AUTH0_DOMAIN', None)
        self.client_id = client_id if client_id else env.str('AUTH0_CLIENT_ID', None)
        self.client_secret = client_secret if client_secret else env.str('AUTH0_CLIENT_SECRET')
        self.get_token = GetToken(self.domain)
        if token_data:
            self.token_data = token_data
        else:
            self.token_data = self.get_token.client_credentials(self.client_id, self.client_secret,'https://{}/api/v2/'.format(self.domain))
        self.mgmt_access_token = self.token_data['access_token']

        self.auth0 = Auth0(self.domain, self.mgmt_access_token)
        try:
            super(AdminTokenMgr, self).__init__(*args, **kwargs)
        except Exception:
            pass

    def get_user_db_connection(self):
        connections = self.auth0.connections.all()
        try:
            user_db = next(x for x in connections if "Username-Password-Authentication" in x["name"])
        except StopIteration:
            raise KeyError("Username-Password-Authentication")
        return user_db
Exemplo n.º 11
0
def get_auth0_token():
    get_token = GetToken(settings.AUTH0_DOMAIN)
    token = get_token.client_credentials(
        settings.AUTH0_CLIENT_ID,
        settings.AUTH0_CLIENT_SECRET,
        f'https://{settings.AUTH0_DOMAIN}/api/v2/',
    )
    return token
Exemplo n.º 12
0
def get_auth0_token():
    client = GetToken(settings.AUTH0_DOMAIN)
    token = client.client_credentials(
        settings.AUTH0_API_ID,
        settings.AUTH0_API_SECRET,
        settings.AUTH0_AUDIENCE,
    )
    return token['access_token']
Exemplo n.º 13
0
def get_token():
    gt = GetToken(current_app.config['AUTH0_DOMAIN'])
    token = gt.client_credentials(
        current_app.config['AUTH0_CLIENT_ID'],
        current_app.config['AUTH0_CLIENT_SECRET'],
        'https://{}/api/v2/'.format(current_app.config['AUTH0_DOMAIN']))
    mgmt_api_token = token['access_token']
    return mgmt_api_token
Exemplo n.º 14
0
def get_auth0_inst(domain, client_id, client_secret):
    """
    Return an authenticated Auth0 instance
    """
    gt = GetToken(domain)
    creds = gt.client_credentials(client_id, client_secret, f"https://{domain}/api/v2/")
    auth0_inst = Auth0(domain, creds["access_token"])
    return auth0_inst
Exemplo n.º 15
0
 def __init__(self):
     get_token = GetToken(domain)
     self.token = get_token.client_credentials(client_id, client_secret,
                                               API_ENDPOINT)
     self.mgmt_api_token = self.token['access_token']
     self.session = RequestSession(API_ENDPOINT)
     headers = {'Bearer': self.mgmt_api_token}
     self.session.headers.update(headers)
def get_management_api_client():
    get_token = GetToken(Config.AUTH0_DOMAIN)
    token = get_token.client_credentials(
        Config.AUTH0_NON_INTERACTIVE_CLIENT_ID,
        Config.AUTH0_NON_INTERACTIVE_CLIENT_SECRET,
        Config.AUTH0_BASE_URL + '/api/v2/')
    mgmt_api_token = token['access_token']

    auth0 = Auth0(Config.AUTH0_DOMAIN, mgmt_api_token)
    return auth0
Exemplo n.º 17
0
 def auth0(self):
     """
     Return an authenticated Auth0 instance
     """
     if not hasattr(self, "_auth0"):
         gt = GetToken(self.domain)
         creds = gt.client_credentials(self.client_id, self.client_secret,
                                       f"https://{self.domain}/api/v2/")
         self._auth0 = Auth0(self.domain, creds["access_token"])
     return self._auth0
Exemplo n.º 18
0
def create_client(jupyterhub_endpoint, project_name, reuse_existing=True):
    for variable in {"AUTH0_DOMAIN", "AUTH0_CLIENT_ID", "AUTH0_CLIENT_SECRET"}:
        if variable not in os.environ:
            raise ValueError(
                f"Required environment variable={variable} not defined")

    get_token = GetToken(os.environ["AUTH0_DOMAIN"])
    token = get_token.client_credentials(
        os.environ["AUTH0_CLIENT_ID"],
        os.environ["AUTH0_CLIENT_SECRET"],
        f'https://{os.environ["AUTH0_DOMAIN"]}/api/v2/',
    )
    mgmt_api_token = token["access_token"]

    auth0 = Auth0(os.environ["AUTH0_DOMAIN"], mgmt_api_token)

    oauth_callback_url = (
        f"https://{jupyterhub_endpoint}/auth/realms/qhub/broker/auth0/endpoint"
    )

    for client in auth0.clients.all(
            fields=["name", "client_id", "client_secret", "callbacks"],
            include_fields=True):
        if client["name"] == project_name and reuse_existing:
            if oauth_callback_url not in client["callbacks"]:
                logger.info(
                    f"updating existing application={project_name} client_id={client['client_id']} adding callback url={oauth_callback_url}"
                )
                auth0.clients.update(
                    client["client_id"],
                    {"callbacks": client["callbacks"] + [oauth_callback_url]},
                )

            return {
                "auth0_subdomain":
                ".".join(os.environ["AUTH0_DOMAIN"].split(".")[:-2]),
                "client_id":
                client["client_id"],
                "client_secret":
                client["client_secret"],
            }

    client = auth0.clients.create({
        "name": project_name,
        "description": f"QHub - {project_name} - {jupyterhub_endpoint}",
        "callbacks": [oauth_callback_url],
        "app_type": "regular_web",
    })

    return {
        "auth0_subdomain":
        ".".join(os.environ["AUTH0_DOMAIN"].split(".")[:-2]),
        "client_id": client["client_id"],
        "client_secret": client["client_secret"],
    }
Exemplo n.º 19
0
    def get_token(self):
        get_token = GetToken(self.domain)

        token = get_token.client_credentials(
            settings.AUTH0_CLIENT_ID,
            settings.AUTH0_CLIENT_SECRET,
            f"https://{self.domain}/api/v2/",
        )

        mgmt_api_token = token["access_token"]
        return mgmt_api_token
Exemplo n.º 20
0
def get_management_api_token():
    domain = auth0_api_settings.MANAGEMENT_API['AUTH0_DOMAIN']
    client_id = auth0_api_settings.MANAGEMENT_API['AUTH0_CLIENT_ID']
    client_secret = auth0_api_settings.MANAGEMENT_API['AUTH0_CLIENT_SECRET']

    get_token = GetToken(domain)
    token = get_token.client_credentials(
        client_id, client_secret,
        'https://{domain}/api/v2/'.format(domain=domain))

    return token['access_token']
Exemplo n.º 21
0
    def create_access_token(cls):

        domain = settings.AUTH0_DOMAIN
        client_id = settings.AUTH0_CLIENT_ID
        client_secret = settings.AUTH0_CLIENT_SECRET
        api_audience = settings.API_AUDIENCE

        get_token = GetToken(domain)
        token = get_token.client_credentials(client_id, client_secret,
                                             api_audience)

        cls.objects.create(access_token=token['access_token'], )
Exemplo n.º 22
0
def get_mgmt_api_token() -> str:
    """
    Handle Auth0 callback in AUTHLIB mode
    :return:
    """
    # https://github.com/auth0/auth0-python#management-sdk-usage
    get_token = GetToken(config[AUTH0_DOMAIN])
    token = get_token.client_credentials(
        config[NON_INTERACTIVE_CLIENT_ID],
        config[NON_INTERACTIVE_CLIENT_SECRET],
        auth0_url('/api/v2/')
    )
    return token['access_token']
Exemplo n.º 23
0
def get_auth0_access_token():
    """Get a Token for the Management-API."""
    ret = memcache.get('get_auth0_access_token()')
    if not ret:
        assert gaetkconfig.AUTH0_DOMAIN != '*unset*'
        assert gaetkconfig.AUTH0_CLIENT_ID != '*unset*'
        get_token = GetToken(gaetkconfig.AUTH0_DOMAIN)
        token = get_token.client_credentials(
            gaetkconfig.AUTH0_CLIENT_ID,
            gaetkconfig.AUTH0_CLIENT_SECRET,
            'https://{}/api/v2/'.format(gaetkconfig.AUTH0_DOMAIN))
        ret = token['access_token']
        memcache.set('get_auth0_access_token()', ret, token['expires_in'] / 2)
    return ret
def conectarSSO():
    dominio = 'authentication-django.auth0.com'
    client_id = '3sWyFJccKrRs3wH52bgQJFX9im4wS0Qp'
    client_secret = 'my82yHs9ZSmb-frFvlLWAEUhVGZwAuyaxlfOR6Ggi1gvWf1FqVQO0Lzfm-uQfPTE'

    # Nos autenticamos al sso y no responde con un token
    get_token = GetToken(dominio)
    token = get_token.client_credentials(client_id, client_secret,
                                         'https://{}/api/v2/'.format(dominio))
    api_token = token['access_token']

    # Enviar token
    auth0 = Auth0(dominio, api_token)
    return auth0
Exemplo n.º 25
0
def connect_to_auth0():
    """Connect to Auth0 using Client Credentials flow. Credentials are stored
    in .env"""
    env_path = Path('.') / '.env'
    load_dotenv(dotenv_path=env_path)
    auth0_client_id = env[constants.AUTH0_CLIENT_ID]
    auth0_client_secret = env[constants.AUTH0_CLIENT_SECRET]
    auth0_domain = env[constants.AUTH0_DOMAIN]
    mgmt_api_url = 'https://' + auth0_domain + '/api/v2/'

    get_token = GetToken(auth0_domain)
    token = get_token.client_credentials(auth0_client_id, auth0_client_secret,
                                         mgmt_api_url)
    mgmt_api_token = token['access_token']
    return Auth0(auth0_domain, mgmt_api_token)
Exemplo n.º 26
0
def init() -> Auth0sdk:
    """
    instantiate Auth0 SDK class
    Goes to Auth0 dashboard and get followings.
    DOMAIN: domain of Auth0 Dashboard Backend Management Client's Applications
    MGMT_CLIENTID: client ID of Auth0 Dashboard Backend Management Client's Applications
    MGMT_CLIENT_SECRET: client secret of Auth0 Dashboard Backend Management Client's Applications
    """
    get_token = GetToken(DOMAIN)
    token = get_token.client_credentials(
        MGMT_CLIENTID, MGMT_CLIENT_SECRET, f"https://{DOMAIN}/api/v2/",
    )
    mgmt_api_token = token["access_token"]

    auth0 = Auth0sdk(DOMAIN, mgmt_api_token)
    return auth0
Exemplo n.º 27
0
def get_auth0_user_id_by_email(email):
    """Get Auth0 user id by user email"""

    get_token = GetToken(auth0_domain)
    token = get_token.client_credentials(
        auth0_client_id, auth0_client_secret,
        'https://{}/api/v2/'.format(auth0_domain))
    mgmt_api_token = token['access_token']
    auth0_users = Auth0Users(auth0_domain, mgmt_api_token)
    query = 'email:%s' % email
    results = auth0_users.list(q=query, search_engine='v3')
    if results['users']:
        auth0_user_id = results['users'][0]['user_id']
    else:
        auth0_user_id = None

    return auth0_user_id
Exemplo n.º 28
0
def user_deletion():
    user_id = request.json['id']

    get_token = GetToken(DOMAIN)
    token = get_token.client_credentials(M2M_ID, M2M_SEC,
                                         '{}/api/v2/'.format(AUTH0_DOMAIN))
    mgmt_api_token = token['access_token']
    auth0 = Auth0(DOMAIN, mgmt_api_token)

    users = auth0.users
    try:
        users.delete(user_id)
    except exceptions.Auth0Error:
        return {
            'resp': {
                'error': 'User id, {0} doesn\'t exist'.format(user_id)
            }
        }
Exemplo n.º 29
0
def get_auth0():
    auth0_api_access_token = cache.get('auth0_api_access_token')
    if not auth0_api_access_token:
        client = GetToken(settings.AUTH0_DOMAIN)
        response = client.client_credentials(
            settings.AUTH0_CLIENT_ID,
            settings.AUTH0_CLIENT_SECRET,
            settings.AUTH0_AUDIENCE,
        )
        cache.set(
            'auth0_api_access_token',
            response['access_token'],
            timeout=response['expires_in'],
        )
        auth0_api_access_token = response['access_token']
    auth0 = Auth0(
        settings.AUTH0_DOMAIN,
        auth0_api_access_token,
    )
    return auth0
Exemplo n.º 30
0
def get_auth0():
    auth0_api_access_token = cache.get('auth0_api_access_token')
    if not auth0_api_access_token:
        client = GetToken(settings.AUTH0_DOMAIN)
        response = client.client_credentials(
            settings.AUTH0_CLIENT_ID,
            settings.AUTH0_CLIENT_SECRET,
            settings.AUTH0_AUDIENCE,
        )
        cache.set(
            'auth0_api_access_token',
            response['access_token'],
            timeout=response['expires_in'],
        )
        auth0_api_access_token = response['access_token']
    auth0 = Auth0(
        settings.AUTH0_DOMAIN,
        auth0_api_access_token,
    )
    return auth0
Exemplo n.º 31
0
def get_membercenter_token():
    """
    Retrieve membercenter access_token.

    This also uses the cache so we're not re-instantiating for every update.
    """
    membercenter_api_access_token = cache.get('membercenter_api_access_token')
    if not membercenter_api_access_token:
        client = GetToken(api_settings.AUTH0_DOMAIN)
        response = client.client_credentials(
            api_settings.AUTH0_CLIENT_ID,
            api_settings.AUTH0_CLIENT_SECRET,
            api_settings.AUTH0_AUDIENCE,
        )
        cache.set(
            'membercenter_api_access_token',
            response['access_token'],
            timeout=response['expires_in'],
        )
        membercenter_api_access_token = response['access_token']
    return membercenter_api_access_token