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

The following are 30 code examples for showing how to use django.contrib.auth.models.User(). 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: controller   Author: deis   File: serializers.py    License: MIT License 7 votes vote down vote up
def create(self, validated_data):
        now = timezone.now()
        user = User(
            email=validated_data.get('email'),
            username=validated_data.get('username'),
            last_login=now,
            date_joined=now,
            is_active=True
        )

        if validated_data.get('first_name'):
            user.first_name = validated_data['first_name']

        if validated_data.get('last_name'):
            user.last_name = validated_data['last_name']

        user.set_password(validated_data['password'])
        # Make the first signup an admin / superuser
        if not User.objects.filter(is_superuser=True).exists():
            user.is_superuser = user.is_staff = True

        user.save()
        return user 
Example 2
Project: controller   Author: deis   File: views.py    License: MIT License 6 votes vote down vote up
def destroy(self, request, **kwargs):
        calling_obj = self.get_object()
        target_obj = calling_obj

        if request.data.get('username'):
            # if you "accidentally" target yourself, that should be fine
            if calling_obj.username == request.data['username'] or calling_obj.is_superuser:
                target_obj = get_object_or_404(User, username=request.data['username'])
            else:
                raise PermissionDenied()

        # A user can not be removed without apps changing ownership first
        if len(models.App.objects.filter(owner=target_obj)) > 0:
            msg = '{} still has applications assigned. Delete or transfer ownership'.format(str(target_obj))  # noqa
            raise AlreadyExists(msg)

        try:
            target_obj.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        except ProtectedError as e:
            raise AlreadyExists(e) 
Example 3
Project: controller   Author: deis   File: views.py    License: MIT License 6 votes vote down vote up
def passwd(self, request, **kwargs):
        if not request.data.get('new_password'):
            raise DeisException("new_password is a required field")

        caller_obj = self.get_object()
        target_obj = self.get_object()
        if request.data.get('username'):
            # if you "accidentally" target yourself, that should be fine
            if caller_obj.username == request.data['username'] or caller_obj.is_superuser:
                target_obj = get_object_or_404(User, username=request.data['username'])
            else:
                raise PermissionDenied()

        if not caller_obj.is_superuser:
            if not request.data.get('password'):
                raise DeisException("password is a required field")
            if not target_obj.check_password(request.data['password']):
                raise AuthenticationFailed('Current password does not match')

        target_obj.set_password(request.data['new_password'])
        target_obj.save()
        return Response({'status': 'password set'}) 
Example 4
Project: controller   Author: deis   File: views.py    License: MIT License 6 votes vote down vote up
def update(self, request, **kwargs):
        app = self.get_object()
        old_owner = app.owner

        if request.data.get('owner'):
            if self.request.user != app.owner and not self.request.user.is_superuser:
                raise PermissionDenied()
            new_owner = get_object_or_404(User, username=request.data['owner'])
            app.owner = new_owner
            # ensure all downstream objects that are owned by this user and are part of this app
            # is also updated
            for downstream_model in [models.AppSettings, models.Build, models.Config,
                                     models.Domain, models.Release, models.TLS]:
                downstream_model.objects.filter(owner=old_owner, app=app).update(owner=new_owner)
        app.save()
        return Response(status=status.HTTP_200_OK) 
Example 5
Project: controller   Author: deis   File: views.py    License: MIT License 6 votes vote down vote up
def users(self, request, *args, **kwargs):
        app = get_object_or_404(models.App, id=kwargs['id'])
        request.user = get_object_or_404(User, username=kwargs['username'])
        # check the user is authorized for this app
        if not permissions.is_app_user(request, app):
            raise PermissionDenied()

        data = {request.user.username: []}
        keys = models.Key.objects \
                     .filter(owner__username=kwargs['username']) \
                     .values('public', 'fingerprint') \
                     .order_by('created')
        if not keys:
            raise NotFound("No Keys match the given query.")

        for info in keys:
            data[request.user.username].append({
                'key': info['public'],
                'fingerprint': info['fingerprint']
            })

        return Response(data, status=status.HTTP_200_OK) 
Example 6
Project: django-payfast   Author: PiDelport   File: tests.py    License: MIT License 6 votes vote down vote up
def test_init_with_user_custom_names_disabled(self):
        user = User.objects.create(
            username='example_user',
            email='user@example.com',
            first_name='First',
            last_name='Last',
        )
        form = PayFastForm(
            initial={
                'amount': 100,
                'item_name': 'Example item',
            },
            user=user
        )
        self.assertEqual({
            'amount': 100,
            'email_address': 'user@example.com',
            'item_name': 'Example item',
            'm_payment_id': '1',
            'merchant_id': '10000100',
            'merchant_key': '46f0cd694581a',
            'notify_url': notify_url(),
        }, form.initial)
        self.assertEqual(user, form.order.user) 
