def handle_login(form_data): print "handle_login()" # Authenticate via Okta API to get Session Token user = form_data["username"] password = form_data["password"] session_token = None try: session_token = get_session_token(username=user, password=password) except ValueError as err: print(err.args) print "session_token: {0}".format(session_token) # Use Session Token to generatet OIDC Auth Code URL if (session_token): okta_util = OktaUtil(request.headers, config.okta) oidc_auth_code_url = okta_util.create_oidc_auth_code_url( session_token, config.okta["oidc_client_id"], config.okta["redirect_uri"]) print "url: {0}".format(oidc_auth_code_url) # redirect to User Auth Code URL to Get OIDC Code return redirect(oidc_auth_code_url) else: return make_response(redirect("/"))
def register(): okta_util = OktaUtil(request.headers) first_name = request.form["firstName"] last_name = request.form["lastName"] email = request.form["email"] mobile = request.form["mobile"] password = request.form["password"] user_info = okta_util.create_user(first_name=first_name, last_name=last_name, email=email, phone=mobile, password=password) print user_info user_id = user_info["id"] # Authenticate auth_response = okta_util.authenticate(username=email, password=password) session[okta_util.OKTA_SESSION_TOKEN_KEY] = auth_response["sessionToken"] factor_response = okta_util.create_sms_factor(user_id=user_id, phone_number=mobile) activate_url = factor_response["_links"]["activate"]["href"] # Activate activate_response = okta_util.activate_sms_factor(url=activate_url) return json.dumps(activate_response)
def logout(): print "logout()" okta_util = OktaUtil(request.headers) session_response = okta_util.close_session(session[okta_util.OKTA_SESSION_TOKEN_KEY]) session[okta_util.OKTA_SESSION_ID_KEY] = None return json.dumps(session_response)
def mfa_verification_poll(): print "mfa_verification_poll()" request_json = request.get_json() print "request_json: {0}".format( json.dumps(request_json, indent=4, sort_keys=True)) polling_url = request_json["pollingUrl"] user_name = request_json["userName"] okta_util = OktaUtil(request.headers, config.okta) response = okta_util.execute_get(polling_url, None) if "factorResult" in response: print "factorResult: {0}".format(response["factorResult"]) if response[ "factorResult"] == "SUCCESS": # Means the user successfully passed the factor, so reset the pasword okta_user_id = okta_util.get_user(user_name)["id"] password_reset_response = okta_util.reset_user_password( okta_user_id) print "password_reset_response: {0}".format( json.dumps(password_reset_response, indent=4, sort_keys=True)) response["ott"] = password_reset_response[ "resetPasswordUrl"].replace( "{0}/reset_password/".format(config.okta["org_host"]), "") return json.dumps(response)
def push_mfa_code_no_reset(): print "push_mfa_code_no_reset()" request_json = request.get_json() print "request_json: {0}".format(request_json) okta_util = OktaUtil(request.headers, config.okta) username = request_json["username"] factor_type = request_json["factorType"] verification_url = request_json["verificationUrl"] code = None if "code" in request_json: code = request_json["code"] user = okta_util.get_user(username) # print "user: {0}".format(user, indent=4, sort_keys=True) response = { "status": "success", "message": "sent" } # alwasy send this down so a malicious user can not farm enrolled factors if ("id" in user): okta_user_id = user["id"] if verification_url: #push_response = okta_util.activate_sms_factor_by_id(okta_factor_id, code) #push_response = okta_util.push_factor_verification(okta_user_id, okta_factor_id, code) push_response = okta_util.activate_sms_factor( verification_url, code) print "push_response: {0}".format( json.dumps(push_response, indent=4, sort_keys=True)) # Check for a valid factor result if "factorResult" in push_response: response["factorResult"] = push_response["factorResult"] # check if there is a polling link to send back down to the client if "_links" in push_response: if "poll" in push_response["_links"]: response["pollingUrl"] = push_response["_links"][ "poll"]["href"] print "factorResult: {0}".format(push_response["factorResult"]) if push_response["factorResult"] == "SUCCESS": response["status"] = "success" elif "status" in push_response: print "HAS STATUS" if push_response["status"] == "ACTIVE": response["status"] = "success" response["factorResult"] = "SUCCESS" else: response["status"] = "failed" response["message"] = push_response["errorSummary"] else: print "WARNING: User '{0}' not enrolled in factor: {1}".format( user["profile"]["login"], factor_type) else: print "WARNING: User '{0}' does not exsist in Okta".format(username) return json.dumps(response)
def decorated_function(*args, **kws): """ Decorator fucntion to make endpoint authorization checks easier for read only scopes defined in Okta """ print("authorize_read_access()") authorization_header = None has_access = False # If if "Authorization" in request.headers: authorization_header = request.headers["Authorization"] authorization_token = authorization_header.replace( "Bearer ", "") # Just get the access toke for introspection okta_util = OktaUtil(request.headers, config.okta) introspection_response = okta_util.introspect_oauth_token( authorization_token) # print "introspection_response: {0}".format(json.dumps(introspection_response, indent=4, sort_keys=True)) if "active" in introspection_response: if introspection_response["scope"] == "read_only": has_access = True # print "authorization_header: {0}".format(authorization_header) if has_access: return f(*args, **kws) else: print("Unauthorized") json_response = {"status": "failed"} return json.dumps(json_response, default=default_date_to_string_converter)
def call_read_api(): """ Calls the read_api endpoint as a client server/app would""" print("call_read_api()") # Get Okta OAuth Token access_token = None json_response = {"status": "false", "timestamp": datetime.datetime.now()} okta_util = OktaUtil(request.headers, config.okta) oauth_url = "{0}/oauth2/{1}/v1/token?clientId={2}&grant_type=client_credentials&scope=read_only".format( config.okta["org_host"], config.okta["auth_server_id"], config.okta["oidc_client_id"]) oauth_response = okta_util.execute_post(oauth_url, {}, okta_util.OKTA_OAUTH_HEADERS) print("oauth_response: {0}".format( json.dumps(oauth_response, indent=4, sort_keys=True))) if "access_token" in oauth_response: access_token = oauth_response["access_token"] # print "access_token: {0}".format(access_token) # Use OAuth token in header and request read_api endpoint headers = { "Accept": "application/json", "Content-Type": "application/json", "Authorization": "Bearer {0}".format(access_token) } json_response = okta_util.execute_get( "{0}/read_api".format(config.okta["app_host"]), {}, headers) print("json_response: {0}".format( json.dumps(json_response, default=default_date_to_string_converter))) return json.dumps(json_response, default=default_date_to_string_converter)
def change_password(): """ handler actually change the password, requires the ott""" print "show_change_password()" print "request.form: {0}".format(json.dumps(request.form, indent=4, sort_keys=True)) response = redirect(config.okta["app_host"]) # redirect to home page if there is no ott if "ott" in request.form: ott = request.form["ott"] password = request.form["password"] confirm_password = request.form["confirmPassword"] is_completed = False has_errors = "false" message = "" if password == confirm_password: okta_util = OktaUtil(request.headers, config.okta) verify_ott_response = okta_util.verify_password_reset_token(ott) #print "verify_ott_response: {0}".format(json.dumps(verify_ott_response, indent=4, sort_keys=True)) user = { "id": verify_ott_response["_embedded"]["user"]["id"], "credentials": { "password" : { "value": password } } } change_password_response = okta_util.update_user(user) #print "change_password_response: {0}".format(json.dumps(change_password_response, indent=4, sort_keys=True)) is_completed = True ##test for error on password update""" if 'errorCode' in change_password_response: print "update user error msg = ",change_password_response['errorCauses'] has_errors ="true" is_completed=False else: has_errors = "true" message = "Passwords do not match" response = make_response( render_template("change_password.html", okta_config=config.okta, message=message, is_completed=is_completed, has_errors=has_errors, ott=ott,orgUrls=app.orgUrls)) if is_completed: response = make_response( render_template("password_success.html", okta_config=config.okta, ott=ott, orgUrls=app.orgUrls)) return response
def get_oauth_token(oauth_code): print "get_oauth_token()" okta_util = OktaUtil(request.headers, config.okta) oauth_token_response_json = okta_util.get_oauth_token( oauth_code, config.okta["redirect_uri"]) print "oauth_token_response_json: {0}".format(oauth_token_response_json) return oauth_token_response_json["access_token"]
def get_session_token(username, password): print "get_session_token()" okta_util = OktaUtil(request.headers, config.okta) session_token = None authn_reponse_json = okta_util.get_session_token(username, password) if "sessionToken" in authn_reponse_json: session_token = authn_reponse_json["sessionToken"] return session_token
def refresh_okta_api_token(): """ Helper method to refresh the okta api token when deployed live for continual testing. Helps to prevent the API key from expiring from no use """ print "refresh_okta_api_token()" response = { "status": "fail" } okta_util = OktaUtil(request.headers, config.okta) groups = okta_util.search_groups("Everyone", 1); # Search for the default 'Everyone' group in Okta if len(groups) == 1: response["status"] = "success" return json.dumps(response);
def get_current_user(user_token_data): print "get_current_user()" current_user = None if "uid" in user_token_data: user_id = user_token_data["uid"] print "Looking up user by id: {0}".format(user_id) okta_util = OktaUtil(request.headers, config.okta) current_user = okta_util.get_user(user_id) return current_user
def get_user(): print "get_user()" response = {} try: okta_util = OktaUtil(request.headers) user_info = okta_util.get_curent_user(session[okta_util.OKTA_SESSION_ID_KEY]) print json.dumps(user_info, indent=4, sort_keys=False) response["firstName"] = user_info["profile"]["firstName"] response["lastName"] = user_info["profile"]["lastName"] response["hpsMemberRecords"] = user_info["profile"]["hpsMemberRecords"] except: print "no user logged in" return json.dumps(response)
def activate(): print "activate()" okta_util = OktaUtil(request.headers) response = {"factorResult": "FAILED"} activate_url = request.form["refurl"] pass_code = request.form["passCode"] # Verify sms factor activate_response = okta_util.activate_sms_factor(url=activate_url, pass_code=pass_code) if activate_response["status"] == "ACTIVE": response["factorResult"] = "SUCCESS" return json.dumps(response)
def is_logged_in(): print "is_logged_in()" result = False okta_util = OktaUtil(request.headers, config.okta) # first check there is a token if("token" in request.cookies): token = request.cookies["token"] if token != "" and token != "NO_TOKEN": # introspect token introspection_results_json = okta_util.introspect_oauth_token(token) if("active" in introspection_results_json): result = True return result
def verifyFactor(): print "verifyFactor()" okta_util = OktaUtil(request.headers) verify_url = request.form["refurl"] verification_Value = request.form["passCode"] factor_response = okta_util.factor_verification(verify_url=verify_url, verification_Value=verification_Value) session_response = okta_util.create_session(session[okta_util.OKTA_SESSION_TOKEN_KEY]) session[okta_util.OKTA_SESSION_ID_KEY] = session_response["id"] return json.dumps(factor_response)
def is_logged_in(): print "is_logged_in()" result = {"isLoggedIn": False} try: okta_util = OktaUtil(request.headers) session_response = okta_util.validate_session(session[okta_util.OKTA_SESSION_ID_KEY]) print session_response url = session_response["_links"]["refresh"]["href"] okta_util.extend_session(url) result["isLoggedIn"] = True except: print "not logged in" return json.dumps(result)
def create_user(): print "create_user" okta_util = OktaUtil(request.headers) first_name = request.form["firstName"] last_name = request.form["lastName"] email = request.form["email"] mobile = request.form["mobile"] password = request.form["password"] user_info = okta_util.create_user(first_name=first_name, last_name=last_name, email=email, phone=mobile, password=password) return json.dumps(user_info)
def create_session(): print "create_session()" result = {"success": False} try: okta_util = OktaUtil(request.headers) # Create Session session_response = okta_util.create_session(session[okta_util.OKTA_SESSION_TOKEN_KEY]) session[okta_util.OKTA_SESSION_ID_KEY] = session_response["id"] url = session_response["_links"]["refresh"]["href"] okta_util.extend_session(url) result["success"] = True except: print "failed to create session" return json.dumps(result)
def login(): print "login()" print request.form okta_util = OktaUtil(request.headers, config.okta) # Authenticate via Okta API to get Session Token session_token = None try: if "auth_token" in request.form: session_token = okta_util.authenticate_via_activation_token( request.form["auth_token"]) else: session_token = get_session_token( username=request.form["username"], password=request.form["password"]) except ValueError as err: print(err.args) print "session_token: {0}".format(session_token) # Use Session Token to generatet OIDC Auth Code URL if (session_token): oidc_auth_code_url = okta_util.create_oidc_auth_code_url( session_token, config.okta["oidc_client_id"], config.okta["redirect_uri"]) print "url: {0}".format(oidc_auth_code_url) # redirect to User Auth Code URL to Get OIDC Code return redirect(oidc_auth_code_url) else: error_list = { "messages": [{ "message": "Bad user name and/or password" }] } response = make_response( render_template("index.html", user={}, error_list=error_list, form_data={}, okta_config=config.okta, is_admin=False)) return response
def update_user(user_id): print "update_user" okta_util = OktaUtil(request.headers) first_name = request.form["firstName"] last_name = request.form["lastName"] email = request.form["email"] mobile = request.form["mobile"] hpsMemberRecords = request.form["hpsMemberRecords"] user_info = okta_util.update_user(user_id=user_id, first_name=first_name, last_name=last_name, email=email, phone=mobile, hpsMemberRecords=hpsMemberRecords) return json.dumps(user_info)
def index(): """ handler for the root url path of the app """ print("index()") okta_util = OktaUtil(request.headers) o365_groups = okta_util.get_o365_groups() report = {"data": []} print("Total Groups: {0}".format(len(o365_groups))) for group in o365_groups: group_id = group["id"] users = okta_util.get_users_by_group_id(group_id) print("Total Users for Group: {0}:{1}".format(group["profile"]["name"], len(users))) for user in users: record = {} record["GroupName"] = group["profile"]["name"] record["FirstName"] = user["profile"]["firstName"] record["LastName"] = user["profile"]["lastName"] report["data"].append(record) # prep csv conversion for output csv_data_io = io.StringIO() csv_columns = [ "GroupName", "FirstName", "LastName" ] cw = csv.DictWriter(csv_data_io, fieldnames=csv_columns, dialect='excel') cw.writeheader() for item in report["data"]: cw.writerow(item) response = Response( csv_data_io.getvalue(), mimetype="text/csv", headers={"Content-disposition": "attachment; filename=export.csv"}) return response
def get_current_user_token(): print "get_current_user_token()" user_results_json = None okta_util = OktaUtil(request.headers, config.okta) if ("token" in request.cookies): introspection_results_json = okta_util.introspect_oauth_token( request.cookies.get("token")) if ("active" in introspection_results_json): if (introspection_results_json["active"]): print "Has active token" user_results_json = { "active": introspection_results_json["active"], "username": introspection_results_json["username"], "uid": introspection_results_json["uid"] } else: print "Has inactive token" else: print "has inactive token error" check_okta_session_url = okta_util.create_oidc_auth_code_url( None, config.okta["oidc_client_id"], config.okta["redirect_uri"]) user_results_json = { "active": False, "redirect_url": check_okta_session_url } else: print "has no token" check_okta_session_url = okta_util.create_oidc_auth_code_url( None, config.okta["oidc_client_id"], config.okta["redirect_uri"]) user_results_json = { "active": False, "redirect_url": check_okta_session_url } if (not user_results_json): print "has no token default" user_results_json = {"active": False} return user_results_json
def loginMFA(): print "loginMFA()" okta_util = OktaUtil(request.headers) user = request.form["user"] pwd = request.form["password"] auth = okta_util.authenticate(username=user, password=pwd) try: session[okta_util.OKTA_SESSION_TOKEN_KEY] = auth["sessionToken"] user_id = auth["_embedded"]["user"]["id"] factors = okta_util.list_factors(user_id=user_id) factor_id = factors[0]["id"] push_factor_response = okta_util.push_factor_verification(user_id=user_id, factor_id=factor_id) except: session[okta_util.OKTA_SESSION_TOKEN_KEY] = None user_id = None push_factor_response = {"status":"FAILED", "message":"Authentication Failed"} return json.dumps(push_factor_response)
def login(): print "login()" okta_util = OktaUtil(request.headers) user = request.form["user"] pwd = request.form["password"] auth = okta_util.authenticate(username=user, password=pwd) try: session[okta_util.OKTA_SESSION_TOKEN_KEY] = auth["sessionToken"] user_id = auth["_embedded"]["user"]["id"] session_response = okta_util.create_session(session[okta_util.OKTA_SESSION_TOKEN_KEY]) session[okta_util.OKTA_SESSION_ID_KEY] = session_response["id"] except: session[okta_util.OKTA_SESSION_TOKEN_KEY] = None user_id = None session_response = {"status":"FAILED", "message":"Authentication Failed"} return json.dumps(session_response)
def oidc(): print "oidc()" print request.form redirect_url = "" if("error" in request.form): oauth_token = "NO_TOKEN" redirect_url = config.okta["app_host"] else: okta_util = OktaUtil(request.headers, config.okta) oidc_code = request.form["code"] print "oidc_code: {0}".format(oidc_code) oauth_response = okta_util.get_oauth_token(oidc_code, config.okta["redirect_uri"]) print "oauth_response: {0}".format(json.dumps(oauth_response, indent=4, sort_keys=True)) oauth_token = oauth_response["id_token"] redirect_url = config.okta["post_oidc_redirect"] response = make_response(redirect(redirect_url)) response.set_cookie('token', oauth_token) return response
def mfa_multiple_sms_numbers(): print "mfa_multiple_sms_numbers()" request_json = request.get_json() print "request_json: {0}".format( json.dumps(request_json, indent=4, sort_keys=True)) user_name = request_json["userName"] okta_util = OktaUtil(request.headers, config.okta) user = okta_util.get_user(user_name) print "user: {0}".format(json.dumps(user, indent=4, sort_keys=True)) json_response = {"primary_sms": "", "available_sms_numbers": ""} if "profile" in user: if config.okta["multi_sms_allowed_numbers"] in user["profile"]: json_response["primary_sms"] = user["profile"][ config.okta["multi_sms_primary_number"]] json_response["available_sms_numbers"] = user["profile"][ config.okta["multi_sms_allowed_numbers"]] return json.dumps(json_response)
def show_change_password(): """ handler for the change password screen""" print "show_change_password()" print "request.form: {0}".format(json.dumps(request.form, indent=4, sort_keys=True)) response = redirect(config.okta["app_host"]) # redirect to home page if there is no ott if "ott" in request.form: ott = request.form["ott"] if ott: okta_util = OktaUtil(request.headers, config.okta) message = "" response = make_response( render_template("change_password.html", okta_config=config.okta, message=message, ott=ott, has_errors = "false", orgUrls=app.orgUrls)) return response
def push_mfa_code(): print "push_mfa_code()" request_json = request.get_json() print "request_json: {0}".format(request_json) okta_util = OktaUtil(request.headers, config.okta) username = request_json["username"] factor_type = request_json["factorType"] code = None if "code" in request_json: code = request_json["code"] user = okta_util.get_user(username) # print "user: {0}".format(user, indent=4, sort_keys=True) response = { "status": "success", "message": "sent" } # alwasy send this down so a malicious user can not farm enrolled factors if ("id" in user): okta_user_id = user["id"] okta_factor_id = None enrolled_factors = okta_util.list_factors(okta_user_id) # print "enrolled_factors: {0}".format(json.dumps(enrolled_factors, indent=4, sort_keys=True)) for factor in enrolled_factors: # check factor type agains the enroled factor print "factor: {0}".format( json.dumps(factor, indent=4, sort_keys=True)) if (factor["factorType"] == factor_type and factor["provider"] == "OKTA") or (factor["provider"] == factor_type): okta_factor_id = factor["id"] print "okta_factor_id: {0}".format(okta_factor_id) if okta_factor_id: push_response = okta_util.push_factor_verification( okta_user_id, okta_factor_id, code) # print "push_response: {0}".format(json.dumps(push_response, indent=4, sort_keys=True)) # Check for a valid factor result if "factorResult" in push_response: response["factorResult"] = push_response["factorResult"] # check if there is a polling link to send back down to the client if "_links" in push_response: if "poll" in push_response["_links"]: response["pollingUrl"] = push_response["_links"][ "poll"]["href"] print "factorResult: {0}".format(push_response["factorResult"]) if push_response[ "factorResult"] == "SUCCESS": # Means the user successfully passed the factor, so reset the pasword password_reset_response = okta_util.reset_user_password( okta_user_id) print "password_reset_response: {0}".format( json.dumps(password_reset_response, indent=4, sort_keys=True)) response["ott"] = password_reset_response[ "resetPasswordUrl"].replace( "{0}/reset_password/".format( config.okta["org_host"]), "") else: response["status"] = "failed" response["message"] = push_response["errorSummary"] else: print "WARNING: User '{0}' not enrolled in factor: {1}".format( user["profile"]["login"], factor_type) else: print "WARNING: User '{0}' does not exsist in Okta".format(username) return json.dumps(response)
def push_multi_sms_mfa_code(): print "push_multi_sms_mfa_code()" has_valid_sms = False request_json = request.get_json() print "request_json: {0}".format(request_json) user_name = request_json["username"] selected_sms_number = request_json["smsNumber"] okta_util = OktaUtil(request.headers, config.okta) user = okta_util.get_user(user_name) # print "user: {0}".format(json.dumps(user, indent=4, sort_keys=True)) response = { "status": "success", "message": "sent" } # alwasy send this down so a malicious user can not farm enrolled factors if ("id" in user): okta_user_id = user["id"] okta_factor_id = None # 1) Verify Phone Number is valid in list if "profile" in user: if config.okta["multi_sms_allowed_numbers"] in user["profile"]: if selected_sms_number in user["profile"][ config.okta["multi_sms_allowed_numbers"]]: has_valid_sms = True # 2) Enroll or re-enroll number enrolled_factors = okta_util.list_factors(okta_user_id) print "enrolled_factors: {0}".format( json.dumps(enrolled_factors, indent=4, sort_keys=True)) for factor in enrolled_factors: # check factor type agains the enroled factor if (factor["factorType"] == "sms"): okta_factor_id = factor["id"] break if okta_factor_id: unenroll_factor_response = okta_util.unenroll_factor( okta_user_id, okta_factor_id) # print "unenroll_factor_response: {0}".format(json.dumps(unenroll_factor_response, indent=4, sort_keys=True)) print "selected_sms_number: {0}".format(selected_sms_number) factor_createion_response = okta_util.create_sms_factor( okta_user_id, selected_sms_number) okta_factor_id = factor_createion_response["id"] print "factor_createion_response: {0}".format( json.dumps(factor_createion_response, indent=4, sort_keys=True)) if "_links" in factor_createion_response: if "verify" in factor_createion_response["_links"]: verify_url = factor_createion_response["_links"]["verify"][ "href"] push_factor_response = okta_util.factor_verification( verify_url, None) response["verifyUrl"] = verify_url elif "activate" in factor_createion_response["_links"]: verify_url = factor_createion_response["_links"]["activate"][ "href"] push_factor_response = okta_util.factor_verification( verify_url, None) response["verifyUrl"] = verify_url #push_factor_response = okta_util.push_factor_verification(okta_user_id, okta_factor_id) print "okta_factor_id: {0}".format(okta_factor_id) print "factor_createion_response: {0}".format( json.dumps(factor_createion_response, indent=4, sort_keys=True)) else: print "WARNING: User '{0}' does not exsist in Okta".format(user_name) return json.dumps(response)
def deactivate_user(user_id): okta_util = OktaUtil(request.headers) user_info = okta_util.deactivate_user(user_id=user_id) return json.dumps(user_info)
def list_users(): okta_util = OktaUtil(request.headers) user_list = okta_util.list_users(100) # TODO: make this configurable return json.dumps(user_list)
def reset_hps(): print "reset_hps()" okta_util = OktaUtil(request.headers) response = okta_util.reset_hps() return json.dumps(response)
def get_user_schema(): print "get_user_schema()" okta_util = OktaUtil(request.headers) response = okta_util.list_user_schema() return json.dumps(response)