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(): token = get_auth0_token() client = Auth0( settings.AUTH0_DOMAIN, token['access_token'], ) return client
def get_user_from_management_api(user_id): domain = auth0_api_settings.MANAGEMENT_API['AUTH0_DOMAIN'] management_api_token = get_management_api_token() auth0 = Auth0(domain, management_api_token) return auth0.users.get(user_id)
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
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", }
def user_post_save(sender, instance=None, created=False, raw=False, **kwargs): """Create Auth0 from user and send verification email.""" if not raw: if created: if instance.person: token = get_auth0_token() auth0 = Auth0( settings.AUTH0_DOMAIN, token, ) create_user_payload = { "connection": "email", "email": instance.email, "email_verified": True, "user_metadata": { "name": instance.person.name }, "app_metadata": { "bhs_id": instance.person.bhs_id } } try: response = auth0.users.create(create_user_payload) except Auth0Error as e: if 'The user already exists' in e.message: return else: raise (e) instance.auth0_id = response['user_id'] instance.save()
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
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}
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)
def get_auth0_client() -> Auth0: token = GetToken(AUTH0_DOMAIN).client_credentials( AUTH0_CLIENT_ID, str(AUTH0_CLIENT_SECRET), f"https://{AUTH0_DOMAIN}/api/v2/", ) mgmt_api_token = token["access_token"] return Auth0(AUTH0_DOMAIN, mgmt_api_token)
def client(self): if self._client and self._token: return self._client # Check token is valid self._token = self.get_token() self._client = Auth0(self.domain, self._token) return self._client
def ban_user(user): params = request.json ban_user_id = params['ban_user_id'] mgmt_api_token = get_token() auth0 = Auth0(current_app.config['AUTH0_DOMAIN'], mgmt_api_token) body = {"blocked": True} auth0.users.update(ban_user_id, body) return {"status": "success"}
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
def user_pre_delete(sender, instance, **kwargs): if instance.auth0_id: token = get_auth0_token() auth0 = Auth0( settings.AUTH0_DOMAIN, token, ) auth0.users.delete(instance.auth0_id) return
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
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
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"], }
def setup_mgmt(cfg: dict): """ Initialise the Auth0 management API. :param cfg: configuration """ global config config = cfg global mgmt_api_token mgmt_api_token = get_mgmt_api_token() global auth0_mgmt auth0_mgmt = Auth0(config[AUTH0_DOMAIN], mgmt_api_token)
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
async def get_users_by_ids(self, ids: List[str]) -> List[Optional[User]]: """Return a list of users from auth0 api.""" auth0 = Auth0(self.settings.domain, await self.management_token_fetcher.get_token()) id_repr = lambda user_id: f'"{user_id}"' q = "user_id:{}".format(" OR ".join( id_repr(user_id) for user_id in ids)) users_structs = await asyncio.to_thread(auth0.users.list, q=q) return [ User(id=struct["user_id"], name=struct["name"]) if struct else None for struct in Loader.fillBy(ids, users_structs["users"], lambda s: s["user_id"]) ]
def get_user_profile(event, _context): """ Gets the user profile from Auth0 by a given user_id. """ auth0 = Auth0(os.getenv('AUTH0_DOMAIN'), os.getenv('AUTH0_TOKEN')) user_id = event['pathParameters']['user_id'] try: user_profile = auth0.users.get(user_id) response = {'statusCode': 200, 'body': json.dumps(user_profile)} except Auth0Error as err: response = {'statusCode': err.status_code, 'body': err.message} return response
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)
def update_auth0_id(user): token = get_auth0_token() auth0 = Auth0( settings.AUTH0_DOMAIN, token, ) result = auth0.users.list( search_engine='v2', q='email:"{0}"'.format(user.email), ) if result['length'] != 1: return log.error("Error {0}".format(user)) auth0_id = result['users'][0]['user_id'] user.auth0_id = auth0_id user.save() return log.info("Updated {0}".format(user))
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 create_authzero_application(authzero_domain, authzero_token): mgmt_api_token = authzero_token auth0 = Auth0(authzero_domain, mgmt_api_token) params = dict() params['name'] = 'spoke{}'.format(str(randrange(1, 99))) params['description'] = 'Spoke Authentication' params['app_type'] = 'spa' params['callbacks'] = list() params['callbacks'].append( 'https://{}.herokuapp.com/login-callback'.format(session['app_name'])) params['callbacks'].append('http://{}.herokuapp.com/login-callback'.format( session['app_name'])) params['allowed_logout_urls'] = list() params['allowed_logout_urls'].append( 'https://{}.herokuapp.com/logout-callback'.format(session['app_name'])) params['allowed_logout_urls'].append( 'http://{}.herokuapp.com/logout-callback'.format(session['app_name'])) params['web_origins'] = list() params['web_origins'].append('https://{}.herokuapp.com'.format( session['app_name'])) params['web_origins'].append('http://{}.herokuapp.com'.format( session['app_name'])) params['allowed_origins'] = list() params['allowed_origins'].append('https://*.{}.herokuapp.com'.format( session['app_name'])) params['allowed_origins'].append('http://*.{}.herokuapp.com'.format( session['app_name'])) params['oidc_conformant'] = False spoke_app_client = auth0.clients.create(params) rule_params = dict() rule_params['name'] = 'spokeuser{}'.format(str(randrange(1, 99))) rule_params[ 'script'] = 'function (user, context, callback) {context.idToken["https://spoke/user_metadata"] = user.user_metadata; callback(null, user, context);}' rule_params['enabled'] = True rule_success = auth0.rules.create(rule_params) return spoke_app_client
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) } }
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
def bind(): if 'profile' not in session: return redirect('login_auth0') if not discord.authorized: return redirect('login_discord') domain = os.getenv('AUTH_DOMAIN') client_id = os.getenv('AUTH_CLIENT_ID') client_secret = os.getenv('AUTH_CLIENT_SECRET') get_token = GetToken(domain) token = get_token.client_credentials( client_id, client_secret, 'https://{}/api/v2/'.format(domain))['access_token'] mgmt = Auth0(domain, token) userlist = mgmt.users.list( q=f'user_metadata.discord_id:"{str(discord.fetch_user().id)}"') if userlist['length'] == 0: mgmt.users.update( session['profile']['user_id'], {'user_metadata': { 'discord_id': str(discord.fetch_user().id) }}) out = f"{session['profile']['name']}'s CodeDay account has been successfully associated with the Discord account \ {discord.fetch_user().username}#{discord.fetch_user().discriminator}! \n\ Please close this window" DiscordWebhook( url=webhookurl, content=f'a~update <@{str(discord.fetch_user().id)}>').execute() elif userlist['length'] == 1: if userlist['users'][0]['user_id'] == session['profile']['user_id']: out = "Your account has already been linked!" else: out = '''This Discord account has already been linked to a CodeDay account. If this was in error, please contact a staff member''' else: out = '''An unhandled error occurred linking your accounts. Please contact a staff member so we can resolve the issue''' session.clear() return out
def role_deletion(): role_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('auth0|5d6d8e3a674ade0f285b8f10') except exceptions.Auth0Error: return {'resp': {'error': 'Role doesn\'t exist'}} return { 'resp': { 'success': 'Role {0} is successfully deleted'.format(role_id) } }
def __init__(self) -> None: domain = secrets.get_secret("auth0_api_domain") client_id = secrets.get_secret("auth0_api_client_id") client_secret = secrets.get_secret("auth0_api_client_secret") if not domain: raise ValueError( "Missing required domain for Auth0 Management API") if not client_id: raise ValueError( "Missing required client_id for Auth0 Management API") if not client_secret: raise ValueError( "Missing required client_secret for Auth0 Management API") self._domain = domain self._client_id = client_id self._client_secret = client_secret self.audience = f"https://{self._domain}/api/v2/" self.client = Auth0(self._domain, self.access_token)