示例#1
0
def activate_okta_user(user_id):
    users_client = UsersClient(config.org_url, config.token)
    try:
        users_client.activate_user(user_id)
        return user_id
    except Exception as e:
        raise e
class UsersClientTest(unittest.TestCase):

    def setUp(self):
        self.client = UsersClient(os.environ.get('OKTA_TEST_URL'), os.environ.get('OKTA_TEST_KEY'))

    def test_paging(self):
        users = self.client.get_paged_users(limit=1)

        first_page_hit = subsequent_page_hit = False

        for user in users.result:
            first_page_hit = True

        while not users.is_last_page():
            users = self.client.get_paged_users(url=users.next_url)
            for user in users.result:
                subsequent_page_hit = True

        self.assertTrue(first_page_hit and subsequent_page_hit, "The first and subsequent pages weren't hit")

    def test_single_user(self):
        user = User(login='******' + str(random.random()) + '@asdf.com',
                    email='*****@*****.**',
                    firstName='Joe',
                    lastName='Schmoe')
        user = self.client.create_user(user, activate=False)
        self.assertEqual(user.status, "STAGED", "User should be staged")

        user = User(login='******' + str(random.random()) + '@asdf.com',
                    email='*****@*****.**',
                    firstName='Joe',
                    lastName='Schmoe')
        user = self.client.create_user(user, activate=True)
        self.assertEqual(user.status, "PROVISIONED", "User should be provisioned")
示例#3
0
def create_okta_user(data):
    users_client = UsersClient(config.org_url, config.token)
    okta_user = User(login=data['email'],
                     email=data['email'],
                     firstName=data['first_name'],
                     lastName=data['last_name'],
                     password=data['password'])
    try:
        return users_client.create_user(okta_user, activate=False).id
    except Exception as e:
        raise e
示例#4
0
def index():
    if 'okta_token' in session:
        me = okta.get('userinfo')
        user_id = me.data['sub']
        users = UsersClient(
            base_url=app.config['OKTA_BASE_URL'],
            api_token=app.config['OKTA_API_TOKEN'],
        )
        user = json.loads(users.get_path('/{0}'.format(user_id)).text)
        groups = json.loads(users.get_path('/{0}/groups'.format(user_id)).text)
        user['groups'] = groups
        return jsonify(user)
    return redirect(url_for('login'))
class UserGroupsClientTest(unittest.TestCase):

    def setUp(self):
        self.client = UserGroupsClient(os.environ.get('OKTA_TEST_URL'), os.environ.get('OKTA_TEST_KEY'))
        self.user_client = UsersClient(os.environ.get('OKTA_TEST_URL'), os.environ.get('OKTA_TEST_KEY'))

    def test_single_group(self):
        name = 'random_group_' + str(random.random())
        group = UserGroup(name=name, description='something interesting here')
        group = self.client.create_group(group)
        self.assertEqual(group.profile.name, name, "The name for the group wasn't set properly")

    def test_add_user_to_group(self):
        # Create group
        name = 'random_group_' + str(random.random())
        group = UserGroup(name=name, description='something interesting here')
        group = self.client.create_group(group)

        # Create user
        user = User(login='******' + str(random.random()) + '@asdf.com',
                    email='*****@*****.**',
                    firstName='Joe',
                    lastName='Schmoe')
        user = self.user_client.create_user(user, activate=False)

        self.client.add_user_to_group(group, user)
class UserGroupsClientTest(unittest.TestCase):
    def setUp(self):
        self.client = UserGroupsClient(os.environ.get('OKTA_TEST_URL'),
                                       os.environ.get('OKTA_TEST_KEY'))
        self.user_client = UsersClient(os.environ.get('OKTA_TEST_URL'),
                                       os.environ.get('OKTA_TEST_KEY'))

    def test_single_group(self):
        name = 'random_group_' + str(random.random())
        group = UserGroup(name=name, description='something interesting here')
        group = self.client.create_group(group)
        self.assertEqual(group.profile.name, name,
                         "The name for the group wasn't set properly")

    def test_add_user_to_group(self):
        # Create group
        name = 'random_group_' + str(random.random())
        group = UserGroup(name=name, description='something interesting here')
        group = self.client.create_group(group)

        # Create user
        user = User(login='******' + str(random.random()) + '@asdf.com',
                    email='*****@*****.**',
                    firstName='Joe',
                    lastName='Schmoe')
        user = self.user_client.create_user(user, activate=False)

        self.client.add_user_to_group(group, user)