Example 7
Project: normandy   Author: mozilla   File: test_api.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def test_it_works(self, api_client, settings):
        user = User.objects.first()  # Get the default user
        settings.PEER_APPROVAL_ENFORCED = False

        res = api_client.get("/api/v3/service_info/")
        assert res.status_code == 200
        assert res.data == {
            "user": {
                "id": user.id,
                "first_name": user.first_name,
                "last_name": user.last_name,
                "email": user.email,
            },
            "peer_approval_enforced": settings.PEER_APPROVAL_ENFORCED,
            "github_url": settings.GITHUB_URL,
        } 
Example 8
Project: normandy   Author: mozilla   File: test_api.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def test_it_works(self, api_client):
        user = User.objects.first()
        group = GroupFactory()
        user.groups.add(group)
        res = api_client.get("/api/v3/user/")
        assert res.status_code == 200
        assert res.data == {
            "count": 1,
            "next": None,
            "previous": None,
            "results": [
                {
                    "id": user.id,
                    "first_name": user.first_name,
                    "last_name": user.last_name,
                    "email": user.email,
                    "groups": [{"id": group.id, "name": group.name}],
                }
            ],
        } 
Example 9
Project: OpenBench   Author: AndyGrant   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def login(request):

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    #                                                                         #
    #  GET  : Return the HTML template used for logging in a User             #
    #                                                                         #
    #  POST : Attempt to login the User and authenticate their credentials.   #
    #         If their login is invalid, let them know. In all cases, return  #
    #         the User back to the main page                                  #
    #                                                                         #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

    if request.method == 'GET':
        return render(request, 'login.html')

    user = django.contrib.auth.authenticate(
        username=request.POST['username'],
        password=request.POST['password'])

    if user is None:
        return index(request, error='Unable to Authenticate User')

    django.contrib.auth.login(request, user)
    return django.http.HttpResponseRedirect('/index/') 
Example 10
Project: OpenBench   Author: AndyGrant   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def clientGetWorkload(request):

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    #                                                                         #
    #  POST : Return a Dictionary of data in order to complete a workload. If #
    #         there are no tests for the User, 'None' will be returned. If we #
    #         cannot authenticate the User, 'Bad Credentials' is returned. If #
    #         the posted Machine does not belong the the User, 'Bad Machine'  #
    #         is returned.                                                    #
    #                                                                         #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

    # Verify the User's credentials
    user = django.contrib.auth.authenticate(
        username=request.POST['username'],
        password=request.POST['password'])
    if user == None: return HttpResponse('Bad Credentials')

    # getWorkload() will verify the integrity of the request
    return HttpResponse(OpenBench.utils.getWorkload(user, request)) 
Example 11
Project: OpenBench   Author: AndyGrant   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def clientSubmitNPS(request):

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    #                                                                         #
    #  POST : Report the speed of the engines in the currently running Test   #
    #         for the User and his Machine. We save this value to display     #
    #                                                                         #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

    # Verify the User's credentials
    user = django.contrib.auth.authenticate(
        username=request.POST['username'],
        password=request.POST['password'])
    if user == None: return HttpResponse('Bad Credentials')

    # Verify the Machine belongs to the User
    machine = Machine.objects.get(id=int(request.POST['machineid']))
    if machine.user != user: return HttpResponse('Bad Machine')

    # Update the NPS and return 'None' to signal no errors
    machine.mnps = float(request.POST['nps']) / 1e6; machine.save()
    return HttpResponse('None') 
Example 12
Project: open-synthesis   Author: twschiller   File: boards.py    License: GNU General Public License v3.0 6 votes vote down vote up
def user_board_listing(request, account_id):
    """Return a paginated board listing view for account with account_id."""
    metric_timeout_seconds = 60 * 2

    queries = {
        # default to boards contributed to
        None: lambda x: ('contributed to', user_boards_contributed(x, viewing_user=request.user)),
        'created': lambda x: ('created', user_boards_created(x, viewing_user=request.user)),
        'evaluated': lambda x: ('evaluated', user_boards_evaluated(x, viewing_user=request.user)),
        'contribute': lambda x: ('contributed to', user_boards_contributed(x, viewing_user=request.user)),
    }

    user = get_object_or_404(User, pk=account_id)
    query = request.GET.get('query')
    verb, board_list = queries.get(query, queries[None])(user)
    desc = _('List of intelligence boards user {username} has {verb}').format(username=user.username, verb=verb)
    context = {
        'user': user,
        'boards': make_paginator(request, board_list),
        'contributors': cache.get_or_set('contributor_count', generate_contributor_count(), metric_timeout_seconds),
        'evaluators': cache.get_or_set('evaluator_count', generate_evaluator_count(), metric_timeout_seconds),
        'meta_description': desc,
        'verb': verb
    }
    return render(request, 'boards/user_boards.html', context) 
