Python django.contrib.auth.models.User() Examples
The following are 30
code examples of django.contrib.auth.models.User().
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: serializers.py From controller with MIT License | 7 votes |
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
Source File: test_api.py From normandy with Mozilla Public License 2.0 | 6 votes |
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 #3
Source File: test_access_policy.py From drf-access-policy with MIT License | 6 votes |
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 #4
Source File: views.py From controller with MIT License | 6 votes |
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 #5
Source File: tests.py From django-payfast with MIT License | 6 votes |
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 #6
Source File: views.py From controller with MIT License | 6 votes |
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 #7
Source File: views.py From controller with MIT License | 6 votes |
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 #8
Source File: views.py From controller with MIT License | 6 votes |
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 #9
Source File: boards.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
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 #10
Source File: test_api.py From normandy with Mozilla Public License 2.0 | 6 votes |
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 #11
Source File: forms.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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 #12
Source File: resource.py From arches with GNU Affero General Public License v3.0 | 6 votes |
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 #13
Source File: users_api_2_3_tests.py From seqr with GNU Affero General Public License v3.0 | 6 votes |
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 #14
Source File: teams.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
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 #15
Source File: teams.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
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 #16
Source File: views.py From OpenBench with GNU General Public License v3.0 | 6 votes |
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 #17
Source File: teams.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
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 #18
Source File: views.py From OpenBench with GNU General Public License v3.0 | 6 votes |
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 #19
Source File: teams.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
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 #20
Source File: createadmin.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
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 #21
Source File: views.py From OpenBench with GNU General Public License v3.0 | 6 votes |
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 #22
Source File: mobile_survey.py From arches with GNU Affero General Public License v3.0 | 6 votes |
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 #23
Source File: test_access_policy.py From drf-access-policy with MIT License | 5 votes |
def setUp(self): User.objects.all().delete() Group.objects.all().delete()
Example #24
Source File: test_access_policy.py From drf-access-policy with MIT License | 5 votes |
def test_get_user_group_values(self): group1 = Group.objects.create(name="admin") group2 = Group.objects.create(name="ceo") user = User.objects.create(username="mr user") user.groups.add(group1, group2) policy = AccessPolicy() result = sorted(policy.get_user_group_values(user)) self.assertEqual(result, ["admin", "ceo"])
Example #25
Source File: users_api_2_3_tests.py From seqr with GNU Affero General Public License v3.0 | 5 votes |
def test_forgot_password(self, mock_send_mail): url = reverse(forgot_password) # send invalid requests response = self.client.post(url, content_type='application/json', data=json.dumps({})) self.assertEqual(response.status_code, 400) self.assertEqual(response.reason_phrase, 'Email is required') response = self.client.post(url, content_type='application/json', data=json.dumps({ 'email': 'test_new_user@test.com' })) self.assertEqual(response.status_code, 400) self.assertEqual(response.reason_phrase, 'No account found for this email') # Send valid request response = self.client.post(url, content_type='application/json', data=json.dumps({ 'email': 'test_user@test.com' })) self.assertEqual(response.status_code, 200) expected_email_content = """ Hi there Test User-- Please click this link to reset your seqr password: /users/set_password/pbkdf2_sha256%2430000%24y85kZgvhQ539%24jrEC3L1IhCezUx3Itp%2B14w%2FT7U6u5XUxtpBZXKv8eh4%3D?reset=true """ mock_send_mail.assert_called_with( 'Reset your seqr password', expected_email_content, None, ['test_user@test.com'], fail_silently=False, ) # Test email failure mock_send_mail.side_effect = AnymailError('Connection err') response = self.client.post(url, content_type='application/json', data=json.dumps({ 'email': 'test_user@test.com' })) self.assertEqual(response.status_code, 400) self.assertEqual(response.reason_phrase, 'Connection err')
Example #26
Source File: test_access_policy.py From drf-access-policy with MIT License | 5 votes |
def test_get_statements_matching_principalif_user_is_authenticated(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": ["anonymous"], "action": ["anonymous_action"]}, {"principal": ["authenticated"], "action": ["authenticated_action"]}, ] policy = AccessPolicy() result = policy._get_statements_matching_principal( FakeRequest(user), statements ) self.assertEqual(len(result), 4) self.assertEqual(result[0]["action"], ["create"]) self.assertEqual(result[1]["action"], ["do_something"]) self.assertEqual(result[2]["action"], ["*"]) self.assertEqual(result[3]["action"], ["authenticated_action"])
Example #27
Source File: test_admin.py From open-synthesis with GNU General Public License v3.0 | 5 votes |
def test_settings_created(self): """Test that a settings object is created when the user is created.""" self.client.post('/accounts/signup/', data=self.valid_data) user = User.objects.filter(username=self.username).first() self.assertIsNotNone(user.settings, 'User settings object not created')
Example #28
Source File: test_access_policy.py From drf-access-policy with MIT License | 5 votes |
def test_evaluate_statements_false_any_deny(self,): policy = AccessPolicy() user = User.objects.create(username="mr user") statements = [ {"principal": "*", "action": "*", "effect": "deny"}, {"principal": "*", "action": "*", "effect": "allow"}, ] result = policy._evaluate_statements([], FakeRequest(user), None, "create") self.assertFalse(result)
Example #29
Source File: test_access_policy.py From drf-access-policy with MIT License | 5 votes |
def test_evaluate_statements_true_if_any_allow_and_none_deny(self,): policy = AccessPolicy() user = User.objects.create(username="mr user") statements = [ {"principal": "*", "action": "create", "effect": "allow"}, {"principal": "*", "action": "take_out_the_trash", "effect": "allow"}, ] result = policy._evaluate_statements( statements, FakeRequest(user), None, "create" ) self.assertTrue(result)
Example #30
Source File: teams.py From open-synthesis with GNU General Public License v3.0 | 5 votes |
def leave_team(request, team_id): team = get_object_or_404(Team, pk=team_id) if not team.members.filter(id=request.user.id).exists(): raise SuspiciousOperation(_('User is not a member of the team')) else: team.members.remove(request.user) team.save() messages.success(request, _('Left team {name}').format(name=team.name)) return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))