示例#7
0
    def clean_email(self):
        """
        email field validation to check if the username is already in Okta

        """
        readCount = 0
        try:
            usersClient = UsersClient(''.join(['https://', settings.OKTA_ORG]), settings.OKTA_API_TOKEN)
            result = usersClient.get_users(filter_string='profile.login eq "' + self.cleaned_data['email'] + '"')
            readCount = len(result)
        except Exception as e:
            return self.cleaned_data['email']

        if readCount > 0:
            raise forms.ValidationError(_("The username already exists."))

        return self.cleaned_data['email']
示例#8
0
def build_client(test_description):
    url = '{}:{}'.format(sdk_config['mockOkta']['proxy'],
                         sdk_config['mockOkta']['port'])
    return UsersClient(
        base_url=url,
        api_token=sdk_config['mockOkta']['apiKey'],
        headers={
            'x-test-description': test_description
        }
    )
示例#9
0
def _get_okta_users(user_client: UsersClient) -> List[Dict]:
    """
    Get Okta users from Okta server
    :param user_client: user client
    :return: Array of user data
    """
    user_list: List[Dict] = []
    paged_users = user_client.get_paged_users()

    # TODO: Fix bug, we miss last page :(
    while True:
        user_list.extend(paged_users.result)
        if not paged_users.is_last_page():
            # Keep on fetching pages of users until the last page
            paged_users = user_client.get_paged_users(url=paged_users.next_url)
        else:
            break

    return user_list
示例#10
0
    def __init__(self, connection_config, reauth_time, auth_attrib) -> None:
        '''
        Args:
            connection_config (Dict):
                Parameters required to connect to the Okta API
            reauth_time (int):
                The min time in seconds to cache auth requests
            auth_attrib (str):
                The attribute of the user record that will be used to
                authenticate them.
        '''
        super().__init__(reauth_time, auth_attrib)
        connection_config['pathname'] = '/api/v1/users'

        self.usersclient = UsersClient(**connection_config)
        self.factorsclient = FactorsClient(**connection_config)
        self.apiclient = ApiClient(**connection_config)

        # Maintain a per user lookup for poll URL
        self.poll_url = {}
示例#11
0
class UserGroupsClientTest(unittest.TestCase):
    def setUp(self):
        self.client = UserGroupsClient("http://okta.mock.invalid",
                                       "mock-api-key")
        self.user_client = UsersClient("http://okta.mock.invalid",
                                       "mock-api-key")

    @requests_mock.Mocker()
    def test_single_group(self, m):
        name = 'random_group_' + str(random.random())
        m.register_uri("POST",
                       "http://okta.mock.invalid/api/v1/groups/",
                       json={
                           "id": "g0001mock",
                           "profile": {
                               "name": name,
                               "description": "something interesting here"
                           },
                       })
        group = UserGroup(name=name, description="something interesting here")
        group = self.client.create_group(group)
        self.assertEqual(group.profile.name, name,
                         "The name for the group wasn't set properly")

    @requests_mock.Mocker()
    def test_add_user_to_group(self, m):
        # Create group
        m.register_uri("POST",
                       "http://okta.mock.invalid/api/v1/groups/",
                       json={"id": "g0001mock"})
        name = 'random_group_' + str(random.random())
        group = UserGroup(name=name, description='something interesting here')
        group = self.client.create_group(group)

        # Create user
        m.register_uri(
            "POST",
            "http://okta.mock.invalid/api/v1/users/?activate=false",
            json={
                "id": "u0001mock",
                "status": "STAGED",
            },
        )
        user = User(login='******' + str(random.random()) + '@asdf.com',
                    email='*****@*****.**',
                    firstName='Joe',
                    lastName='Schmoe')
        user = self.user_client.create_user(user, activate=False)

        m.register_uri(
            "PUT",
            "http://okta.mock.invalid/api/v1/groups/g0001mock/users/u0001mock",
            json={})
        self.client.add_user_to_group(group, user)
