示例#1
0
def init_app(name=None):
    name = name or __name__
    app = Flask(name)
    app.config.from_pyfile('application.cfg')
    app.config.from_pyfile('production.cfg')

    app.jinja_env.globals['GIT_HASH'] = get_git_hash()

    #app.ldap_orm = Connection(app.config['LDAP_URL'], app.config['LDAP_BIND_DN'], app.config['LDAP_BIND_PW'], auto_bind=True)
    server = Server(app.config['LDAP_URL'], get_info=ALL)
    app.ldap_conn = Connection(server,
                               app.config['LDAP_BIND_DN'],
                               app.config['LDAP_BIND_PW'],
                               auto_bind=True)
    model.ldap_conn = app.ldap_conn
    model.base_dn = app.config['LDAP_BASE_DN']

    from .model import db
    db.init_app(app)
    with app.app_context():
        db.create_all()

    app.babel = Babel(app)
    init_oauth2(app)
    app.login_manager = LoginManager(app)

    #init hydra admin api
    hydra_config = hydra.Configuration(
        host=app.config['HYDRA_ADMIN_URL'],
        username=app.config['HYDRA_ADMIN_USER'],
        password=app.config['HYDRA_ADMIN_PASSWORD'])
    hydra_client = hydra.ApiClient(hydra_config)
    app.hydra_api = hydra.AdminApi(hydra_client)

    from .views import auth_views, frontend_views, init_login_manager, api_views, pki_views, admin_views
    init_login_manager(app)
    app.register_blueprint(auth_views)
    app.register_blueprint(frontend_views)
    app.register_blueprint(api_views)
    app.register_blueprint(pki_views)
    app.register_blueprint(admin_views)

    @app.before_request
    def befor_request():
        request_start_time = time.time()
        g.request_time = lambda: "%.5fs" % (time.time() - request_start_time)

    from .translations import init_babel

    init_babel(app)

    app.lenticular_services = {}
    for service_name, service_config in app.config[
            'LENTICULAR_CLOUD_SERVICES'].items():
        app.lenticular_services[service_name] = model.Service.from_config(
            service_name, service_config)

    app.pki = Pki(app.config['PKI_PATH'], app.config['DOMAIN'])

    return app
示例#2
0
    def dispatch_request(self):
        form = ConsentForm()

        challenge = request.args.get(
            "consent_challenge") or form.challenge.data
        if not challenge:
            abort(400)

        with ory_hydra_client.ApiClient(configuration) as api_client:
            hydra = ory_hydra_client.AdminApi(api_client)
            consent_request = hydra.get_consent_request(challenge)
            form.requested_scope.choices = [
                (s, s) for s in consent_request.requested_scope
            ]

            session = {
                "access_token": {},
                "id_token": {
                    "sub": "248289761001",
                    "name": "Jane Doe",
                    "given_name": "Jane",
                    "family_name": "Doe",
                    "preferred_username": "******",
                    "email": "*****@*****.**",
                    "picture": "",
                },
            }

            if request.method == "GET":
                return self.get(form, consent_request, session, hydra)
            elif request.method == "POST":
                return self.post(form, consent_request, session, hydra)
            abort(405)
def rjct_consent_challenge():
    def reject_consent_challenge(api_instance: AdminApi,
                                 consent_challenge: str):
        body = ory_hydra_client.RejectRequest()
        api_response = api_instance.reject_consent_request(consent_challenge,
                                                           body=body)
        return {'redirectUrl': api_response.redirect_to}

    configuration = ory_hydra_client.Configuration(
        os.environ.get('HYDRA_ADMIN_SERVER'))

    try:
        consent_challenge = request.get_json()['consentChallenge']

        if not consent_challenge:
            abort(400)

        with ory_hydra_client.ApiClient(configuration) as api_client:
            api_instance = ory_hydra_client.AdminApi(api_client)
            return reject_consent_challenge(api_instance, consent_challenge)

    except KeyError:
        logging.error(
            f'There was an error when getting value by key in request body')
    except ApiException as api_exception:
        logging.error(f'An ApiException occurred: {api_exception.reason}')
def login_challenge():
    def reject_login_request(api_instance: AdminApi, login_challenge):
        # this function has to be tested
        body = ory_hydra_client.RejectRequest()
        api_response = api_instance.reject_login_request(login_challenge,
                                                         body=body)
        return {'redirectUrl': api_response.redirect_to}

    def accept_login_request(api_instance: AdminApi, login_challenge, subject):
        # subject must be equal to the user's id genereted by ory kratos
        # if remember is not set loging out may not work as expected!!!
        body = ory_hydra_client.AcceptLoginRequest(subject=subject,
                                                   remember=True,
                                                   remember_for=3600)
        api_response = api_instance.accept_login_request(login_challenge,
                                                         body=body)
        return {'redirectUrl': api_response.redirect_to}

    req_json = request.get_json()
    configuration = ory_hydra_client.Configuration(
        os.environ.get('HYDRA_ADMIN_SERVER'))

    try:
        login_challenge = req_json['loginChallenge']
        if not login_challenge:
            abort(400)

        with ory_hydra_client.ApiClient(configuration) as api_client:
            api_instance = ory_hydra_client.AdminApi(api_client)
            # the response has the property skip.
            # further information is in the documentation
            # response: LoginRequest = api_instance.get_login_request(login_challenge)
            kratos_url = os.environ.get('KRATOS_SERVER')
            res_whoami = requests.get(f'{kratos_url}/sessions/whoami',
                                      cookies=request.cookies)

            if res_whoami.status_code == 401:
                return reject_login_request(api_instance, login_challenge)
            elif (res_whoami.json() and 'active' in res_whoami.json()
                  and res_whoami.json()['active'] is True):

                subject = res_whoami.json()['identity']['id']
                return accept_login_request(api_instance, login_challenge,
                                            subject)

            else:
                return reject_login_request(api_instance, login_challenge)
    except KeyError:
        logging.error('There was an error when trying to get value by key.')
        abort(400)
    except ApiException:
        logging.error('An ApiException occurred.')
        abort(400)
