Python django.core.exceptions.SuspiciousOperation() Examples

The following are 30 code examples for showing how to use django.core.exceptions.SuspiciousOperation(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.core.exceptions , or try the search function .

Example 1
Project: open-synthesis   Author: twschiller   File: teams.py    License: GNU General Public License v3.0 6 votes vote down vote up
def edit_team(request, team_id):
    """Return a team edit view, or handle the form submission."""
    # TODO: if user turns off invitation-required, let everyone in who had outstanding membership requests

    team = get_object_or_404(Team, pk=team_id)

    if team.owner_id is None or team.owner_id != request.user.id:
        raise SuspiciousOperation(_('User is not the owner of the team'))

    if request.method == 'POST':
        form = TeamCreateForm(request.POST, instance=team)
        if form.is_valid():
            form.save()
            messages.success(request, _('Updated team information'))
            return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
    else:
        form = TeamCreateForm(instance=team)
    return render(request, 'teams/edit_team.html', context={
        'team': team,
        'form': form
    }) 
Example 2
Project: open-synthesis   Author: twschiller   File: teams.py    License: GNU General Public License v3.0 6 votes vote down vote up
def invite_members(request, team_id):
    """Return a team edit view, or handle the form submission."""
    team = get_object_or_404(Team, pk=team_id)

    if team.owner_id is None or team.owner_id != request.user.id:
        raise SuspiciousOperation(_('User is not the owner of the team'))

    if request.method == 'POST':
        form = TeamInviteForm(request.POST, team=team)
        if form.is_valid():
            to_invite = form.cleaned_data['members']
            invites = [TeamRequest(team=team, inviter=request.user, invitee=x) for x in to_invite]
            TeamRequest.objects.bulk_create(invites)
            for user in to_invite:
                notify.send(request.user, recipient=user, actor=request.user, verb='invite', action_object=team, target=user)
            messages.success(request, _('Invited {count} members to the team').format(count=len(to_invite)))
            return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
    else:
        form = TeamInviteForm(team=team)
    return render(request, 'teams/invite.html', context={
        'team': team,
        'form': form
    }) 
Example 3
Project: open-synthesis   Author: twschiller   File: teams.py    License: GNU General Public License v3.0 6 votes vote down vote up
def decide_invitation(request, invite_id):
    invite = get_object_or_404(TeamRequest, pk=invite_id)
    team = invite.team

    if team.owner_id is None or team.owner_id != request.user.id:
        raise SuspiciousOperation(_('User is not the owner of the team'))
    elif 'accept' in request.POST:
        invite.team.members.add(invite.invitee)
        invite.team.save()
        notify.send(request.user, recipient=invite.invitee, actor=request.user, verb='accept', action_object=team, target=invite.invitee)
        messages.success(request, _('Added {name} to the team').format(name=invite.invitee.username))
    elif 'reject' in request.POST:
        notify.send(request.user, recipient=invite.invitee, actor=request.user, verb='reject', action_object=team, target=invite.invitee)
        messages.success(request, _('Ignored {name}\'s team membership request').format(name=invite.invitee.username))
    else:
        return HttpResponseBadRequest(_('POST request must include either "{accept}" or "{reject}"').format(accept='accept', reject='reject'))

    invite.delete()
    return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,))) 
Example 4
Project: open-synthesis   Author: twschiller   File: teams.py    License: GNU General Public License v3.0 6 votes vote down vote up
def revoke_membership(request, team_id, member_id):
    team = get_object_or_404(Team, pk=team_id)
    user = get_object_or_404(User, pk=member_id)

    if team.owner_id is None or team.owner_id != request.user.id:
        raise SuspiciousOperation(_('User is not the owner of the team'))
    elif user == team.owner:
        raise SuspiciousOperation(_('Cannot remove the owner from the team'))
    elif not team.invitation_required:
        raise SuspiciousOperation(_('Cannot remove user from teams that don\'t require an invitation'))

    team.members.remove(user)
    team.save()
    notify.send(request.user, recipient=user, actor=request.user, verb='remove', action_object=team, target=user)
    messages.success(request, _('Removed {name} from team').format(name=user.username))
    return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,))) 
