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

The following are 30 code examples for showing how to use django.contrib.auth.models.AnonymousUser(). 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.contrib.auth.models , or try the search function .

Example 1
Project: py2swagger   Author: Arello-Mobile   File: method.py    License: 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 2
Project: open-synthesis   Author: twschiller   File: metrics.py    License: 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 3
Project: resolwe   Author: genialis   File: test_api.py    License: Apache License 2.0 6 votes vote down vote up
def test_collection_data_count(self):
        data1 = self._create_data()
        data2 = self._create_data()

        entity = self._create_entity([data1, data2])

        collection1 = Collection.objects.create(contributor=self.contributor)
        assign_perm("view_collection", AnonymousUser(), collection1)

        collection2 = Collection.objects.create(contributor=self.contributor)
        assign_perm("view_collection", AnonymousUser(), collection2)
        collection2.entity_set.add(entity)
        collection2.data.add(data1, data2)

        response = self.client.get(self.detail_url(collection1.id))
        self.assertEqual(response.data["data_count"], 0)

        response = self.client.get(self.detail_url(collection2.id))
        self.assertEqual(response.data["data_count"], 2) 
Example 4
Project: resolwe   Author: genialis   File: test_ordering.py    License: 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 5
Project: resolwe   Author: genialis   File: test_ordering.py    License: 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 6
Project: django-defender   Author: jazzband   File: tests.py    License: 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 7
Project: django-defender   Author: jazzband   File: tests.py    License: 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
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: 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
Project: GTDWeb   Author: lanbing510   File: context_processors.py    License: 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 10
Project: drf-access-policy   Author: rsinger86   File: test_access_policy.py    License: 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 11
Project: kobo-predict   Author: awemulya   File: test_form_enter_data.py    License: 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 12
Project: bioforum   Author: reBiocoder   File: __init__.py    License: 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 13
Project: bioforum   Author: reBiocoder   File: context_processors.py    License: 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 14
Project: waliki   Author: mgaitan   File: models.py    License: 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 15
Project: aiohttp-json-rpc   Author: pengutronix   File: django.py    License: 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 16
Project: controller   Author: deis   File: authentication.py    License: MIT License 5 votes vote down vote up
def authenticate(self, request):
        """
        Authenticate the request for anyone!
        """
        return AnonymousUser(), None 
Example 17
Project: controller   Author: deis   File: authentication.py    License: MIT License 5 votes vote down vote up
def authenticate(self, request):
        """
        Authenticate the request for anyone or if a valid token is provided, a user.
        """
        try:
            return TokenAuthentication.authenticate(TokenAuthentication(), request)
        except:
            return AnonymousUser(), None 
Example 18
Project: figures   Author: appsembler   File: test_figures_home_view.py    License: MIT License 5 votes vote down vote up
def test_anonymous_user(self):
        '''Verify that anonymous users (not logged in) get redirected to login
        '''
        request = self.factory.get(reverse('figures-home'))
        request.user = AnonymousUser()
        response = figures_home(request)
        assert response.status_code == 302
        assert response['location'].startswith(self.redirect_startswith) 
Example 19
Project: django-oauth-toolkit-jwt   Author: Humanitec   File: authentication.py    License: MIT License 5 votes vote down vote up
def authenticate_credentials(self, payload):
        """
        Returns an active user that matches the payload's user id and email.
        """
        if getattr(settings, 'JWT_AUTH_DISABLED', False):
            return AnonymousUser()

        User = get_user_model()
        username = payload.get(getattr(settings, 'JWT_ID_ATTRIBUTE'))

        if not username:
            msg = 'Invalid payload.'
            raise exceptions.AuthenticationFailed(msg)

        try:
            kwargs = {
                getattr(settings, 'JWT_ID_ATTRIBUTE'): username
            }
            user = User.objects.get(**kwargs)
        except User.DoesNotExist:
            msg = 'Invalid signature.'
            raise exceptions.AuthenticationFailed(msg)

        if not user.is_active:
            msg = 'User account is disabled.'
            raise exceptions.AuthenticationFailed(msg)

        return user 
