Python django.contrib.auth.models.AnonymousUser() Examples

The following are 30 code examples of django.contrib.auth.models.AnonymousUser(). 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 also want to check out all available functions/classes of the module django.contrib.auth.models , or try the search function .
Example #1
Source File: context_processors.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def auth(request):
    """
    Returns context variables required by apps that use Django's authentication
    system.

    If there is no 'user' attribute in the request, uses AnonymousUser (from
    django.contrib.auth).
    """
    if hasattr(request, 'user'):
        user = request.user
    else:
        from django.contrib.auth.models import AnonymousUser
        user = AnonymousUser()

    return {
        'user': user,
        'perms': PermWrapper(user),
    } 
Example #2
Source File: test_ordering.py    From resolwe with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super().setUp()

        user_model = get_user_model()
        self.user_1 = user_model.objects.create(
            username="user_1", first_name="Zion", last_name="Zucchini"
        )
        self.user_2 = user_model.objects.create(
            username="user_2", first_name="Zack", last_name="Zucchini"
        )
        self.user_3 = user_model.objects.create(
            username="user_3", first_name="Adam", last_name="Angus"
        )

        self.entity_1 = Entity.objects.create(name="Entity 1", contributor=self.user_1)
        self.entity_2 = Entity.objects.create(name="Entity 2", contributor=self.user_2)
        self.entity_3 = Entity.objects.create(name="Entity 3", contributor=self.user_3)

        assign_perm("view_entity", AnonymousUser(), self.entity_1)
        assign_perm("view_entity", AnonymousUser(), self.entity_2)
        assign_perm("view_entity", AnonymousUser(), self.entity_3)

        self.url = reverse("resolwe-api:entity-list") 
Example #3
Source File: django.py    From aiohttp-json-rpc with Apache License 2.0 6 votes vote down vote up
def get_user(self, request):
        session_key = request.cookies.get('sessionid', '')

        if session_key:
            try:
                session = Session.objects.get(session_key=session_key)
                uid = session.get_decoded().get('_auth_user_id')

                try:
                    return User.objects.get(pk=uid)

                except User.DoesNotExist:
                    pass

            except Session.DoesNotExist:
                pass

        return AnonymousUser() 
Example #4
Source File: tests.py    From django-defender with Apache License 2.0 6 votes vote down vote up
def test_get_ip_reverse_proxy(self):
        """ Tests if can handle a long user agent
        """
        request_factory = RequestFactory()
        request = request_factory.get(ADMIN_LOGIN_URL)
        request.user = AnonymousUser()
        request.session = SessionStore()

        request.META["HTTP_X_FORWARDED_FOR"] = "192.168.24.24"
        self.assertEqual(utils.get_ip(request), "192.168.24.24")

        request_factory = RequestFactory()
        request = request_factory.get(ADMIN_LOGIN_URL)
        request.user = AnonymousUser()
        request.session = SessionStore()

        request.META["REMOTE_ADDR"] = "24.24.24.24"
        self.assertEqual(utils.get_ip(request), "24.24.24.24") 
Example #5
Source File: models.py    From waliki with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_users_for(cls, perms, slug):
        """
        return users with ``perms`` for the given ``slug``.

        ``perms`` could be the permission name or an iterable
         of permissions names
        """

        rules = cls.get_rules_for(perms, slug)
        if rules.filter(apply_to=ACLRule.TO_ANY).exists():
            return {AnonymousUser()} | set(get_user_model().objects.all())
        elif rules.filter(apply_to=ACLRule.TO_LOGGED).exists():
            return get_user_model().objects.all()

        allowed = []
        for rule in rules:
            if rule.apply_to == ACLRule.TO_STAFF:
                allowed += get_user_model().objects.filter(is_staff=True).values_list('id', flat=True)
            elif rule.apply_to == ACLRule.TO_SUPERUSERS:
                allowed += get_user_model().objects.filter(is_superuser=True).values_list('id', flat=True)
            else:
                allowed += get_user_model().objects.filter(Q(aclrule=rule) |
                                                           Q(groups__aclrule=rule)).values_list('id',
                                                                                                flat=True)
        return get_user_model().objects.filter(id__in=allowed).distinct() 
Example #6
Source File: context_processors.py    From bioforum with MIT License 6 votes vote down vote up
def auth(request):
    """
    Return context variables required by apps that use Django's authentication
    system.

    If there is no 'user' attribute in the request, use AnonymousUser (from
    django.contrib.auth).
    """
    if hasattr(request, 'user'):
        user = request.user
    else:
        from django.contrib.auth.models import AnonymousUser
        user = AnonymousUser()

    return {
        'user': user,
        'perms': PermWrapper(user),
    } 