Example 5
Project: open-synthesis   Author: twschiller   File: teams.py    License: GNU General Public License v3.0 6 votes vote down vote up
def join_team(request, team_id):
    team = get_object_or_404(Team, pk=team_id)

    if team.members.filter(id=request.user.id).exists():
        raise SuspiciousOperation(_('User is already a member of the team'))
    elif TeamRequest.objects.filter(invitee=request.user, inviter__isnull=False, team=team).exists() or not team.invitation_required:
        team.members.add(request.user)
        team.save()
        TeamRequest.objects.filter(invitee=request.user, team=team).delete()
        messages.success(request, _('Joined team {name}').format(name=team.name))
        return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
    elif TeamRequest.objects.filter(invitee=request.user, team=team).exists():
        return HttpResponseBadRequest(_('User already has a membership request with the team'))
    else:
        TeamRequest.objects.create(invitee=request.user, team=team)
        if team.owner:
            notify.send(request.user, recipient=team.owner, actor=request.user, verb='request_membership', target=team)
        messages.success(request, _('Requested invitation to team {name}').format(name=team.name))
        return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,))) 
Example 6
Project: GTDWeb   Author: lanbing510   File: base.py    License: GNU General Public License v2.0 6 votes vote down vote up
def decode(self, session_data):
        encoded_data = base64.b64decode(force_bytes(session_data))
        try:
            # could produce ValueError if there is no ':'
            hash, serialized = encoded_data.split(b':', 1)
            expected_hash = self._hash(serialized)
            if not constant_time_compare(hash.decode(), expected_hash):
                raise SuspiciousSession("Session data corrupted")
            else:
                return self.serializer().loads(serialized)
        except Exception as e:
            # ValueError, SuspiciousOperation, unpickling exceptions. If any of
            # these happen, just return an empty dictionary (an empty session).
            if isinstance(e, SuspiciousOperation):
                logger = logging.getLogger('django.security.%s' %
                        e.__class__.__name__)
                logger.warning(force_text(e))
            return {} 
Example 7
Project: dingtalk-django-example   Author: 007gzs   File: storage.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _normalize_name(self, name):
        """
        Normalizes the name so that paths like /path/to/ignored/../foo.txt
        work. We check to make sure that the path pointed to is not outside
        the directory specified by the LOCATION setting.
        """
        if name.startswith("https://") or name.startswith("http://"):
            return name
        base_path = force_text(self.location)
        base_path = base_path.rstrip('/')

        final_path = urljoin(base_path.rstrip('/') + "/", name)

        base_path_len = len(base_path)
        if (not final_path.startswith(base_path) or
                final_path[base_path_len:base_path_len + 1] not in ('', '/')):
            raise SuspiciousOperation("Attempted access to '%s' denied." %
                                      name)
        return final_path.lstrip('/') 
Example 8
Project: kobo-predict   Author: awemulya   File: common.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def skip_suspicious_operations(record):
    """Prevent django from sending 500 error
    email notifications for SuspiciousOperation
    events, since they are not true server errors,
    especially when related to the ALLOWED_HOSTS
    configuration

    background and more information:
    http://www.tiwoc.de/blog/2013/03/django-prevent-email-notification-on-susp\
    iciousoperation/
    """
    if record.exc_info:
        exc_value = record.exc_info[1]
        if isinstance(exc_value, SuspiciousOperation):
            return False
    return True

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration. 
Example 9
Project: timed-backend   Author: adfinis-sygroup   File: authentication.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_userinfo_or_introspection(self, access_token):
        try:
            claims = self.cached_request(
                self.get_userinfo, access_token, "auth.userinfo"
            )
        except requests.HTTPError as e:
            if not (
                e.response.status_code in [401, 403] and settings.OIDC_CHECK_INTROSPECT
            ):
                raise e

            # check introspection if userinfo fails (confidental client)
            claims = self.cached_request(
                self.get_introspection, access_token, "auth.introspection"
            )
            if "client_id" not in claims:
                raise SuspiciousOperation("client_id not present in introspection")

        return claims 
