Пример #1
0
    def post(self, request, *args, **kwargs):
        authorize = AuthorizeEndpoint(request)

        try:
            authorize.validate_params()

            if not request.POST.get('allow'):
                signals.user_decline_consent.send(
                    self.__class__,
                    user=request.user,
                    client=authorize.client,
                    scope=authorize.params['scope'])

                # give user a change to logout
                django_user_logout(request)
                raise AuthorizeError(authorize.params['redirect_uri'],
                                     'access_denied', authorize.grant_type)

            signals.user_accept_consent.send(self.__class__,
                                             user=request.user,
                                             client=authorize.client,
                                             scope=authorize.params['scope'])

            # Save the user consent given to the client.
            authorize.set_client_user_consent()

            uri = authorize.create_response_uri()

            return redirect(uri)

        except AuthorizeError as error:
            uri = error.create_uri(authorize.params['redirect_uri'],
                                   authorize.params['state'])

            return redirect(uri)
Пример #2
0
    def test_func(self):
        request = self.request
        client_id = request.GET.get('client_id',
                                    request.POST.get('client_id', None))
        Application = get_application_model()
        user = request.user
        if user.is_authenticated:
            last_login_backend = request.session.get(
                'social_auth_last_login_backend')
            try:
                application = Application.objects.get(client_id=client_id)
            except Application.DoesNotExist:
                logger.info("Application with id '{}' does not exist".format(
                    client_id))
                return False

            allowed_methods = application.login_methods.all()
            if allowed_methods is None:
                return False

            allowed_providers = set((x.provider_id for x in allowed_methods))
            if last_login_backend is not None:
                active_backend = user.social_auth.filter(
                    provider=last_login_backend)

            if ((last_login_backend is None and user is not None) or
                (active_backend.exists() and active_backend.first().provider
                 not in allowed_providers)):
                django_user_logout(request)
                return False

        return True
Пример #3
0
def check_login_required(request, authorize):
    """
    Raises AuthorizeError or JustRedirect if login is required for this auth.
    """
    if 'login' in authorize.params['prompt'] or request.user.is_anonymous:
        if 'none' in authorize.params['prompt']:
            raise AuthorizeError(authorize.params['redirect_uri'],
                                 'login_required', authorize.grant_type)
        else:
            django_user_logout(request)
            full_path = strip_prompt_login(request.get_full_path())
            raise JustRedirect(
                redirect_to_login(full_path, settings.get('OIDC_LOGIN_URL')))
Пример #4
0
def after_userlogin_hook(request, user, client):
    """Marks Django session modified and ensures the current
    session has an allowed login backend for the client.

    One purpose of this function is to keep the session used by the
    oidc-provider fresh. This is achieved by pointing
    'OIDC_AFTER_USERLOGIN_HOOK' setting to this.

    The other is to prevent authorizing users with an unallowed backend
    for specific clients.

    """
    request.session.modified = True

    last_login_backend = request.session.get('social_auth_last_login_backend')
    try:
        client_options = OidcClientOptions.objects.get(oidc_client=client)
    except OidcClientOptions.DoesNotExist:
        return None

    allowed_methods = client_options.login_methods.all()
    if allowed_methods is None:
        raise PermissionDenied

    allowed_providers = set((x.provider_id for x in allowed_methods))
    if last_login_backend is not None:
        active_backend = user.social_auth.filter(provider=last_login_backend)

    if ((last_login_backend is None and user is not None)
            or (active_backend.exists()
                and active_backend.first().provider not in allowed_providers)):
        django_user_logout(request)
        next_page = request.get_full_path()
        return redirect_to_login(next_page, settings.get('OIDC_LOGIN_URL'))

    # Return None to continue the login flow
    return None