Example 20
Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        factory = RequestFactory()
        self.request = factory.get('/', {'page': 3, 'sort': 'asc'})
        self.request.user = AnonymousUser()
        # Simulate that we get throught the middleware
        self.request.franchise = None 
Example 21
Project: donation-tracker   Author: GamesDoneQuick   File: util.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.rand = random.Random()
        self.factory = RequestFactory()
        self.locked_event = models.Event.objects.create(
            datetime=long_ago_noon, targetamount=5, short='locked', name='Locked Event'
        )
        self.event = models.Event.objects.create(
            datetime=today_noon, targetamount=5, short='event', name='Test Event'
        )
        self.anonymous_user = AnonymousUser()
        self.user = User.objects.create(username='test')
        self.add_user = User.objects.create(username='add')
        self.locked_user = User.objects.create(username='locked')
        self.locked_user.user_permissions.add(
            Permission.objects.get(name='Can edit locked events')
        )
        if self.model_name:
            self.add_user.user_permissions.add(
                Permission.objects.get(name='Can add %s' % self.model_name),
                Permission.objects.get(name='Can change %s' % self.model_name),
            )
            self.locked_user.user_permissions.add(
                Permission.objects.get(name='Can add %s' % self.model_name),
                Permission.objects.get(name='Can change %s' % self.model_name),
            )
        self.super_user = User.objects.create(username='super', is_superuser=True)
        self.maxDiff = None 
Example 22
Project: donation-tracker   Author: GamesDoneQuick   File: test_me.py    License: Apache License 2.0 5 votes vote down vote up
def test_anonymous_user(self):
        self.request.user = AnonymousUser()
        self.assertEqual(
            self.parseJSON(tracker.views.me(self.request), 403),
            {'error': 'Permission Denied', 'exception': '',},
        ) 
Example 23
Project: donation-tracker   Author: GamesDoneQuick   File: search_feeds.py    License: Apache License 2.0 5 votes vote down vote up
def apply_feed_filter(query, model, feed_name, params=None, user=None):
    params = params or {}
    noslice = canonical_bool(params.pop('noslice', False))
    user = user or AnonymousUser()
    if model == 'donation':
        query = donation_feed_filter(feed_name, noslice, params, query, user)
    elif model in ['bid', 'bidtarget', 'allbids']:
        query = bid_feed_filter(feed_name, noslice, params, query, user)
    elif model == 'run':
        query = run_feed_filter(feed_name, noslice, params, query)
    elif model == 'prize':
        query = prize_feed_filter(feed_name, noslice, params, query, user)
    elif model == 'event':
        query = event_feed_filter(feed_name, params, query)
    return query 
Example 24
Project: donation-tracker   Author: GamesDoneQuick   File: search_filters.py    License: Apache License 2.0 5 votes vote down vote up
def check_field_permissions(rootmodel, key, value, user=None):
    user = user or AnonymousUser()
    toks = key.split('__')
    if len(toks) >= 2:
        tail = toks[-2]
        rootmodel = _FKMap.get(tail, tail)
    field = toks[-1]
    # cannot search for locked=True unless you can view locked events
    if (
        field == 'locked'
        and canonical_bool(value)
        and not user.has_perm('tracker.view_locked_events')
    ):
        raise PermissionDenied
    if rootmodel == 'donor':
        if (field in _DonorEmailFields) and not user.has_perm('tracker.view_emails'):
            raise PermissionDenied
        elif (field in _DonorNameFields) and not user.has_perm(
            'tracker.view_usernames'
        ):
            raise PermissionDenied
    elif rootmodel == 'donation':
        if (field == 'testdonation') and not user.has_perm('tracker.view_test'):
            raise PermissionDenied
        if (field == 'comment') and not user.has_perm('tracker.view_comments'):
            raise PermissionDenied
    elif rootmodel in ['bid', 'allbids', 'bidtarget']:
        if (
            (field == 'state')
            and not user.has_perm('tracker.view_hidden')
            and value not in ['OPENED', 'CLOSED']
        ):
            raise PermissionDenied 