Example 13
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 14
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 15
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 16
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 17
Project: open-synthesis   Author: twschiller   File: createadmin.py    License: GNU General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        """Handle the command invocation."""
        email = getattr(settings, 'ADMIN_EMAIL_ADDRESS', None)
        username = getattr(settings, 'ADMIN_USERNAME', None)
        password = getattr(settings, 'ADMIN_PASSWORD', None)

        if not email or not username or not password:
            raise CommandError('ADMIN_USERNAME, ADMIN_PASSWORD, and ADMIN_EMAIL_ADDRESS must be set')

        admin = User(username=username, email=email)
        admin.set_password(password)
        admin.is_superuser = True
        admin.is_staff = True
        admin.save()

        msg = 'Successfully configured admin %s (%s)' % (username, email)
        self.stdout.write(self.style.SUCCESS(msg))  # pylint: disable=no-member 
Example 18
Project: seqr   Author: macarthur-lab   File: users_api_2_3_tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_set_password(self):
        username = 'test_new_user'
        user = User.objects.create_user(username)
        password = user.password
        auth_user = auth.get_user(self.client)
        self.assertNotEqual(user, auth_user)

        set_password_url = reverse(set_password, args=[username])
        response = self.client.post(set_password_url, content_type='application/json', data=json.dumps({}))
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.reason_phrase, 'Password is required')

        response = self.client.post(set_password_url, content_type='application/json', data=json.dumps({
            'password': 'password123', 'firstName': 'Test'}))
        self.assertEqual(response.status_code, 200)

        user = User.objects.get(username='test_new_user')
        self.assertEqual(user.first_name, 'Test')
        self.assertFalse(user.password == password)

        auth_user = auth.get_user(self.client)
        self.assertEqual(user, auth_user) 
Example 19
Project: arches   Author: archesproject   File: mobile_survey.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def update_identities(
        self, data, mobile_survey, related_identities, identity_type="users", identity_model=User, xmodel=models.MobileSurveyXUser
    ):
        mobile_survey_identity_ids = {u.id for u in related_identities}
        identities_to_remove = mobile_survey_identity_ids - set(data[identity_type])
        identities_to_add = set(data[identity_type]) - mobile_survey_identity_ids

        for identity in identities_to_add:
            if identity_type == "users":
                xmodel.objects.create(user=identity_model.objects.get(id=identity), mobile_survey=mobile_survey)
            else:
                xmodel.objects.create(group=identity_model.objects.get(id=identity), mobile_survey=mobile_survey)

        for identity in identities_to_remove:
            if identity_type == "users":
                xmodel.objects.filter(user=identity_model.objects.get(id=identity), mobile_survey=mobile_survey).delete()
            else:
                xmodel.objects.filter(group=identity_model.objects.get(id=identity), mobile_survey=mobile_survey).delete() 
Example 20
Project: arches   Author: archesproject   File: resource.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def delete(self, request, resourceid=None):
        delete_error = _("Unable to Delete Resource")
        delete_msg = _("User does not have permissions to delete this instance because the instance or its data is restricted")
        try:
            if resourceid is not None:
                if user_can_delete_resource(request.user, resourceid) is False:
                    return JSONErrorResponse(delete_error, delete_msg)
                ret = Resource.objects.get(pk=resourceid)
                try:
                    deleted = ret.delete(user=request.user)
                except ModelInactiveError as e:
                    message = _("Unable to delete. Please verify the model status is active")
                    return JSONResponse({"status": "false", "message": [_(e.title), _(str(message))]}, status=500)
                except PermissionDenied:
                    return JSONErrorResponse(delete_error, delete_msg)
                if deleted is True:
                    return JSONResponse(ret)
                else:
                    return JSONErrorResponse(delete_error, delete_msg)
            return HttpResponseNotFound()
        except PermissionDenied:
            return JSONErrorResponse(delete_error, delete_msg) 