Example #7
Source File: tests.py    From django-defender with Apache License 2.0 6 votes vote down vote up
def test_login_non_blocked_for_non_standard_login_views_different_msg(self):
        """
        Check that a view wich returns the expected status code but not the
        expected message is not causing the IP to be locked out.
        """

        @watch_login(status_code=401, msg="Invalid credentials")
        def fake_api_401_login_view_without_msg(request):
            """ Fake the api login with 401 """
            return HttpResponse("Ups, wrong credentials", status=401)

        request_factory = RequestFactory()
        request = request_factory.post("api/login")
        request.user = AnonymousUser()
        request.session = SessionStore()

        request.META["HTTP_X_FORWARDED_FOR"] = "192.168.24.24"

        for _ in range(4):
            fake_api_401_login_view_without_msg(request)

            data_out = utils.get_blocked_ips()
            self.assertEqual(data_out, []) 
Example #8
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def logout(request):
    """
    Removes the authenticated user's ID from the request and flushes their
    session data.
    """
    # Dispatch the signal before the user is logged out so the receivers have a
    # chance to find out *who* logged out.
    user = getattr(request, 'user', None)
    if hasattr(user, 'is_authenticated') and not user.is_authenticated():
        user = None
    user_logged_out.send(sender=user.__class__, request=request, user=user)

    # remember language choice saved to session
    language = request.session.get(LANGUAGE_SESSION_KEY)

    request.session.flush()

    if language is not None:
        request.session[LANGUAGE_SESSION_KEY] = language

    if hasattr(request, 'user'):
        from django.contrib.auth.models import AnonymousUser
        request.user = AnonymousUser() 
Example #9
Source File: metrics.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def user_boards_contributed(user, include_removed=False, viewing_user=AnonymousUser):
    """Return list of boards contributed to by the user in reverse order (most recent contributions first).

    :param user: the user
    :param include_removed: True iff boards that have been removed should be included in the result
    :param viewing_user: user for calculating permissions
    """
    # basic approach: (1) merge, (2) sort, and (3) add making sure there's no duplicate boards
    def _boards(class_):
        models = (
            class_.objects.filter(creator=user)
            .order_by('-submit_date')
            .select_related('board', 'board__permissions')
        )
        return [(x.submit_date, x.board) for x in models if include_removed or not x.board.removed]
    contributions = sorted(itertools.chain(_boards(Evidence), _boards(Hypothesis)), key=lambda x: x[0], reverse=True)
    boards = [
        board
        for date, board in contributions
        if (include_removed or not board.removed) and board.can_read(viewing_user)
    ]
    return first_occurrences(boards) 
Example #10
Source File: test_ordering.py    From resolwe with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super().setUp()

        user_model = get_user_model()
        user = user_model.objects.create(username="user")

        self.proc_1 = Process.objects.create(
            name="My process", contributor=user, version=1
        )
        self.proc_2 = Process.objects.create(
            name="My process", contributor=user, version=2
        )

        assign_perm("view_process", AnonymousUser(), self.proc_1)
        assign_perm("view_process", AnonymousUser(), self.proc_2)

        self.url = reverse("resolwe-api:process-list") 
Example #11
Source File: __init__.py    From bioforum with MIT License 6 votes vote down vote up
def logout(request):
    """
    Remove the authenticated user's ID from the request and flush their session
    data.
    """
    # Dispatch the signal before the user is logged out so the receivers have a
    # chance to find out *who* logged out.
    user = getattr(request, 'user', None)
    if hasattr(user, 'is_authenticated') and not user.is_authenticated:
        user = None
    user_logged_out.send(sender=user.__class__, request=request, user=user)

    # remember language choice saved to session
    language = request.session.get(LANGUAGE_SESSION_KEY)

    request.session.flush()

    if language is not None:
        request.session[LANGUAGE_SESSION_KEY] = language

    if hasattr(request, 'user'):
        from django.contrib.auth.models import AnonymousUser
        request.user = AnonymousUser() 
Example #12
Source File: test_access_policy.py    From drf-access-policy with MIT License 6 votes vote down vote up
def test_get_statements_matching_principal_if_user_is_anonymous(self):
        user = AnonymousUser()

        statements = [
            {"principal": ["id:5"], "action": ["create"]},
            {"principal": ["*"], "action": ["list"]},
            {"principal": ["authenticated"], "action": ["authenticated_action"]},
            {"principal": ["anonymous"], "action": ["anonymous_action"]},
        ]

        policy = AccessPolicy()

        result = policy._get_statements_matching_principal(
            FakeRequest(user), statements
        )

        self.assertEqual(len(result), 2)
        self.assertEqual(result[0]["action"], ["list"])
        self.assertEqual(result[1]["action"], ["anonymous_action"]) 