Пример #5
0
def after_userlogin_hook(request, user, client):
    """Marks Django session modified and ensures the current
    session has an allowed login backend for the client.

    One purpose of this function is to keep the session used by the
    oidc-provider fresh. This is achieved by pointing
    'OIDC_AFTER_USERLOGIN_HOOK' setting to this.

    The other is to prevent authorizing users with an unallowed backend
    for specific clients.

    """
    request.session.modified = True

    last_login_backend = request.session.get('social_auth_last_login_backend')
    try:
        client_options = OidcClientOptions.objects.get(oidc_client=client)
    except OidcClientOptions.DoesNotExist:
        return None

    allowed_methods = client_options.login_methods.all()
    if allowed_methods is None:
        raise PermissionDenied

    allowed_providers = set((x.provider_id for x in allowed_methods))
    if last_login_backend is not None:
        active_backend = user.social_auth.filter(provider=last_login_backend)

    if ((last_login_backend is None and user is not None)
            or (active_backend.exists() and active_backend.first().provider not in allowed_providers)):
        django_user_logout(request)
        next_page = request.get_full_path()
        return redirect_to_login(next_page, settings.get('OIDC_LOGIN_URL'))

    # Return None to continue the login flow
    return None
Пример #6
0
    def get(self, request, *args, **kwargs):
        authorize = self.authorize_endpoint_class(request)

        try:
            authorize.validate_params()

            if get_attr_or_callable(request.user, 'is_authenticated'):
                # Check if there's a hook setted.
                hook_resp = settings.get('OIDC_AFTER_USERLOGIN_HOOK',
                                         import_str=True)(
                                             request=request,
                                             user=request.user,
                                             client=authorize.client)
                if hook_resp:
                    return hook_resp

                if 'login' in authorize.params['prompt']:
                    if 'none' in authorize.params['prompt']:
                        raise AuthorizeError(authorize.params['redirect_uri'],
                                             'login_required',
                                             authorize.grant_type)
                    else:
                        django_user_logout(request)
                        next_page = strip_prompt_login(request.get_full_path())
                        return redirect_to_login(
                            next_page, settings.get('OIDC_LOGIN_URL'))

                if 'select_account' in authorize.params['prompt']:
                    # TODO: see how we can support multiple accounts for the end-user.
                    if 'none' in authorize.params['prompt']:
                        raise AuthorizeError(authorize.params['redirect_uri'],
                                             'account_selection_required',
                                             authorize.grant_type)
                    else:
                        django_user_logout(request)
                        return redirect_to_login(
                            request.get_full_path(),
                            settings.get('OIDC_LOGIN_URL'))

                if {'none', 'consent'}.issubset(authorize.params['prompt']):
                    raise AuthorizeError(authorize.params['redirect_uri'],
                                         'consent_required',
                                         authorize.grant_type)

                if not authorize.client.require_consent and (
                        'consent' not in authorize.params['prompt']):
                    return redirect(authorize.create_response_uri())

                if authorize.client.reuse_consent:
                    # Check if user previously give consent.
                    if authorize.client_has_user_consent() and (
                            'consent' not in authorize.params['prompt']):
                        return redirect(authorize.create_response_uri())

                if 'none' in authorize.params['prompt']:
                    raise AuthorizeError(authorize.params['redirect_uri'],
                                         'consent_required',
                                         authorize.grant_type)

                # Generate hidden inputs for the form.
                context = {
                    'params': authorize.params,
                }
                hidden_inputs = render_to_string(
                    'oidc_provider/hidden_inputs.html', context)

                # Remove `openid` from scope list
                # since we don't need to print it.
                if 'openid' in authorize.params['scope']:
                    authorize.params['scope'].remove('openid')

                context = {
                    'client': authorize.client,
                    'hidden_inputs': hidden_inputs,
                    'params': authorize.params,
                    'scopes': authorize.get_scopes_information(),
                }

                return render(request, OIDC_TEMPLATES['authorize'], context)
            else:
                if 'none' in authorize.params['prompt']:
                    raise AuthorizeError(authorize.params['redirect_uri'],
                                         'login_required',
                                         authorize.grant_type)
                if 'login' in authorize.params['prompt']:
                    next_page = strip_prompt_login(request.get_full_path())
                    return redirect_to_login(next_page,
                                             settings.get('OIDC_LOGIN_URL'))

                return redirect_to_login(request.get_full_path(),
                                         settings.get('OIDC_LOGIN_URL'))

        except (ClientIdError, RedirectUriError) as error:
            context = {
                'error': error.error,
                'description': error.description,
            }

            return render(request, OIDC_TEMPLATES['error'], context)

        except AuthorizeError as error:
            uri = error.create_uri(authorize.params['redirect_uri'],
                                   authorize.params['state'])

            return redirect(uri)