Example 21
Project: GTDWeb   Author: lanbing510   File: forms.py    License: GNU General Public License v2.0 6 votes vote down vote up
def confirm_login_allowed(self, user):
        """
        Controls whether the given User may log in. This is a policy setting,
        independent of end-user authentication. This default behavior is to
        allow login by active users, and reject login by inactive users.

        If the given user cannot log in, this method should raise a
        ``forms.ValidationError``.

        If the given user may log in, this method should return None.
        """
        if not user.is_active:
            raise forms.ValidationError(
                self.error_messages['inactive'],
                code='inactive',
            ) 
Example 22
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_action_when_method_unsafe(self):
        cooks = Group.objects.create(name="cooks")
        user = User.objects.create(id=5)
        user.groups.add(cooks)

        statements = [
            {"principal": ["id:5"], "action": ["create"]},
            {"principal": ["group:dev"], "action": ["destroy"]},
            {"principal": ["group:cooks"], "action": ["do_something"]},
            {"principal": ["*"], "action": ["*"]},
            {"principal": ["id:79"], "action": ["vote"]},
            {"principal": ["id:900"], "action": ["<safe_methods>"]},
        ]

        policy = AccessPolicy()

        result = policy._get_statements_matching_action(
            FakeRequest(user, method="DELETE"), "destroy", statements
        )

        self.assertEqual(len(result), 2)
        self.assertEqual(result[0]["action"], ["destroy"])
        self.assertEqual(result[1]["action"], ["*"]) 
Example 23
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def get_queryset(self):
        return User.objects.filter(pk=self.request.user.pk) 
Example 24
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def get_queryset(self):
        return User.objects.filter(pk=self.request.user.pk) 
Example 25
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def create(self, request, *args, **kwargs):
        app = get_object_or_404(models.App, id=request.data['receive_repo'])
        self.user = request.user = get_object_or_404(User, username=request.data['receive_user'])
        # check the user is authorized for this app
        if not permissions.is_app_user(request, app):
            raise PermissionDenied()
        request.data['app'] = app
        request.data['owner'] = self.user
        super(BuildHookViewSet, self).create(request, *args, **kwargs)
        # return the application databag
        response = {'release': {'version': app.release_set.filter(failed=False).latest().version}}
        return Response(response, status=status.HTTP_200_OK) 
Example 26
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def create(self, request, *args, **kwargs):
        app = get_object_or_404(models.App, id=request.data['receive_repo'])
        request.user = get_object_or_404(User, username=request.data['receive_user'])
        # check the user is authorized for this app
        if not permissions.is_app_user(request, app):
            raise PermissionDenied()
        config = app.release_set.filter(failed=False).latest().config
        serializer = self.get_serializer(config)
        return Response(serializer.data, status=status.HTTP_200_OK) 
Example 27
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def create(self, request, **kwargs):
        app = self.get_object()
        if not permissions.IsOwnerOrAdmin.has_object_permission(permissions.IsOwnerOrAdmin(),
                                                                request, self, app):
            raise PermissionDenied()

        user = get_object_or_404(User, username=request.data['username'])
        assign_perm(self.perm, user, app)
        app.log("User {} was granted access to {}".format(user, app))
        return Response(status=status.HTTP_201_CREATED) 
Example 28
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def create(self, request, **kwargs):
        user = get_object_or_404(User, username=request.data['username'])
        user.is_superuser = user.is_staff = True
        user.save(update_fields=['is_superuser', 'is_staff'])
        return Response(status=status.HTTP_201_CREATED) 
Example 29
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def destroy(self, request, **kwargs):
        user = get_object_or_404(User, username=kwargs['username'])
        user.is_superuser = user.is_staff = False
        user.save(update_fields=['is_superuser', 'is_staff'])
        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 30
Project: django-payfast   Author: PiDelport   File: tests.py    License: MIT License 5 votes vote down vote up
def test_init_with_user(self):
        user = User.objects.create(
            username='example_user',
            email='user@example.com',
            first_name='First',
            last_name='Last',
        )
        form = PayFastForm(
            initial={
                'amount': 100,
                'item_name': 'Example item',
            },
            user=user
        )
        self.assertEqual({
            'amount': 100,
            'email_address': 'user@example.com',
            'item_name': 'Example item',
            'm_payment_id': '1',
            'merchant_id': '10000100',
            'merchant_key': '46f0cd694581a',
            'name_first': 'First',
            'name_last': 'Last',
            'notify_url': notify_url(),
        }, form.initial)
        self.assertEqual(user, form.order.user)