示例#12
0
def get_oidc():
    """
    Connect to okta
    """
    if 'oidc' not in g:
        print('okta: get_oidc call')
        g.oidc = OpenIDConnect(current_app)
        g.okta_client = UsersClient(
            "https://dev-833144.okta.com",
            "00xJ6vTQkI8LzIQcPXf7Ehw75GrdAVDdqA2tvQFxFx")
        # fixing global oidc problem for decorator in rooms
        oidc = g.oidc
    return g.oidc
示例#13
0
def _create_user_client(okta_org, okta_api_key):
    """
    Create Okta User Client
    :param okta_org: Okta organization name
    :param okta_api_key: Okta API key
    :return: Instance of UsersClient
    """
    # https://github.com/okta/okta-sdk-python/blob/master/okta/models/user/User.py
    user_client = UsersClient(
        base_url=f"https://{okta_org}.okta.com/",
        api_token=okta_api_key,
    )

    return user_client
示例#14
0
class UsersClientTest(unittest.TestCase):
    def setUp(self):
        self.client = UsersClient(os.environ.get('OKTA_TEST_URL'),
                                  os.environ.get('OKTA_TEST_KEY'))

    def test_paging(self):
        users = self.client.get_paged_users(limit=1)

        first_page_hit = subsequent_page_hit = False

        for user in users.result:
            first_page_hit = True

        while not users.is_last_page():
            users = self.client.get_paged_users(url=users.next_url)
            for user in users.result:
                subsequent_page_hit = True

        self.assertTrue(first_page_hit and subsequent_page_hit,
                        "The first and subsequent pages weren't hit")

    def test_single_user(self):
        user = User(login='******' + str(random.random()) + '@asdf.com',
                    email='*****@*****.**',
                    firstName='Joe',
                    lastName='Schmoe')
        user = self.client.create_user(user, activate=False)
        self.assertEqual(user.status, "STAGED", "User should be staged")

        user = User(login='******' + str(random.random()) + '@asdf.com',
                    email='*****@*****.**',
                    firstName='Joe',
                    lastName='Schmoe')
        user = self.client.create_user(user, activate=True)
        self.assertEqual(user.status, "PROVISIONED",
                         "User should be provisioned")
示例#15
0
 def setUp(self):
     self.client = UsersClient(os.environ.get('OKTA_TEST_URL'), os.environ.get('OKTA_TEST_KEY'))
示例#16
0
from flask_oidc import OpenIDConnect
from os import environ
from flask import Flask, render_template
from algo import Parse
import sys
import appR

app = Flask(__name__)
app.config["OIDC_CLIENT_SECRETS"] = "client_secrets.json"
app.config["OIDC_COOKIE_SECURE"] = False
app.config["OIDC_CALLBACK_ROUTE"] = "/oidc/callback"
app.config["OIDC_SCOPES"] = ["openid", "email", "profile"]
app.config["SECRET_KEY"] = environ.get("SECRET_KEY")
app.config["OIDC_ID_TOKEN_COOKIE_NAME"] = "oidc_token"
oidc = OpenIDConnect(app)
okta_client = UsersClient("http://dev-363595.okta.com",
                          "006AeB7u4B3zN3IQBYBdXVTluHFvyWucqCqcavGwlt")


@app.before_request
def before_request():
    if oidc.user_loggedin:
        g.user = okta_client.get_user(oidc.user_getfield("sub"))
    else:
        g.user = None


@app.route('/')
def iindex():
    return render_template("index.html")

示例#17
0
from flask import Blueprint, redirect, url_for
from flask_oidc import OpenIDConnect
from okta import UsersClient

