def form_valid(self, form):
        try:
            credentials = {
                'client_id': form.cleaned_data.get('client_id'),
                'redirect_uri': form.cleaned_data.get('redirect_uri'),
                'response_type': form.cleaned_data.get('response_type', None),
                'state': form.cleaned_data.get('state', None),
                'form_expires_in': form.cleaned_data.get('expires_in'),
            }

            scopes = form.cleaned_data.get('scope')
            allow = form.cleaned_data.get('allow')
            uri, headers, body, status = self.create_authorization_response(
                request=self.request,
                scopes=scopes,
                credentials=credentials,
                allow=allow)
            self.success_url = uri

            # here we save the expires_in choice from the allow form
            # into the expires cache table.
            expires_in = form.cleaned_data.get('expires_in')
            client_id = form.cleaned_data.get('client_id')
            user_id = self.request.user.pk
            ExpiresIn.objects.set_expires_in(client_id, user_id, expires_in)

            logger.debug("Success url for the request: {0}".format(
                self.success_url))
            return HttpResponseUriRedirect(self.success_url)

        except OAuthToolkitError as error:
            return self.error_response(error)
Example #2
0
    def form_valid(self, form):
        try:
            # Get credentials
            credentials = {
                'client_id': form.cleaned_data.get('client_id'),
                'redirect_uri': form.cleaned_data.get('redirect_uri'),
                'response_type': form.cleaned_data.get('response_type', None),
                'state': form.cleaned_data.get('state', None),
            }

            # Get other data and build uri
            scopes = form.cleaned_data.get('scope')
            allow = form.cleaned_data.get('allow')
            uri, headers, body, status = self.create_authorization_response(
                request=self.request,
                scopes=scopes,
                credentials=credentials,
                allow=allow)

            # Check if use has domain, send that param as well
            if self.request.user.domain:
                uri += '&account={}'.format(self.request.user.owner.id)

            # Set success url and redirect
            self.success_url = uri
            return HttpResponseUriRedirect(self.success_url)

        except OAuthToolkitError as error:
            return self.error_response(error)
Example #3
0
    def error_response(self, error, **kwargs):
        """Handle errors with a redirect or an error response."""
        redirect, error_response = super(
            BaseAuthorizationView, self).error_response(error, **kwargs)

        if redirect:
            return HttpResponseUriRedirect(error_response['url'])

        status = error_response['error'].status_code
        error_response.pop('url', None)
        return self.render_to_response(error_response, status=status)
Example #4
0
    def get(self, request, *args, **kwargs):
        # Note: This code is copied from https://github.com/evonove/django-oauth-toolkit/blob/34f3b7b3511c15686039079026165feaadb1b87d/oauth2_provider/views/base.py#L111
        # Places that we have changed are noted with ***.
        application = None
        try:
            # *** Moved code to get the require_approval value earlier on so we can
            # circumvent our custom code in the case when auto_even_if_expired
            # isn't required.
            require_approval = request.GET.get(
                "approval_prompt",
                oauth2_settings.REQUEST_APPROVAL_PROMPT,
            )
            if require_approval != 'auto_even_if_expired':
                return super(EdxOAuth2AuthorizationView,
                             self).get(request, *args, **kwargs)

            scopes, credentials = self.validate_authorization_request(request)
            all_scopes = get_scopes_backend().get_all_scopes()
            kwargs["scopes_descriptions"] = [
                all_scopes[scope] for scope in scopes
            ]
            kwargs['scopes'] = scopes

            # at this point we know an Application instance with such client_id exists in the database
            application = get_application_model().objects.get(
                client_id=credentials['client_id'])
            content_orgs = ApplicationOrganization.get_related_org_names(
                application,
                relation_type=ApplicationOrganization.RELATION_TYPE_CONTENT_ORG
            )
            kwargs['application'] = application
            kwargs['content_orgs'] = content_orgs
            kwargs['client_id'] = credentials['client_id']
            kwargs['redirect_uri'] = credentials['redirect_uri']
            kwargs['response_type'] = credentials['response_type']
            kwargs['state'] = credentials['state']

            self.oauth2_data = kwargs
            # following two loc are here only because of https://code.djangoproject.com/ticket/17795
            form = self.get_form(self.get_form_class())
            kwargs['form'] = form

            # If skip_authorization field is True, skip the authorization screen even
            # if this is the first use of the application and there was no previous authorization.
            # This is useful for in-house applications-> assume an in-house applications
            # are already approved.
            if application.skip_authorization:
                uri, headers, body, status = self.create_authorization_response(
                    request=self.request,
                    scopes=" ".join(scopes),
                    credentials=credentials,
                    allow=True)
                return HttpResponseUriRedirect(
                    uri, application.get_allowed_schemes())

            # *** Changed the if statement that checked for require_approval to an assert.
            assert require_approval == 'auto_even_if_expired'
            tokens = get_access_token_model().objects.filter(
                user=request.user,
                application=kwargs['application'],
                # *** Purposefully keeping this commented out code to highlight that
                # our version of the implementation does NOT filter by expiration date.
                # expires__gt=timezone.now(),
            ).all()

            # check past authorizations regarded the same scopes as the current one
            for token in tokens:
                if token.allow_scopes(scopes):
                    uri, headers, body, status = self.create_authorization_response(
                        request=self.request,
                        scopes=" ".join(scopes),
                        credentials=credentials,
                        allow=True)
                    return HttpResponseUriRedirect(
                        uri, application.get_allowed_schemes())

            # render an authorization prompt so the user can approve
            # the application's requested scopes
            return self.render_to_response(self.get_context_data(**kwargs))

        except OAuthToolkitError as error:
            return self.error_response(error, application)