Example 10
Project: bioforum   Author: reBiocoder   File: base.py    License: MIT License 6 votes vote down vote up
def decode(self, session_data):
        encoded_data = base64.b64decode(force_bytes(session_data))
        try:
            # could produce ValueError if there is no ':'
            hash, serialized = encoded_data.split(b':', 1)
            expected_hash = self._hash(serialized)
            if not constant_time_compare(hash.decode(), expected_hash):
                raise SuspiciousSession("Session data corrupted")
            else:
                return self.serializer().loads(serialized)
        except Exception as e:
            # ValueError, SuspiciousOperation, unpickling exceptions. If any of
            # these happen, just return an empty dictionary (an empty session).
            if isinstance(e, SuspiciousOperation):
                logger = logging.getLogger('django.security.%s' % e.__class__.__name__)
                logger.warning(str(e))
            return {} 
Example 11
Project: bioforum   Author: reBiocoder   File: file.py    License: MIT License 6 votes vote down vote up
def load(self):
        session_data = {}
        try:
            with open(self._key_to_file(), "rb") as session_file:
                file_data = session_file.read()
            # Don't fail if there is no data in the session file.
            # We may have opened the empty placeholder file.
            if file_data:
                try:
                    session_data = self.decode(file_data)
                except (EOFError, SuspiciousOperation) as e:
                    if isinstance(e, SuspiciousOperation):
                        logger = logging.getLogger('django.security.%s' % e.__class__.__name__)
                        logger.warning(str(e))
                    self.create()

                # Remove expired sessions.
                expiry_age = self.get_expiry_age(expiry=self._expiry_date(session_data))
                if expiry_age <= 0:
                    session_data = {}
                    self.delete()
                    self.create()
        except (IOError, SuspiciousOperation):
            self._session_key = None
        return session_data 
Example 12
Project: bioforum   Author: reBiocoder   File: cached_db.py    License: MIT License 6 votes vote down vote up
def load(self):
        try:
            data = self._cache.get(self.cache_key)
        except Exception:
            # Some backends (e.g. memcache) raise an exception on invalid
            # cache keys. If this happens, reset the session. See #17810.
            data = None

        if data is None:
            # Duplicate DBStore.load, because we need to keep track
            # of the expiry date to set it properly in the cache.
            try:
                s = self.model.objects.get(
                    session_key=self.session_key,
                    expire_date__gt=timezone.now()
                )
                data = self.decode(s.session_data)
                self._cache.set(self.cache_key, data, self.get_expiry_age(expiry=s.expire_date))
            except (self.model.DoesNotExist, SuspiciousOperation) as e:
                if isinstance(e, SuspiciousOperation):
                    logger = logging.getLogger('django.security.%s' % e.__class__.__name__)
                    logger.warning(str(e))
                self._session_key = None
                data = {}
        return data 
Example 13
Project: django-qiniu-storage   Author: glasslion   File: backends.py    License: MIT License 6 votes vote down vote up
def _normalize_name(self, name):
        """
        Normalizes the name so that paths like /path/to/ignored/../foo.txt
        work. We check to make sure that the path pointed to is not outside
        the directory specified by the LOCATION setting.
        """

        base_path = force_text(self.location)
        base_path = base_path.rstrip('/')

        final_path = urljoin(base_path.rstrip('/') + "/", name)

        base_path_len = len(base_path)
        if (not final_path.startswith(base_path) or
                final_path[base_path_len:base_path_len + 1] not in ('', '/')):
            raise SuspiciousOperation("Attempted access to '%s' denied." %
                                      name)
        return final_path.lstrip('/') 
Example 14
Project: mozilla-django-oidc   Author: mozilla   File: test_views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def test_get_auth_failure_tampered_session_state(self):
        """Test authentication failure attempt for an inactive user."""
        user = User.objects.create_user('example_username')
        user.is_active = False
        user.save()

        get_data = {
            'code': 'example_code',
            'state': 'example_state'
        }

        url = reverse('oidc_authentication_callback')
        request = self.factory.get(url, get_data)
        request.session = {
            'oidc_state': 'tampered_state'
        }
        callback_view = views.OIDCAuthenticationCallbackView.as_view()

        with self.assertRaises(SuspiciousOperation) as context:
            callback_view(request)

        expected_error_message = 'Session `oidc_state` does not match the OIDC callback state'
        self.assertEqual(context.exception.args, (expected_error_message,)) 