bp = Blueprint("auth", __name__, url_prefix="/")
oidc = OpenIDConnect()
okta_client = UsersClient("dev-xxxxx.oktapreview.com",
                          "xxxxxxxxxxxxxxxxxxxxxxxxxxx")


@bp.route("/login")
@oidc.require_login
def login():
    """
    Force the user to login, then redirect them to the dashboard

    """
    return redirect(url_for("blog.dashboard"))


@bp.route("/logout")
def logout():
    """
    Log the user out of their account.

    """
    oidc.logout()
    return redirect(url_for("blog.index"))
示例#18
0
from flask_oidc import OpenIDConnect
from okta import UsersClient
from src.python.services import weatherqueryservice

app = Flask(
    __name__,
    template_folder='/Users/jamiecoupe/PycharmProjects/weatherpy2/web/templates'
)
app.config["OIDC_CLIENT_SECRETS"] = "./data/config/client_secrets.json"
app.config["OIDC_COOKIE_SECURE"] = False
app.config["OIDC_CALLBACK_ROUTE"] = "/oidc/callback"
app.config["OIDC_SCOPES"] = ["openid", "email", "profile"]
app.config[
    "SECRET_KEY"] = "asdansdasdqwergfddfdfdfdfdfdfdfdfdfdfdfddfdfsdfwqlk2342834723842934234qjlwdnalsdaksdlashdja"
oidc = OpenIDConnect(app)
okta_client = UsersClient("https://dev-629582.okta.com",
                          "00xsE71AvAQpNB5MV6QFZbTYdIUBzX5errE0Gj6TqH")


@app.before_request
def before_request():
    if oidc.user_loggedin:
        g.user = okta_client.get_user(oidc.user_getfield("sub"))
    else:
        g.user = None


@app.route("/")
def index():
    return render_template("index.html")

示例#19
0
"""Authentication views and helpers."""

from os import environ

from flask import Blueprint, redirect, url_for
from flask_oidc import OpenIDConnect
from okta import UsersClient

bp = Blueprint("auth", __name__, url_prefix="/")
oidc = OpenIDConnect()
okta_client = UsersClient(environ.get("OKTA_ORG_URL"),
                          environ.get("OKTA_AUTH_TOKEN"))


@bp.route("/login")
@oidc.require_login
def login():
    """
    Force the user to login, then redirect them to the dashboard.
    """
    return redirect(url_for("blog.dashboard"))


@bp.route("/logout")
def logout():
    """
    Log the user out of their account.
    """
    oidc.logout()
    return redirect(url_for("blog.index"))
示例#20
0
 def setUp(self):
     self.client = UsersClient(os.environ.get('OKTA_TEST_URL'),
                               os.environ.get('OKTA_TEST_KEY'))
示例#21
0
import time
from okta import UsersClient
from okta import FactorsClient

site = 'Your Site'
skey = 'Your Key'

usersClient = UsersClient(site, skey)
factorClient = FactorsClient(site, skey)

currentDate = time.strftime('%Y%m%d')

lst = []
users = usersClient.get_paged_users()
while True:
    for user in users.result:
        if user.status == 'ACTIVE':  # Get only active users
            lst.append(user)

    if not users.is_last_page():
        # Keep on fetching pages of users until the last page
        users = usersClient.get_paged_users(url=users.next_url)
    else:
        break

EnrolledUsers = open('C:\\temp\\EnrolledUsers' + currentDate + '.csv', 'w+')
EnrolledUsers.write(
    "Username,FactorType,UserID,DateEnrolled,TimeEnrolled")  # Set CSV Headers

for user in lst:
    lifecycle = factorClient.get_lifecycle_factors(user_id=user.id)
示例#22
0
文件: app.py 项目: cewhitsett/PDA
from config import login_token, def_user, org_url

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////tmp/pda.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)

app.config["OIDC_CLIENT_SECRETS"] = "client_secrets.json"
app.config["OIDC_COOKIE_SECURE"] = False
app.config["OIDC_CALLBACK_ROUTE"] = "/oidc/callback"
app.config["OIDC_SCOPES"] = ["openid", "email", "profile"]
app.config["SECRET_KEY"] = "abcd"
app.config["OIDC_ID_TOKEN_COOKIE_NAME"] = "oidc_token"