Example #13
Source File: test_form_enter_data.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_public_with_link_to_share_toggle_on(self):
        # sharing behavior as of 09/13/2012:
        # it requires both data_share and form_share both turned on
        # in order to grant anon access to form uploading
        # TODO: findout 'for_user': 'all' and what it means
        response = self.client.post(self.perm_url, {'for_user': 'all',
                                    'perm_type': 'link'})
        self.assertEqual(response.status_code, 302)
        self.assertEqual(MetaData.public_link(self.xform), True)
        # toggle shared on
        self.xform.shared = True
        self.xform.shared_data = True
        self.xform.save()
        response = self.anon.get(self.show_url)
        self.assertEqual(response.status_code, 302)
        if not self._running_enketo():
            raise SkipTest
        with HTTMock(enketo_mock):
            factory = RequestFactory()
            request = factory.get('/')
            request.user = AnonymousUser()
            response = enter_data(
                request, self.user.username, self.xform.id_string)
            self.assertEqual(response.status_code, 302) 
Example #14
Source File: method.py    From py2swagger with MIT License 6 votes vote down vote up
def _create_view(self):
        """
        Creates DjangoRestFramework view
        :return: view
        """
        view = self.callback()

        view.kwargs = getattr(view, 'kwargs', dict())
        if hasattr(self.introspector.pattern, 'default_args'):
            view.kwargs.update(self.introspector.pattern.default_args)

        view.request = HttpRequest()
        view.request.user = AnonymousUser()
        view.request.method = self.method

        return view 
Example #15
Source File: test_permissions.py    From spacenews with MIT License 5 votes vote down vote up
def test_get_instance_if_anonymous(req):

    req.method = 'GET'
    req.user = AnonymousUser()

    perm = CommentPermission()
    assert perm.has_object_permission(req, mock.Mock(), Comment()) 
Example #16
Source File: test_permissions.py    From spacenews with MIT License 5 votes vote down vote up
def test_put_instance_if_anonymous(req):

    req.method = 'PUT'
    req.user = AnonymousUser()

    perm = CommentPermission()
    assert not perm.has_object_permission(req, mock.Mock(), Comment()) 
Example #17
Source File: profile.py    From pasportaservo with GNU Affero General Public License v3.0 5 votes vote down vote up
def _convert_profile_to_user(profile_obj):
    if isinstance(profile_obj, Profile):
        return profile_obj.user or AnonymousUser()
    else:
        return profile_obj 
Example #18
Source File: test_permissions.py    From spacenews with MIT License 5 votes vote down vote up
def test_delete_instance_if_anonymous(req):

    req.method = 'DELETE'
    req.user = AnonymousUser()

    perm = CommentPermission()
    assert not perm.has_object_permission(req, mock.Mock(), Comment()) 
Example #19
Source File: tests.py    From django-warrant with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_header_missing(self):
        request = self.factory.get('/does/not/matter')

        request.user = AnonymousUser()

        APIKeyMiddleware.process_request(request)

        # Test that missing headers responds properly
        self.assertFalse(hasattr(request, 'api_key')) 
Example #20
Source File: test_chat_forms.py    From pasportaservo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_clean_recipients(self):
        faker = Faker()

        # Writing to a deceased user is expected to raise an error.
        form = CustomAnonymousWriteForm(
            sender=AnonymousUser(),
            data={
                'recipients': self.recipient_deceased.username,
                'subject': faker.sentence(),
                'body': faker.paragraph(),
                'email': faker.email(),
            })
        self.assertFalse(form.is_valid())
        self.assertIn('recipients', form.errors)
        self.assertEqual(
            form.errors['recipients'],
            ["Some usernames are rejected: {}.".format(self.recipient_deceased.username)]
        )

        # Writing to a user who is alive is expected to result in no errors.
        form = CustomAnonymousWriteForm(
            sender=AnonymousUser(),
            data={
                'recipients': self.recipient_living.username,
                'subject': faker.sentence(),
                'body': faker.paragraph(),
                'email': faker.email(),
            })
        self.assertTrue(form.is_valid())

        # Writing to a user without profile is expected to result in no errors.
        form = CustomAnonymousWriteForm(
            sender=AnonymousUser(),
            data={
                'recipients': UserFactory(profile=None),
                'subject': faker.sentence(),
                'body': faker.paragraph(),
                'email': faker.email(),
            })
        self.assertTrue(form.is_valid()) 
Example #21
Source File: base.py    From django-sudo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.request = self.get("/foo")
        self.request.session = {}
        self.setUser(AnonymousUser()) 
Example #22
Source File: utils.py    From karrot-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, user=None):
        self.user = user or AnonymousUser() 
Example #23
Source File: test_acl.py    From waliki with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_any_logged_user(self):
        user1 = UserFactory()
        ACLRuleFactory(slug='page', permissions=['view_page'], apply_to=ACLRule.TO_LOGGED)
        users = ACLRule.get_users_for(['view_page'], 'page')
        self.assertNotIn(AnonymousUser(), users)
        self.assertIn(user1, users) 