Example #5
0
    def get(self, request, *args, **kwargs):
        """
        Copied blantly from super method. Had to change few stuff, but didn't find better way
        than copying and editing the whole stuff.
        Sin Count += 1
        """
        try:
            scopes, credentials = self.validate_authorization_request(request)
            try:
                del credentials['request']
                # Removing oauthlib.Request from credentials. This is not required in future
            except KeyError:
                pass

            kwargs['scopes_descriptions'] = [
                oauth2_settings.SCOPES[scope] for scope in scopes
            ]
            kwargs['scopes'] = scopes
            # at this point we know an Application instance with such client_id exists in the database
            application = get_oauth2_application_model().objects.get(
                client_id=credentials['client_id'])  # TODO: cache it!
            kwargs['application'] = application
            kwargs.update(credentials)
            self.oauth2_data = kwargs
            # following two loc are here only because of https://code.djangoproject.com/ticket/17795
            form = self.get_form(self.get_form_class())
            kwargs['form'] = form

            # Check to see if the user has already granted access and return
            # a successful response depending on 'approval_prompt' url parameter
            require_approval = request.GET.get(
                'approval_prompt', oauth2_settings.REQUEST_APPROVAL_PROMPT)

            # If skip_authorization field is True, skip the authorization screen even
            # if this is the first use of the application and there was no previous authorization.
            # This is useful for in-house applications-> assume an in-house applications
            # are already approved.
            if application.skip_authorization:
                uri, headers, body, status = self.create_authorization_response(
                    request=self.request,
                    scopes=" ".join(scopes),
                    credentials=credentials,
                    allow=True)
                return HttpResponseUriRedirect(uri)

            elif require_approval == 'auto':
                tokens = request.user.accesstoken_set.filter(
                    application=kwargs['application']).all().order_by('-id')
                if len(tokens) > 0:
                    token = tokens[0]
                    if len(tokens) > 1:
                        # Enforce one token pair per user policy. Remove all older tokens
                        request.user.accesstoken_set.exclude(
                            pk=token.id).all().delete()

                    # check past authorizations regarded the same scopes as the current one
                    if token.allow_scopes(scopes):
                        uri, headers, body, status = self.create_authorization_response(
                            request=self.request,
                            scopes=" ".join(scopes),
                            credentials=credentials,
                            allow=True)
                        return HttpResponseUriRedirect(uri)

            return self.render_to_response(self.get_context_data(**kwargs))

        except OAuthToolkitError as error:
            return self.error_response(error)