Python django.contrib.auth.authenticate() Examples
The following are 30
code examples of django.contrib.auth.authenticate().
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
, or try the search function
.
Example #1
Source File: testview.py From yang-explorer with Apache License 2.0 | 8 votes |
def test_01_login(self): """Verify user creation""" user = authenticate(username='demo', password='demo123') self.assertTrue(user is not None) self.assertTrue(user.is_active == True) user = authenticate(username='demo', password='demo122') self.assertTrue(user is None) user = authenticate(username='demo', password='') self.assertTrue(user is None) user = authenticate(username='demo1', password='demo123') self.assertTrue(user is None) user = authenticate(username='', password='demo123') self.assertTrue(user is None)
Example #2
Source File: views.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def filter_queryset(self, queryset): project = self.kwargs.get('pk', None) if project: queryset = queryset.filter( user__user_roles__project__id = project, user__is_active=True).order_by('user__first_name') return queryset try: org = self.request.user.user_profile.organization queryset = queryset.filter(organization = org,user__is_active=True).order_by('user__first_name') except: queryset = [] return queryset # def web_authenticate(username=None, password=None): # # returns User , Email_correct, Password_correct # try: # user = User.objects.get(email__iexact=username) # if user.check_password(password): # return authenticate(username=user.username, password=password) # else: # return None, True, False # except User.DoesNotExist: # return None, False, True
Example #3
Source File: account.py From AnsibleUI with GNU General Public License v3.0 | 6 votes |
def myLogin(request): errors = [] data = '' next = request.GET.get('next') or request.GET.get('redirect_to') or '/' if request.method == 'POST': username = request.POST.get('username', '') password = request.POST.get('password', '') if not request.POST.get('username',''): errors.append('Enter a user') if not request.POST.get('password',''): errors.append('Enter a passwd') if not errors: user = auth.authenticate(username=username,password=password) if user is not None and user.is_active: auth.login(request,user) return redirect('%s' % next) else: data = '登陆失败,请核对信息' print(errors) return render(request, 'login2.html', {'errors': errors, 'data': data},)
Example #4
Source File: views.py From Django-Bookworm with MIT License | 6 votes |
def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('books') else: form = UserCreationForm() return render(request, 'signup.html', {'form': form})
Example #5
Source File: views.py From ideascube with GNU Affero General Public License v3.0 | 6 votes |
def welcome_staff(request): """Allow to create a staff user if None exists yet.""" if user_model.objects.filter(is_staff=True).exists(): return HttpResponseRedirect('/') if request.method == 'POST': form = CreateStaffForm(request.POST) if form.is_valid(): user = form.save() user = authenticate(serial=user.serial, password=request.POST['password']) login(request, user) msg = _(u'Welcome to {}, {}!').format( get_config('server', 'site-name'), user) messages.add_message(request, messages.SUCCESS, msg) return HttpResponseRedirect('/') else: form = CreateStaffForm() return render(request, 'ideascube/welcome_staff.html', {'form': form})
Example #6
Source File: forms.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: self.user_cache = authenticate(username=username, password=password) if self.user_cache is None: raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name}, ) else: self.confirm_login_allowed(self.user_cache) return self.cleaned_data
Example #7
Source File: forms.py From StormOnline with Apache License 2.0 | 6 votes |
def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') message = ERROR_MESSAGE if username and password: self.user_cache = authenticate( username=username, password=password) if self.user_cache is None: if u'@' in username: User = get_user_model() # Mistakenly entered e-mail address instead of username? Look it up. try: user = User.objects.get(email=username) except (User.DoesNotExist, User.MultipleObjectsReturned): # Nothing to do here, moving along. pass else: if user.check_password(password): message = _("Your e-mail address is not your username." " Try '%s' instead.") % user.username raise forms.ValidationError(message) elif not self.user_cache.is_active or not self.user_cache.is_staff: raise forms.ValidationError(message) return self.cleaned_data
Example #8
Source File: auth.py From arches with GNU Affero General Public License v3.0 | 6 votes |
def post(self, request): username = request.POST.get("username", None) password = request.POST.get("password", None) user = authenticate(username=username, password=password) if user: if hasattr(user, "userprofile") is not True: models.UserProfile.objects.create(user=user) userDict = JSONSerializer().serializeToPython(user) userDict["password"] = None userDict["is_reviewer"] = user_is_resource_reviewer(user) userDict["viewable_nodegroups"] = user.userprofile.viewable_nodegroups userDict["editable_nodegroups"] = user.userprofile.editable_nodegroups userDict["deletable_nodegroups"] = user.userprofile.deletable_nodegroups response = JSONResponse(userDict) else: response = Http401Response() return response
Example #9
Source File: auth.py From arches with GNU Affero General Public License v3.0 | 6 votes |
def post(self, request): messages = {"invalid_password": None, "password_validations": None, "success": None, "other": None, "mismatched": None} try: user = request.user old_password = request.POST.get("old_password") new_password = request.POST.get("new_password") new_password2 = request.POST.get("new_password2") if user.check_password(old_password) == False: messages["invalid_password"] = _("Invalid password") if new_password != new_password2: messages["mismatched"] = _("New password and confirmation must match") try: validation.validate_password(new_password, user) except ValidationError as val_err: messages["password_validations"] = val_err.messages if messages["invalid_password"] is None and messages["password_validations"] is None and messages["mismatched"] is None: user.set_password(new_password) user.save() authenticated_user = authenticate(username=user.username, password=new_password) login(request, authenticated_user) messages["success"] = _("Password successfully updated") except Exception as err: messages["other"] = err return JSONResponse(messages)
Example #10
Source File: test_middleware.py From django-oidc-rp with MIT License | 6 votes |
def test_log_out_the_user_if_the_refresh_token_is_expired(self, rf): request = rf.get('/oidc/cb/', {'state': 'state', 'code': 'authcode', }) SessionMiddleware().process_request(request) request.session.save() backend = OIDCAuthBackend() user = backend.authenticate(request, 'nonce') request.session['oidc_auth_id_token_exp_timestamp'] = \ (tz.now() - dt.timedelta(minutes=1)).timestamp() request.session['oidc_auth_refresh_token'] = 'this_is_a_refresh_token' auth.login(request, user) request.user = user httpretty.register_uri( httpretty.POST, oidc_rp_settings.PROVIDER_TOKEN_ENDPOINT, body=json.dumps({'error': 'yes'}), content_type='text/json', status=400) middleware = OIDCRefreshIDTokenMiddleware(lambda r: 'OK') middleware(request) assert not request.user.is_authenticated
Example #11
Source File: test_middleware.py From django-oidc-rp with MIT License | 6 votes |
def test_log_out_the_user_if_the_id_token_is_not_valid(self, rf): request = rf.get('/oidc/cb/', {'state': 'state', 'code': 'authcode', }) SessionMiddleware().process_request(request) request.session.save() backend = OIDCAuthBackend() user = backend.authenticate(request, 'nonce') request.session['oidc_auth_id_token_exp_timestamp'] = \ (tz.now() - dt.timedelta(minutes=1)).timestamp() request.session['oidc_auth_refresh_token'] = 'this_is_a_refresh_token' auth.login(request, user) request.user = user httpretty.register_uri( httpretty.POST, oidc_rp_settings.PROVIDER_TOKEN_ENDPOINT, body=json.dumps({ 'id_token': 'badidtoken', 'access_token': 'accesstoken', 'refresh_token': 'refreshtoken', }), content_type='text/json') middleware = OIDCRefreshIDTokenMiddleware(lambda r: 'OK') middleware(request) assert not request.user.is_authenticated
Example #12
Source File: users_api.py From seqr with GNU Affero General Public License v3.0 | 6 votes |
def set_password(request, username): user = User.objects.get(username=username) request_json = json.loads(request.body) if not request_json.get('password'): return create_json_response({}, status=400, reason='Password is required') user.set_password(request_json['password']) user.first_name = request_json.get('firstName') or '' user.last_name = request_json.get('lastName') or '' user.save() u = authenticate(username=username, password=request_json['password']) login(request, u) return create_json_response({'success': True})
Example #13
Source File: utils.py From django-useraudit with BSD 3-Clause "New" or "Revised" License | 6 votes |
def simulate_login(username, password, headers=None): rf = RequestFactory() request = rf.request(**headers) engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore() # TODO remove when we don't support Django 1.10 anymore # request passed in to authenticate only after Django 1.10 # Also the middleware saving the request to thread local can be dropped try: user = authenticate(request, username=username, password=password) except TypeError: middleware.thread_data.request = request user = authenticate(username=username, password=password) if user: login(request, user)
Example #14
Source File: test_briefcase_api.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def test_submission_with_instance_id_on_root_node(self): self._publish_xml_form() message = u"Successful submission." instanceId = u'5b2cc313-fc09-437e-8149-fcd32f695d41' self.assertRaises( Instance.DoesNotExist, Instance.objects.get, uuid=instanceId) submission_path = os.path.join( self.this_directory, 'fixtures', 'transportation', 'view', 'submission.xml') count = Instance.objects.count() with codecs.open(submission_path, encoding='utf-8') as f: post_data = {'xml_submission_file': f} self.factory = APIRequestFactory() request = self.factory.post(self._submission_url, post_data) request.user = authenticate(username='bob', password='bob') response = submission(request, username=self.user.username) self.assertContains(response, message, status_code=201) self.assertContains(response, instanceId, status_code=201) self.assertEqual(Instance.objects.count(), count + 1)
Example #15
Source File: test_briefcase_client.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def form_list_xml(url, request, **kwargs): response = requests.Response() factory = RequestFactory() req = factory.get(url.path) req.user = authenticate(username='bob', password='bob') req.user.profile.require_auth = False req.user.profile.save() id_string = 'transportation_2011_07_25' if url.path.endswith('formList'): res = formList(req, username='bob') elif url.path.endswith('form.xml'): res = download_xform(req, username='bob', id_string=id_string) elif url.path.find('xformsManifest') > -1: res = xformsManifest(req, username='bob', id_string=id_string) elif url.path.find('formid-media') > -1: data_id = url.path[url.path.rfind('/') + 1:] res = download_media_data( req, username='bob', id_string=id_string, data_id=data_id) response._content = get_streaming_content(res) else: res = formList(req, username='bob') response.status_code = 200 if not response._content: response._content = res.content return response
Example #16
Source File: views.py From oxidizr with GNU General Public License v2.0 | 6 votes |
def form_valid(self, form): user_email = form.cleaned_data['email'].lower().strip() password = form.cleaned_data['password'] user = authenticate(email=user_email, password=password) if user and user.is_active: login(self.request, user) return redirect(self.get_success_url()) else: try: user = User.objects.get(email__iexact=user_email) if not check_password(password, user.password): form._errors['password'] = ErrorList([u'That is not the correct Password.']) except User.DoesNotExist: form._errors['email'] = ErrorList([u'This email is not registered with us.']) context = self.get_context_data(form=form) return self.render_to_response(context)
Example #17
Source File: test_base.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def _make_submission_w_attachment(self, path, attachment_path): with open(path) as f: a = open(attachment_path) post_data = {'xml_submission_file': f, 'media_file': a} url = '/%s/submission' % self.user.username auth = DigestAuth('bob', 'bob') self.factory = APIRequestFactory() request = self.factory.post(url, post_data) request.user = authenticate(username='bob', password='bob') self.response = submission(request, username=self.user.username) if auth and self.response.status_code == 401: request.META.update(auth(request.META, self.response)) self.response = submission(request, username=self.user.username)
Example #18
Source File: tests.py From django-useraudit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_authentication_works_if_reactivated(self): self.setuser(last_login=timezone.now() - timedelta(days=6)) u = self.authenticate() # User is inactive now # Reactivate user self.user.is_active = True self.user.save() u = self.authenticate() self.assertIsNotNone(u, "Should be able to log in again if it has been activated") self.assertTrue(self.user2.is_active) ########################################################################### # password expiry test cases
Example #19
Source File: tests.py From django-useraudit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_authenticate_works(self): u = authenticate(username=self.username, password=self.password) self.assertIsNotNone(u) self.assertTrue(u.is_active)
Example #20
Source File: tests.py From django-useraudit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_user_deactivation_saved_on_password_expired(self): self.setuser(password_change_date=timezone.now() - timedelta(days=6)) u = self.authenticate() ud = UserDeactivation.objects.get(username=self.username) self.assertIsNone(u) self.assertIsNotNone(ud) self.assertFalse(self.user2.is_active) self.assertEquals(ud.reason, UserDeactivation.PASSWORD_EXPIRED)
Example #21
Source File: tests.py From django-useraudit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_no_warning_if_disabled(self): u = self.authenticate() self.assertIsNone(self.password_will_expire_warning_signal)
Example #22
Source File: tests.py From django-useraudit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_no_warning_if_password_already_expired(self): self.setuser(password_change_date=timezone.now() - timedelta(days=2)) u = self.authenticate() self.assertIsNone(self.password_will_expire_warning_signal)
Example #23
Source File: views.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def web_authenticate(username=None, password=None): try: if "@" in username: user = User.objects.get(email__iexact=username) else: user = User.objects.get(username__iexact=username) if user.check_password(password): return authenticate(username=user.username, password=password), False else: return None, True # Email is correct except User.DoesNotExist: return None, False # false Email incorrect
Example #24
Source File: tests.py From django-useraudit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_password_not_expired(self): u = self.authenticate() self.assertIsNotNone(u) self.assertTrue(u.is_active)
Example #25
Source File: tests.py From django-useraudit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_not_expired(self): u = self.authenticate() self.assertIsNotNone(u) self.assertTrue(u.is_active)
Example #26
Source File: tests.py From django-useraudit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_fresh_user(self): self.setuser(last_login=None) u = self.authenticate() self.assertIsNotNone(u) self.assertTrue(u.is_active)
Example #27
Source File: tests.py From django-useraudit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_expiry_disabled(self): self.setuser(last_login=timezone.now() - timedelta(days=10000)) u = self.authenticate() self.assertIsNotNone(u) self.assertTrue(u.is_active)
Example #28
Source File: tests.py From django-useraudit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def authenticate(self): return authenticate(username=self.username, password=self.password)
Example #29
Source File: tests.py From django-useraudit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_user_deactivation_saved_on_expiration(self): self.setuser(last_login=timezone.now() - timedelta(days=6)) u = self.authenticate() ud = UserDeactivation.objects.get(username=self.username) self.assertIsNone(u) self.assertIsNotNone(ud) self.assertEquals(ud.reason, UserDeactivation.ACCOUNT_EXPIRED)
Example #30
Source File: tests.py From django-useraudit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_expired(self): self.setuser(last_login=timezone.now() - timedelta(days=6)) u = self.authenticate() self.assertIsNone(u) self.assertFalse(self.user2.is_active)