oidc = OpenIDConnect(app)
okta_client = UsersClient(org_url, login_token)


# Deletes the database. Mostly for testing
def delete_it():
    db.reflect()
    db.drop_all()


# Creates a couple entries in the database for testing.
def create_it():
    db.create_all()

    for i in range(5):
        j = Journal(name=str(i), desc="My {} item".format(i), user=def_user)
示例#23
0
# Okta API Key for simple-flask-app (web app)
OKTA_API_KEY        = '00_28BIjc5iOGlb-QwMGK3CaNmovLbWMjCeJoN3j5Q'
OKTA_ORG_URL        = 'https://dev-548896.oktapreview.com'


## ----- APP CONFIGURATION ----- ##

app = Flask(__name__)
app.config["OIDC_CLIENT_SECRETS"] = "client_secrets.json"
app.config["OIDC_COOKIE_SECURE"] = False
app.config["OIDC_CALLBACK_ROUTE"] = "/oidc/callback"
app.config["OIDC_SCOPES"] = ["openid", "email", "profile"]
app.config["SECRET_KEY"] = FLASK_SECRET_KEY
app.config["OIDC_ID_TOKEN_COOKIE_NAME"] = "oidc_token"
oidc = OpenIDConnect(app)
okta_client = UsersClient(OKTA_ORG_URL, OKTA_API_KEY)


## ----- APP DEFINITIONS ----- ##

@app.before_request
def before_request():
    if oidc.user_loggedin:
        g.user = okta_client.get_user(oidc.user_getfield("sub"))
    else:
        g.user = None


@app.route("/")
def index():
    return render_template("index.html")
示例#24
0
# Create an instance of the Flask class that is the WSGI application.
# The first argument is the name of the application module or package,
# typically __name__ when using a single module.
app = Flask(__name__)
app.debug = True
app.config["OIDC_CLIENT_SECRETS"] = "exclude/client_secrets.json"
app.config["OIDC_COOKIE_SECURE"] = False
#allows you to test out user login and registration in development without using SSL. If you were going to run your site publicly, you would remove this option and use SSL on your site.
app.config["OIDC_CALLBACK_ROUTE"] = "/oidc/callback"
app.config["OIDC_SCOPES"] = ["openid", "email", "profile"]
app.config["SECRET_KEY"] = "aa"
oidc = OpenIDConnect(app)
oidc.init_app(app)

okta_client = UsersClient("https://dev-711513.oktapreview.com",
                          "00-96K0PI5EgQUBFwFDwoBn9JObfyu4p6wfmFdlxjO")


@app.before_request
def before_request():
    if oidc.user_loggedin:
        g.user = okta_client.get_user(oidc.user_getfield("sub"))
    else:
        g.user = None


# Flask route decorators map / and /hello to the hello function.
# To add other resources, create functions that generate the page contents
# and add decorators to define the appropriate resource locators for them.

示例#25
0
        'token_uri': f'{os.getenv("OKTA_ORG_URL")}/oauth2/default/v1/token',
        'issuer': f'{os.getenv("OKTA_ORG_URL")}/oauth2/default',
        'userinfo_uri':
        f'{os.getenv("OKTA_ORG_URL")}/oauth2/default/v1/userinfo',
        'redirects_uris': os.getenv('OIDC_REDIRECT_URIS')
    }
}
with open('client_secrets.json', 'w') as fp:
    json.dump(client_secrets, fp)
app.config['OIDC_CLIENT_SECRETS'] = 'client_secrets.json'
app.config['OIDC_COOKIE_SECURE'] = os.getenv('OIDC_COOKIE_SECURE')
app.config['OIDC_CALLBACK_ROUTE'] = os.getenv('OIDC_CALLBACK_ROUTE')
app.config['OIDC_SCOPES'] = ["openid", "email", "profile"]
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
oidc = OpenIDConnect(app)
okta_client = UsersClient(os.getenv('OKTA_ORG_URL'),
                          os.getenv('OKTA_AUTH_TOKEN'))