Example 15
Project: mozilla-django-oidc   Author: mozilla   File: test_auth.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def test_allowed_unsecured_invalid_token(self):
        """Test payload data from invalid secure token (unsecured allowed)."""
        header = force_bytes(json.dumps({'alg': 'HS256', 'typ': 'JWT'}))
        payload = force_bytes(json.dumps({'foo': 'bar'}))

        # Compute signature
        key = b'mysupersecuretestkey'
        fake_key = b'mysupersecurefaketestkey'
        h = hmac.HMAC(key, hashes.SHA256(), backend=default_backend())
        msg = '{}.{}'.format(smart_text(b64encode(header)), smart_text(b64encode(payload)))
        h.update(force_bytes(msg))
        signature = b64encode(h.finalize())

        token = '{}.{}.{}'.format(
            smart_text(b64encode(header)),
            smart_text(b64encode(payload)),
            smart_text(signature)
        )
        token_bytes = force_bytes(token)
        key_text = smart_text(fake_key)

        with self.assertRaises(SuspiciousOperation) as ctx:
            self.backend.get_payload_data(token_bytes, key_text)
        self.assertEqual(ctx.exception.args[0], 'JWS token verification failed.') 
Example 16
Project: mozilla-django-oidc   Author: mozilla   File: test_auth.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def test_disallowed_unsecured_invalid_token(self):
        """Test payload data from invalid secure token (unsecured disallowed)."""
        header = force_bytes(json.dumps({'alg': 'HS256', 'typ': 'JWT'}))
        payload = force_bytes(json.dumps({'foo': 'bar'}))

        # Compute signature
        key = b'mysupersecuretestkey'
        fake_key = b'mysupersecurefaketestkey'
        h = hmac.HMAC(key, hashes.SHA256(), backend=default_backend())
        msg = '{}.{}'.format(smart_text(b64encode(header)), smart_text(b64encode(payload)))
        h.update(force_bytes(msg))
        signature = b64encode(h.finalize())

        token = '{}.{}.{}'.format(
            smart_text(b64encode(header)),
            smart_text(b64encode(payload)),
            smart_text(signature)
        )
        token_bytes = force_bytes(token)
        key_text = smart_text(fake_key)

        with self.assertRaises(SuspiciousOperation) as ctx:
            self.backend.get_payload_data(token_bytes, key_text)
        self.assertEqual(ctx.exception.args[0], 'JWS token verification failed.') 
Example 17
Project: swagger-django-generator   Author: praekelt   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def body_to_dict(body, schema):
    # type: (str, Dict) -> Dict
    """

    :param body: The body content
    :param schema: The expected JSONSchema
    :return: A dictionary containing the parsed body
    :raises SuspiciousOperation: If the body is not in JSON format, or does not
       conform to the specified schema.
    """
    try:
        data = json.loads(body)
        jsonschema.validate(data, schema=schema)
        return data
    except Exception as e:
        # The SuspiciousOperation exception will result in an
        # HttpResponseBadRequest response.
        raise SuspiciousOperation(e) 
Example 18
Project: swagger-django-generator   Author: praekelt   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def body_to_dict(body, schema):
    # type: (str, Dict) -> Dict
    """

    :param body: The body content
    :param schema: The expected JSONSchema
    :return: A dictionary containing the parsed body
    :raises SuspiciousOperation: If the body is not in JSON format, or does not
       conform to the specified schema.
    """
    try:
        data = json.loads(body)
        jsonschema.validate(data, schema=schema)
        return data
    except Exception as e:
        # The SuspiciousOperation exception will result in an
        # HttpResponseBadRequest response.
        raise SuspiciousOperation(e) 