Example 25
Project: open-synthesis   Author: twschiller   File: metrics.py    License: GNU General Public License v3.0 5 votes vote down vote up
def user_boards_created(user, viewing_user=AnonymousUser):
    """Return queryset of boards created by user in reverse creation order (most recently created first)."""
    return Board.objects.user_readable(viewing_user).filter(creator=user) 
Example 26
Project: open-synthesis   Author: twschiller   File: metrics.py    License: GNU General Public License v3.0 5 votes vote down vote up
def user_boards_evaluated(user, include_removed=False, viewing_user=AnonymousUser):
    """Return list of boards evaluated by user in reverse order of evaluation (most recently evaluated 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
    """
    evaluations = Evaluation.objects.filter(user=user).order_by('-timestamp')
    boards = [
        e.board
        for e in evaluations.select_related('board', 'board__permissions')
        if (include_removed or not e.board.removed) and e.board.can_read(viewing_user)
    ]
    return first_occurrences(boards) 
Example 27
Project: coursys   Author: sfu-fas   File: middleware.py    License: GNU General Public License v3.0 5 votes vote down vote up
def process_request(self, request):
        assert hasattr(request, 'user'), (
            "'django.contrib.auth.middleware.AuthenticationMiddleware' must be before Authentication2FAMiddleware."
        )

        # By the time we get here, Django's AuthenticationMiddleware has checked the standard authentication:
        # password-authenticated session is good for request.user (or it's an AnonymousUser).

        # All we can do here is tighten the restrictions (unless we set request.user to a real User instance, which
        # we don't).

        # It might be more efficient to make request.user and request.maybe_stale_user SimpleLazyObject, but since
        # almost all of our requests are authenticated, they would be fired anyway.

        password_user = request.user # the user who was password-authenticated by Django
        request.maybe_stale_user = password_user
        request.session_info = SessionInfo.for_request(request, user=password_user)

        if not password_user.is_authenticated:
            # No user authenticated in any way: we have nothing more to check.
            return

        # Do the django_otp verification checks, so we know that there's a 2fa on the session.
        self._verify_user(request, password_user)
        if needs_2fa(request, password_user) and not password_user.is_verified():
            # User has password-authenticated, but 2FA is required and we don't have it.
            request.user = AnonymousUser()
            return

        if not auth_okay(request, password_user):
            # User has password-authenticated and 2FA, but they're out of date by our standards.
            request.user = AnonymousUser()
            return 
Example 28
Project: arches   Author: archesproject   File: auth_tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_set_anonymous_user_middleware(self):
        """
        Test to check that any anonymous request to the system gets the anonymous user set on the
        request as opposed to the built-in AnonymousUser supplied by django

        """

        request = self.factory.get(reverse("home"))
        request.user = AnonymousUser()
        set_anonymous_user(request)

        self.assertTrue(request.user.username == "anonymous")
        self.assertTrue(request.user != AnonymousUser()) 
Example 29
Project: django-mptt-comments   Author: zmrenwu   File: test_forms.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        self.target_object = Site.objects.create(name='test', domain='test.com')
        self.auth_user = User.objects.create_user('user', 'test')
        self.anon_user = AnonymousUser() 
Example 30
Project: resolwe   Author: genialis   File: test_shortcuts.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super().setUp()

        self.admin.delete()
        self.user1 = get_user_model().objects.create(username="test_user1")
        self.user2 = get_user_model().objects.create(username="test_user2")
        self.group1 = Group.objects.create(name="Test group 1")
        self.group2 = Group.objects.create(name="Test group 2")
        self.anonymous = AnonymousUser()

        self.collection = Collection.objects.create(
            contributor=self.user1, name="Test collection",
        )