def consent_challenge():
    def reject_consent_challenge(api_instance: AdminApi,
                                 consent_challenge: str):
        body = ory_hydra_client.RejectRequest()
        api_response = api_instance.reject_consent_request(consent_challenge,
                                                           body=body)
        return {'redirectUrl': api_response.redirect_to}

    def accept_consent_challenge(api_instance: AdminApi,
                                 consent_challenge: str, requested_scope):
        body = ory_hydra_client.AcceptConsentRequest(
            grant_scope=requested_scope, remember=True, remember_for=3600)
        api_response = api_instance.accept_consent_request(consent_challenge,
                                                           body=body)
        return {'redirectUrl': api_response.redirect_to}

    req_json = request.get_json()
    configuration = ory_hydra_client.Configuration(
        os.environ.get('HYDRA_ADMIN_SERVER'))

    try:
        consent_challenge = req_json['consentChallenge']

        if not consent_challenge:
            abort(400)

        with ory_hydra_client.ApiClient(configuration) as api_client:
            api_instance = ory_hydra_client.AdminApi(api_client)
            api_response = api_instance.get_consent_request(consent_challenge)
            kratos_url = os.environ.get('KRATOS_SERVER')
            res_whoami = requests.get(f'{kratos_url}/sessions/whoami',
                                      cookies=request.cookies)

            if res_whoami.status_code == 401:
                return reject_consent_challenge(api_instance,
                                                consent_challenge)
            elif (res_whoami.json() and 'active' in res_whoami.json()
                  and res_whoami.json()['active'] is True):

                requested_scope = api_response.requested_scope
                return accept_consent_challenge(api_instance,
                                                consent_challenge,
                                                requested_scope)
            else:
                return reject_consent_challenge(api_instance,
                                                consent_challenge)

    except KeyError:
        logging.error(
            f'There was an error when getting value by key in request body')
    except ApiException as api_exception:
        logging.error(f'An ApiException occured: {api_exception.reason}')
示例#6
0
    def dispatch_request(self):
        form = LoginForm()

        challenge = request.args.get("login_challenge") or form.challenge.data
        if not challenge:
            abort(400)

        with ory_hydra_client.ApiClient(configuration) as api_client:
            hydra = ory_hydra_client.AdminApi(api_client)
            login_request = hydra.get_login_request(challenge)
            if request.method == "GET":
                return self.get(login_request, form, hydra)
            elif request.method == "POST":
                return self.post(login_request, form, hydra)
        abort(405)
def logout_challenge():
    req_json = request.get_json()
    configuration = ory_hydra_client.Configuration(
        os.environ.get('HYDRA_ADMIN_SERVER'))

    try:
        logout_challenge = req_json['logoutChallenge']

        if not logout_challenge:
            abort(401)

        with ory_hydra_client.ApiClient(configuration) as api_client:
            api_instance = ory_hydra_client.AdminApi(api_client)
            api_response = api_instance.accept_logout_request(logout_challenge)
            return {'redirectUrl': api_response.redirect_to}

    except KeyError:
        logging.error(
            'There was an error when getting value by key in request body')
    except ApiException as api_exception:
        logging.error(f'An ApiException occurred: {api_exception.reason}')
def get_consent_request():
    def reject_consent_challenge(api_instance: AdminApi,
                                 consent_challenge: str):
        body = ory_hydra_client.RejectRequest()
        api_response = api_instance.reject_consent_request(consent_challenge,
                                                           body=body)
        return {'redirectUrl': api_response.redirect_to}

    def accept_consent_challenge(api_instance: AdminApi,
                                 consent_challenge: str, requested_scope):
        body = ory_hydra_client.AcceptConsentRequest(
            grant_scope=requested_scope, remember=True, remember_for=3600)
        api_response = api_instance.accept_consent_request(consent_challenge,
                                                           body=body)
        return {'redirectUrl': api_response.redirect_to}

    configuration = ory_hydra_client.Configuration(
        os.environ.get('HYDRA_ADMIN_SERVER'))

    try:
        consent_challenge = request.args.get('consent_challenge')
        if not consent_challenge:
            abort(400)

        with ory_hydra_client.ApiClient(configuration) as api_client:
            api_instance = ory_hydra_client.AdminApi(api_client)
            api_response = api_instance.get_consent_request(consent_challenge)

            if api_response.skip:
                kratos_url = os.environ.get('KRATOS_SERVER')
                res_whoami = requests.get(f'{kratos_url}/sessions/whoami',
                                          cookies=request.cookies)

                if res_whoami.status_code == 401:
                    return reject_consent_challenge(api_instance,
                                                    consent_challenge)
                elif (res_whoami.json() and 'active' in res_whoami.json()
                      and res_whoami.json()['active'] is True):

                    requested_scope = api_response.requested_scope
                    return accept_consent_challenge(api_instance,
                                                    consent_challenge,
                                                    requested_scope)
                else:
                    return reject_consent_challenge(api_instance,
                                                    consent_challenge)

            if not api_response.skip:
                response = {
                    'client': api_response.client.client_name,
                    'challenge': api_response.challenge,
                    'requested_scope': api_response.requested_scope,
                    'user': api_response.subject
                }
                return response

    except ValueError:
        logging.error(
            'It was not possible to retrive the value with the given key')
    except Exception:
        logging.error('There was an error in get_consent_request')