# Client for Google's Datastore
datastore_client = datastore.Client()

# Instantiates a Google logging client
logging_client = google.cloud.logging.Client()

# Retrieves a Cloud Logging handler based on the environment
# you're running in and integrates the handler with the
# Python logging module. By default this captures all logs
# at INFO level and higher
logging_client.get_default_handler()
logging_client.setup_logging()

示例#26
0
from os import environ

from flask import Blueprint, redirect, url_for
from flask_oidc import OpenIDConnect
from okta import UsersClient


bp = Blueprint("auth", __name__, url_prefix="/")
oidc = OpenIDConnect()
okta_client = UsersClient("https://dev-407714.okta.com/", "token")


@bp.route("/login")
@oidc.require_login
def login():
    """
    Force the user to login, then redirect them to the dashboard.
    """
    return redirect(url_for("blog.dashboard"))


@bp.route("/logout")
def logout():
    """
    Log the user out of their account.
    """
    oidc.logout()
    return redirect(url_for("blog.index"))
示例#27
0
from flask import Flask, render_template, g, redirect, url_for, json
from flask_oidc import OpenIDConnect
from okta import UsersClient
import requests

app = Flask(__name__)
app.config["OIDC_CLIENT_SECRETS"] = "client_secrets.json"
app.config["OIDC_COOKIE_SECURE"] = False
app.config["OIDC_CALLBACK_ROUTE"] = "/oidc/callback"
app.config["OIDC_SCOPES"] = ["openid", "email", "profile", "contacts"]
app.config["SECRET_KEY"] = "Secret key"
app.config["OIDC_ID_TOKEN_COOKIE_NAME"] = "oidc_token"
oidc = OpenIDConnect(app)
okta_client = UsersClient("https://dev-685287.okta.com",
                          "00pnofetVEDO7BzxPltCb1pmASZRkxROKYD03gnESE")


@app.before_request
def before_request():
    if oidc.user_loggedin:
        g.user = okta_client.get_user(oidc.user_getfield("sub"))
        #print("my id is ", + g.user.id)
    else:
        g.user = None


@app.route("/")
def index():
    return render_template("index.html")

示例#28
0
 def setUp(self):
     self.client = UserGroupsClient("http://okta.mock.invalid",
                                    "mock-api-key")
     self.user_client = UsersClient("http://okta.mock.invalid",
                                    "mock-api-key")
示例#29
0
mysql = mysql.connector.connect(host="localhost",
                                user="******",
                                passwd="root",
                                database="HiringInceptors",
                                auth_plugin="mysql_native_password")

app = Flask(__name__)
app.config["OIDC_CLIENT_SECRETS"] = "clients_secrets.json"
app.config["OIDC_COOKIE_SECURE"] = False
app.config["OIDC_CALLBACK_ROUTE"] = "/end/callback"
app.config["OIDC_SCOPES"] = ["openid", "email", "profile"]
app.config["OIDC_ID_TOKEN_COOKIE_NAME"] = "oidc_token"
app.config["SECRET_KEY"] = "{{ LONG_RANDOM_STRING }}"

oidc = OpenIDConnect(app)
okta_client = UsersClient("https://dev-764808.okta.com",
                          "00eyvjQ5-edxVO-whsoxWbORgbfr7kc--8cuSckLzZ")