Пример #7
0
def logout(request):
    if (request.user.is_authenticated()):
        django_user_logout(request)
        return HttpResponseRedirect(reverse('bitfund.core.views.index'))
    else:
        return HttpResponseRedirect(reverse('bitfund.core.views.login'))
Пример #8
0
    def get(self, request, *args, **kwargs):
        authorize = self.authorize_endpoint_class(request)

        try:
            authorize.validate_params()

            if get_attr_or_callable(request.user, 'is_authenticated'):
                # Check if there's a hook setted.
                hook_resp = settings.get('OIDC_AFTER_USERLOGIN_HOOK', import_str=True)(
                    request=request, user=request.user,
                    client=authorize.client)
                if hook_resp:
                    return hook_resp

                if 'login' in authorize.params['prompt']:
                    if 'none' in authorize.params['prompt']:
                        raise AuthorizeError(
                            authorize.params['redirect_uri'], 'login_required',
                            authorize.grant_type)
                    else:
                        django_user_logout(request)
                        next_page = strip_prompt_login(request.get_full_path())
                        return redirect_to_login(next_page, settings.get('OIDC_LOGIN_URL'))

                if 'select_account' in authorize.params['prompt']:
                    # TODO: see how we can support multiple accounts for the end-user.
                    if 'none' in authorize.params['prompt']:
                        raise AuthorizeError(
                            authorize.params['redirect_uri'], 'account_selection_required',
                            authorize.grant_type)
                    else:
                        django_user_logout(request)
                        return redirect_to_login(
                            request.get_full_path(), settings.get('OIDC_LOGIN_URL'))

                if {'none', 'consent'}.issubset(authorize.params['prompt']):
                    raise AuthorizeError(
                        authorize.params['redirect_uri'], 'consent_required', authorize.grant_type)

                implicit_flow_resp_types = {'id_token', 'id_token token'}
                allow_skipping_consent = (
                    authorize.client.client_type != 'public' or
                    authorize.params['response_type'] in implicit_flow_resp_types)

                if not authorize.client.require_consent and (
                        allow_skipping_consent and
                        'consent' not in authorize.params['prompt']):
                    return redirect(authorize.create_response_uri())

                if authorize.client.reuse_consent:
                    # Check if user previously give consent.
                    if authorize.client_has_user_consent() and (
                            allow_skipping_consent and
                            'consent' not in authorize.params['prompt']):
                        return redirect(authorize.create_response_uri())

                if 'none' in authorize.params['prompt']:
                    raise AuthorizeError(
                        authorize.params['redirect_uri'], 'consent_required', authorize.grant_type)

                # Generate hidden inputs for the form.
                context = {
                    'params': authorize.params,
                }
                hidden_inputs = render_to_string('oidc_provider/hidden_inputs.html', context)

                # Remove `openid` from scope list
                # since we don't need to print it.
                if 'openid' in authorize.params['scope']:
                    authorize.params['scope'].remove('openid')

                context = {
                    'client': authorize.client,
                    'hidden_inputs': hidden_inputs,
                    'params': authorize.params,
                    'scopes': authorize.get_scopes_information(),
                }

                return render(request, OIDC_TEMPLATES['authorize'], context)
            else:
                if 'none' in authorize.params['prompt']:
                    raise AuthorizeError(
                        authorize.params['redirect_uri'], 'login_required', authorize.grant_type)
                if 'login' in authorize.params['prompt']:
                    next_page = strip_prompt_login(request.get_full_path())
                    return redirect_to_login(next_page, settings.get('OIDC_LOGIN_URL'))

                return redirect_to_login(request.get_full_path(), settings.get('OIDC_LOGIN_URL'))

        except (ClientIdError, RedirectUriError) as error:
            context = {
                'error': error.error,
                'description': error.description,
            }

            return render(request, OIDC_TEMPLATES['error'], context)

        except AuthorizeError as error:
            uri = error.create_uri(
                authorize.params['redirect_uri'],
                authorize.params['state'])

            return redirect(uri)
Пример #9
0
def logout(request):
    if (request.user.is_authenticated()) :
        django_user_logout(request)
        return HttpResponseRedirect(reverse('bitfund.core.views.index'))
    else :
        return HttpResponseRedirect(reverse('bitfund.core.views.login'))