Example 19
Project: swagger-django-generator   Author: praekelt   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def body_to_dict(body, schema):
    # type: (str, Dict) -> Dict
    """

    :param body: The body content
    :param schema: The expected JSONSchema
    :return: A dictionary containing the parsed body
    :raises SuspiciousOperation: If the body is not in JSON format, or does not
       conform to the specified schema.
    """
    try:
        data = json.loads(body)
        jsonschema.validate(data, schema=schema)
        return data
    except Exception as e:
        # The SuspiciousOperation exception will result in an
        # HttpResponseBadRequest response.
        raise SuspiciousOperation(e) 
Example 20
Project: acacia_main   Author: AcaciaTrading   File: db.py    License: MIT License 6 votes vote down vote up
def load(self):
        try:
            s = Session.objects.get(
                session_key=self.session_key,
                expire_date__gt=timezone.now()
            )
            self.user_id = s.user_id
            # do not overwrite user_agent/ip, as those might have been updated
            if self.user_agent != s.user_agent or self.ip != s.ip:
                self.modified = True
            return self.decode(s.session_data)
        except (Session.DoesNotExist, SuspiciousOperation) as e:
            if isinstance(e, SuspiciousOperation):
                logger = logging.getLogger('django.security.%s' %
                                           e.__class__.__name__)
                logger.warning(force_text(e))
            self.create()
            return {} 
Example 21
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: base.py    License: MIT License 6 votes vote down vote up
def decode(self, session_data):
        encoded_data = base64.b64decode(force_bytes(session_data))
        try:
            # could produce ValueError if there is no ':'
            hash, serialized = encoded_data.split(b':', 1)
            expected_hash = self._hash(serialized)
            if not constant_time_compare(hash.decode(), expected_hash):
                raise SuspiciousSession("Session data corrupted")
            else:
                return self.serializer().loads(serialized)
        except Exception as e:
            # ValueError, SuspiciousOperation, unpickling exceptions. If any of
            # these happen, just return an empty dictionary (an empty session).
            if isinstance(e, SuspiciousOperation):
                logger = logging.getLogger('django.security.%s' % e.__class__.__name__)
                logger.warning(str(e))
            return {} 
Example 22
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: file.py    License: MIT License 6 votes vote down vote up
def load(self):
        session_data = {}
        try:
            with open(self._key_to_file(), "rb") as session_file:
                file_data = session_file.read()
            # Don't fail if there is no data in the session file.
            # We may have opened the empty placeholder file.
            if file_data:
                try:
                    session_data = self.decode(file_data)
                except (EOFError, SuspiciousOperation) as e:
                    if isinstance(e, SuspiciousOperation):
                        logger = logging.getLogger('django.security.%s' % e.__class__.__name__)
                        logger.warning(str(e))
                    self.create()

                # Remove expired sessions.
                expiry_age = self.get_expiry_age(expiry=self._expiry_date(session_data))
                if expiry_age <= 0:
                    session_data = {}
                    self.delete()
                    self.create()
        except (IOError, SuspiciousOperation):
            self._session_key = None
        return session_data 
Example 23
Project: luscan-devel   Author: blackye   File: request.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_host(self):
        """Returns the HTTP host using the environment or request headers."""
        # We try three options, in order of decreasing preference.
        if settings.USE_X_FORWARDED_HOST and (
            'HTTP_X_FORWARDED_HOST' in self.META):
            host = self.META['HTTP_X_FORWARDED_HOST']
        elif 'HTTP_HOST' in self.META:
            host = self.META['HTTP_HOST']
        else:
            # Reconstruct the host using the algorithm from PEP 333.
            host = self.META['SERVER_NAME']
            server_port = str(self.META['SERVER_PORT'])
            if server_port != ('443' if self.is_secure() else '80'):
                host = '%s:%s' % (host, server_port)

        allowed_hosts = ['*'] if settings.DEBUG else settings.ALLOWED_HOSTS
        if validate_host(host, allowed_hosts):
            return host
        else:
            raise SuspiciousOperation(
                "Invalid HTTP_HOST header (you may need to set ALLOWED_HOSTS): %s" % host) 