def create_table():
    cur = mysql.cursor()
    cur.execute(
        'create table if not exists job_list(job_id int(7) primary key Auto_Increment, job_title varchar(20), job_description varchar(200), job_skills varchar(20) );'
    )
    cur.execute(
        'create table if not exists applicant(id int(7) primary key Auto_Increment,email varchar(100) , password varchar(20), firstname varchar(200), lastname varchar(200) );'
    )
    cur.execute(
        'create table if not exists recruiter(id int(7) primary key Auto_Increment,email varchar(100) , password varchar(20), firstname varchar(200), lastname varchar(200) );'
    )
    cur.execute(
        'create table if not exists resume( applicant_id varchar(10) ,  fullname varchar(30),education varchar(150) , phone varchar(11) ,email varchar(20),job_skills varchar(100),projects varchar(100), experience varchar(10));'
示例#30
0
from okta import UsersClient
import env



app = Flask(__name__)

app.config["OIDC_CLIENT_SECRETS"] = "client_secrets.json"
app.config["OIDC_COOKIE_SECURE"] = False
app.config["OIDC_CALLBACK_ROUTE"] = "/oidc/callback"
app.config["OIDC_SCOPES"] = ["openid", "email", "profile"]
app.config["SECRET_KEY"] = env.SECRET_KEY
app.config["OIDC_ID_TOKEN_COOKIE_NAME"] = "oidc_token"
oidc = OpenIDConnect(app)

okta_client = UsersClient(env.URL, env.API_TOKEN)




@app.before_request
def before_request():
    if oidc.user_loggedin:
        g.user = okta_client.get_user(oidc.user_getfield("sub"))
    else:
        g.user = None


@app.route('/')
def index():
    return render_template('index.html')
示例#31
0
class AuthClient(BaseAuthClient):
    def __init__(self, connection_config, reauth_time, auth_attrib) -> None:
        '''
        Args:
            connection_config (Dict):
                Parameters required to connect to the Okta API
            reauth_time (int):
                The min time in seconds to cache auth requests
            auth_attrib (str):
                The attribute of the user record that will be used to
                authenticate them.
        '''
        super().__init__(reauth_time, auth_attrib)
        connection_config['pathname'] = '/api/v1/users'

        self.usersclient = UsersClient(**connection_config)
        self.factorsclient = FactorsClient(**connection_config)
        self.apiclient = ApiClient(**connection_config)

        # Maintain a per user lookup for poll URL
        self.poll_url = {}

    def _get_okta_userid(self, username):
        user = self.usersclient.get_users(query=username, limit=1)

        try:
            return user[0].id
        except Exception as error:
            logging.error('Error getting username {}'.format(error))
            return None

    def _get_factors(self, userid):
        try:
            return self.factorsclient.get_lifecycle_factors(userid)
        except Exception as error:
            logging.error('Error getting factors {}'.format(error))
            return None

    def can_auth(self, user):
        # type: () -> bool
        # Check Okta user for a push factor.
        # Returns false is not available
        # Returns factor Id if it is
        # TODO: Add support for other types of auth (TOTP, etc).
        username = self._auth_attribute(user)
        if username is not False:
            logging.debug('Checking auth capabilities for {}'.format(username))

            okta_user_id = self._get_okta_userid(username)
            factors = self._get_factors(okta_user_id)
            if factors is not None:
                for factor in factors:
                    if factor.factorType == 'push':
                        return factor.id

        return False

    def auth(self, user, reason=None):
        # type: (str) -> None
        logging.debug('Sending Okta Push request for {}'.format(
            self._auth_attribute(user)))

        # Okta's SDK is broken!
        # https://github.com/okta/okta-sdk-python/issues/66
        # res = self.factorsclient.verify_factor(
        #    user_id=self.okta_user_id,
        #    user_factor_id=self.okta_push_factor_id
        # )
        # Implement our own call which actually works
        okta_user_id = self._get_okta_userid(self._auth_attribute(user))
        res = self.apiclient.post_path('/{0}/factors/{1}/verify'.format(
            okta_user_id, user._factor_id))
        try:
            res_obj = json.loads(res.text)
        except Exception as error:
            raise AuthException(error)

        self.poll_url[okta_user_id] = res_obj['_links']['poll']['href']
        user._last_auth_state = AuthStates.PENDING

    def auth_status(self, user):
        # type: () -> int
        okta_user_id = self._get_okta_userid(self._auth_attribute(user))

        if user._last_auth_state == AuthStates.PENDING:
            response = self.apiclient.get(self.poll_url[okta_user_id])
            response_obj = json.loads(response.text)
            res = response_obj['factorResult']
            if res != 'WAITING':
                if res == 'SUCCESS':
                    user._last_auth_state = AuthStates.AUTHORIZED
                    user._last_auth_time = datetime.now(tz=pytz.utc)
                else:
                    user._last_auth_state = AuthStates.DENIED
                    user._last_auth_time = datetime.min
        elif user._last_auth_state == AuthStates.AUTHORIZED:
            if not self._recently_authed(user):
                user._last_auth_state = AuthStates.NONE
        return user._last_auth_state

    def reset(self, user):
        okta_user_id = self._get_okta_userid(self._auth_attribute(user))
        self.poll_url.pop(okta_user_id, None)
        user._last_auth_state = AuthStates.NONE
示例#32
0
from flask import Flask, render_template, g, redirect, url_for, request
from flask_oidc import OpenIDConnect
from okta import UsersClient
import requests

app = Flask(__name__)
app.config["OIDC_CLIENT_SECRETS"] = "client_secrets.json"
app.config["OIDC_COOKIE_SECURE"] = False
app.config["OIDC_CALLBACK_ROUTE"] = "/oidc/callback"
app.config["OIDC_SCOPES"] = ["openid", "email", "profile"]
app.config["SECRET_KEY"] = "secret"
app.config["OIDC_ID_TOKEN_COOKIE_NAME"] = "oidc_token"
oidc = OpenIDConnect(app)
okta_client = UsersClient("https://{{OKTA_DOMAIN}}", "{{OKTA_AUTH_TOKEN}}")

# user-id mapping
user_id = {"alice": "1001", "bob": "1002", "john": "1003", "jane": "1004"}

# mapping of the users the logged-in user is allowed to see
# this mapping is used to list the buttons on the dashboard
views = {"Alice Opa": ["alice", "bob", "john"], "Bob Rego": ["bob"], "John Opa": ["john"], "Jane Opa": ["jane"]}


@app.before_request
def before_request():
    if oidc.user_loggedin:
        g.user = okta_client.get_user(oidc.user_getfield("sub"))
    else:
        g.user = None

示例#33
0
import requests
import config
import json

app = Flask(__name__)
app.config.update({
    'SECRET_KEY': config.okta_client_secret,
    'OIDC_CLIENT_SECRETS': './client_secrets.json',
    'OIDC_DEBUG': True,
    'OIDC_ID_TOKEN_COOKIE_SECURE': False,
    'OIDC_SCOPES': ["openid", "profile"],
    'OIDC_CALLBACK_ROUTE': config.okta_callback_route
})

oidc = OpenIDConnect(app)
okta_client = UsersClient(config.okta_org_url, config.okta_auth_token)


# Fetch Okta user record if logged in
@app.before_request
def before_request():
    if oidc.user_loggedin:
        g.user = okta_client.get_user(oidc.user_getfield('sub'))
    else:
        g.user = None


# Main application route
@app.route('/')
def start():
    return redirect(url_for(".box_auth"))
示例#34
0
from flask import Flask, render_template, g, redirect, url_for
from flask_cors import CORS
from flask_oidc import OpenIDConnect
from okta import UsersClient

app = Flask(__name__)
CORS(app)

app.config["OIDC_CLIENT_SECRETS"] = "client_secrets.json"
app.config["OIDC_COOKIE_SECURE"] = False
app.config["OIDC_CALLBACK_ROUTE"] = "/oidc/callback"
app.config["OIDC_SCOPES"] = ["openid", "email", "profile"]
app.config["SECRET_KEY"] = "HalloBJKIsTheBest"
oidc = OpenIDConnect(app)
okta_client = UsersClient("https://dev-375036.okta.com",
                          "00MIStcQpRWVq7IcwuSbqT61DGw5piXGatgFcHv6Yo")


@app.before_request
def before_request():
    if oidc.user_loggedin:
        g.user = okta_client.get_user(oidc.user_getfield("sub"))
    else:
        g.user = None


@app.route("/")
def index():
    return render_template("index.html")