Example #24
Source File: test_acl.py    From waliki with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_any_user(self):
        user1 = UserFactory()
        ACLRuleFactory(slug='page', permissions=['view_page'], apply_to=ACLRule.TO_ANY)
        users = ACLRule.get_users_for(['view_page'], 'page')
        self.assertIn(AnonymousUser(), users)
        self.assertIn(user1, users) 
Example #25
Source File: __init__.py    From bioforum with MIT License 5 votes vote down vote up
def get_user(request):
    """
    Return the user model instance associated with the given request session.
    If no user is retrieved, return an instance of `AnonymousUser`.
    """
    from .models import AnonymousUser
    user = None
    try:
        user_id = _get_user_session_key(request)
        backend_path = request.session[BACKEND_SESSION_KEY]
    except KeyError:
        pass
    else:
        if backend_path in settings.AUTHENTICATION_BACKENDS:
            backend = load_backend(backend_path)
            user = backend.get_user(user_id)
            # Verify the session
            if hasattr(user, 'get_session_auth_hash'):
                session_hash = request.session.get(HASH_SESSION_KEY)
                session_hash_verified = session_hash and constant_time_compare(
                    session_hash,
                    user.get_session_auth_hash()
                )
                if not session_hash_verified:
                    request.session.flush()
                    user = None

    return user or AnonymousUser() 
Example #26
Source File: UserFeed.py    From engage-backend with Apache License 2.0 5 votes vote down vote up
def get_queryset(self):
        print("get queryset")
        # Is there no test for figuring if req.user is of AnonymousUser type?
        data = []
        now = datetime.now(pytz.UTC)
        unixnow = calendar.timegm(now.utctimetuple())
        if (not isinstance(self.request.user, AnonymousUser)):
            user = EngageUser.objects.get(user=self.request.user)
            tags_query_set = user.tags.all()
            tag_names = list(map(lambda x: x.name, tags_query_set))
            agenda_items = AgendaItem.objects.filter(tags__name__in=tag_names).filter(
                agenda__meeting_time__contained_by=NumericRange(self.request.data['begin'], self.request.data['end']))
            if agenda_items[0].meeting_time > unixnow:
                meeting_held = False
            else:
                meeting_held = True
        else:
            # return the most recent agenda items for the upcoming meeting,
            # if there is no upcoming meeting, show the last meeting instead
            last_run = Agenda.objects.order_by('-meeting_time')[0]
            if last_run.meeting_time > unixnow:
                meeting_held = False
            else:
                meeting_held = True

            agenda_items = last_run.items.all()

        for ag_item in agenda_items:
            data.append({"item": ag_item, "tag": list(
                ag_item.tags.all()), "meeting_already_held": meeting_held})
        return data 
Example #27
Source File: fixtures.py    From wagtail-tag-manager with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def request(self, **request):
        request["user"] = None
        request = super(RequestFactory, self).request(**request)
        request.user = AnonymousUser()
        request.session = SessionStore()
        request._messages = FallbackStorage(request)
        return request 
Example #28
Source File: utils.py    From django-cas-ng with MIT License 5 votes vote down vote up
def get_user_from_session(session: SessionBase) -> Union[User, AnonymousUser]:
    """
    Get User object (or AnonymousUser() if not logged in) from session.
    """
    try:
        user_id = session[SESSION_KEY]
        backend_path = session[BACKEND_SESSION_KEY]
        backend = load_backend(backend_path)
        return backend.get_user(user_id) or AnonymousUser()
    except KeyError:
        return AnonymousUser() 
Example #29
Source File: test_middleware.py    From django-cas-ng with MIT License 5 votes vote down vote up
def _process_view_with_middleware(
        middleware_cls, url, view_func):
    middleware = middleware_cls()
    request_factory = RequestFactory()
    request = request_factory.get(url)
    request.user = AnonymousUser()
    return middleware.process_view(request, view_func,
                                   view_args=(), view_kwargs={}) 
Example #30
Source File: real_connection_tests.py    From django-influxdb-metrics with MIT License 5 votes vote down vote up
def test_middleware(self):
        self.influxdb_client.delete_series(measurement='django_request')

        req = RequestFactory().get('/?campaign=bingo')
        req.META['HTTP_REFERER'] = 'http://google.co.uk/foobar/'
        req.user = AnonymousUser()
        mware = InfluxDBRequestMiddleware()
        mware.process_view(req, 'view_funx', 'view_args', 'view_kwargs')
        mware.process_exception(req, None)

        results = list(query('select * from django_request'))
        self.assertEqual(len(results), 1)
        result = results[0][0]
        self.assertEqual(result['value'], 0)