Example 24
Project: luscan-devel   Author: blackye   File: multipartparser.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _update_unget_history(self, num_bytes):
        """
        Updates the unget history as a sanity check to see if we've pushed
        back the same number of bytes in one chunk. If we keep ungetting the
        same number of bytes many times (here, 50), we're mostly likely in an
        infinite loop of some sort. This is usually caused by a
        maliciously-malformed MIME request.
        """
        self._unget_history = [num_bytes] + self._unget_history[:49]
        number_equal = len([current_number for current_number in self._unget_history
                            if current_number == num_bytes])

        if number_equal > 40:
            raise SuspiciousOperation(
                "The multipart parser got stuck, which shouldn't happen with"
                " normal uploaded files. Check for malicious upload activity;"
                " if there is none, report this to the Django developers."
            ) 
Example 25
Project: openhgsenti   Author: drexly   File: base.py    License: Apache License 2.0 6 votes vote down vote up
def decode(self, session_data):
        encoded_data = base64.b64decode(force_bytes(session_data))
        try:
            # could produce ValueError if there is no ':'
            hash, serialized = encoded_data.split(b':', 1)
            expected_hash = self._hash(serialized)
            if not constant_time_compare(hash.decode(), expected_hash):
                raise SuspiciousSession("Session data corrupted")
            else:
                return self.serializer().loads(serialized)
        except Exception as e:
            # ValueError, SuspiciousOperation, unpickling exceptions. If any of
            # these happen, just return an empty dictionary (an empty session).
            if isinstance(e, SuspiciousOperation):
                logger = logging.getLogger('django.security.%s' %
                        e.__class__.__name__)
                logger.warning(force_text(e))
            return {} 
Example 26
Project: python2017   Author: bpgc-cte   File: base.py    License: MIT License 6 votes vote down vote up
def decode(self, session_data):
        encoded_data = base64.b64decode(force_bytes(session_data))
        try:
            # could produce ValueError if there is no ':'
            hash, serialized = encoded_data.split(b':', 1)
            expected_hash = self._hash(serialized)
            if not constant_time_compare(hash.decode(), expected_hash):
                raise SuspiciousSession("Session data corrupted")
            else:
                return self.serializer().loads(serialized)
        except Exception as e:
            # ValueError, SuspiciousOperation, unpickling exceptions. If any of
            # these happen, just return an empty dictionary (an empty session).
            if isinstance(e, SuspiciousOperation):
                logger = logging.getLogger('django.security.%s' % e.__class__.__name__)
                logger.warning(force_text(e))
            return {} 
Example 27
Project: controller   Author: deis   File: test_certificate.py    License: MIT License 5 votes vote down vote up
def test_load_invalid_cert(self):
        """Inject a cert that can't be loaded by pyopenssl"""

        with self.assertRaises(SuspiciousOperation):
            Certificate.objects.create(
                owner=self.user,
                name='random-test-cert',
                certificate='i am bad data',
                key='i am bad data as well'
            ) 
Example 28
Project: controller   Author: deis   File: test_certificate.py    License: MIT License 5 votes vote down vote up
def test_load_invalid_key(self):
        """Inject a private key that can't be loaded by pyopenssl"""

        with self.assertRaises(SuspiciousOperation):
            Certificate.objects.create(
                owner=self.user,
                name='random-test-cert',
                certificate=self.cert,
                key='I am Groot.'
            ) 
Example 29
Project: django-oidc-rp   Author: impak-finance   File: test_backends.py    License: MIT License 5 votes vote down vote up
def test_cannot_authenticate_a_user_if_the_state_is_not_present_in_the_request_parameters(
            self, rf):
        request = rf.get('/oidc/cb/', {'code': 'authcode', })
        SessionMiddleware().process_request(request)
        request.session.save()
        backend = OIDCAuthBackend()
        with pytest.raises(SuspiciousOperation):
            backend.authenticate(request, 'nonce') 
Example 30
Project: django-oidc-rp   Author: impak-finance   File: test_backends.py    License: MIT License 5 votes vote down vote up
def test_cannot_authenticate_a_user_if_the_code_is_not_present_in_the_request_parameters(
            self, rf):
        request = rf.get('/oidc/cb/', {'state': 'state', })
        SessionMiddleware().process_request(request)
        request.session.save()
        backend = OIDCAuthBackend()
        with pytest.raises(SuspiciousOperation):
            backend.authenticate(request, 'nonce')