我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用django.contrib.auth.hashers.check_password()。
def fuzz_verifier_django(self): try: self._require_django_support() except SkipTest: return None from django.contrib.auth.hashers import check_password def verify_django(secret, hash): """django/check_password""" if self.handler.name == "django_bcrypt" and hash.startswith("bcrypt$$2y$"): hash = hash.replace("$$2y$", "$$2a$") if self.django_has_encoding_glitch and isinstance(secret, bytes): # e.g. unsalted_md5 on 1.5 and higher try to combine # salt + password before encoding to bytes, leading to ascii error. # this works around that issue. secret = secret.decode("utf-8") return check_password(secret, hash) return verify_django
def set_password(request, token): profile = request.user.profile if not check_password(token, profile.token): return HttpResponseBadRequest() if request.method == "POST": form = SetPasswordForm(request.POST) if form.is_valid(): password = form.cleaned_data["password"] request.user.set_password(password) request.user.save() profile.token = "" profile.save() # Setting a password logs the user out, so here we # log them back in. u = authenticate(username=request.user.email, password=password) auth_login(request, u) messages.success(request, "Your password has been set!") return redirect("hc-profile") return render(request, "accounts/set_password.html", {})
def change_password(request): user = User.objects.get(email=request.user.email) if request.method == 'POST': form = ChangePasswordForm(request.POST) if form.is_valid(): if check_password(request.POST['password'], user.password): #?? ???? ?? print('Okay') user.set_password(request.POST['password1']) # ??? ???? ??. user.save() return redirect('root') else: print('Fail to change password') # message? ?? ?? ??? else: form = ChangePasswordForm() return render(request, 'account/change.html', {'form': form})
def change_password(request): print request.data # If password or old-password not in request body if not (request.data.get('old_password', None) or request.data.get('new_password', None)): # Return error message with status code 400 return Response(status=status.HTTP_400_BAD_REQUEST) # try: # if old-password match if check_password(request.data['old_password'], request.user.password): # change user password request.user.set_password(request.data['new_password']) request.user.save() return Response(status=status.HTTP_200_OK) else: # else return with error message and status code 400 return Response({'detail': 'Doesn\'t match with your current password.'}, status=status.HTTP_400_BAD_REQUEST) # except: # # If exception return with status 400 # return Response(status=status.HTTP_400_BAD_REQUEST)
def post(self, request): form = self.form(request.POST) # print form.is_valid() # print form.errors if form.is_valid(): uname = form.cleaned_data['username'] passw = form.cleaned_data['password'] userq = models.Userprofile.objects.filter(user__username=uname) user = userq.first() if not user: return HttpResponse('No such user found') else: if not check_password(passw, user.user.password): return HttpResponse("Incorrect Password") else: if not user.user.is_active: return HttpResponse('User not activated') session_add_user(request, uname) return HttpResponse( 'Login Successful, should be moved to feed page') else: return HttpResponseRedirect('/login')
def clean(self): cleanedData = super(AdminModel, self).clean() cUsername = cleanedData.get("emailaddress") try: admin = Admin.objects.get(emailaddress__iexact=cUsername) if hashers.check_password(cleanedData.get("password"), admin.password): logging.debug("test") else: raise forms.ValidationError("Username or password incorrect") except User.DoesNotExist: raise forms.ValidationError("Username or password incorrect")
def clean(self): cleanedData = super(LoginModel, self).clean() cUsername = cleanedData.get("emailaddress") try: user = User.objects.get(emailaddress__iexact=cUsername) if hashers.check_password(cleanedData.get("password"), user.password): logging.debug(cleanedData.get("rememberMe")) else: raise forms.ValidationError("Username or password incorrect") except User.DoesNotExist: raise forms.ValidationError("Username or password incorrect")
def test_90_django_reference(self): """run known correct hashes through Django's check_password()""" self._require_django_support() # XXX: esp. when it's no longer supported by django, # should verify it's *NOT* recognized from django.contrib.auth.hashers import check_password assert self.known_correct_hashes for secret, hash in self.iter_known_hashes(): self.assertTrue(check_password(secret, hash), "secret=%r hash=%r failed to verify" % (secret, hash)) self.assertFalse(check_password('x' + secret, hash), "mangled secret=%r hash=%r incorrect verified" % (secret, hash))
def authenticate(self, username=None, token=None): try: profile = (Profile.objects .select_related("user").get(user__username=username)) except Profile.DoesNotExist: return None if not check_password(token, profile.token): return None return profile.user
def authenticate(self, username=None, password=None): try: user = User.objects.get(email=username) except User.DoesNotExist: return None if user.check_password(password): return user
def authenticate(self, username="", password="", **kwargs): try: user = get_user_model().objects.get(email__iexact=username) if check_password(password, user.password): return user else: return None except get_user_model().DoesNotExist: # No user was found, return None - triggers default login failed return None
def test_post_edit_password(self): self.client.force_login(get_user_model().objects.get(first_name='User')) data={'password':'1', 'old_password':"clubsuite",'new_password1':"clubsuite1",'new_password2':"clubsuite1"} response=self.client.post(reverse('suite:edit_profile'),data) self.assertEqual(response.status_code,200) #Need get() to get updated user newUser=get_user_model().objects.get(first_name='User') self.assertEqual(newUser,self.user) self.assertTrue(check_password("clubsuite1",newUser.password))
def login_view(request): # it will fetch the data from the database and redirect to feed.html page... if request.method == 'POST': #Process The Data response_data = {} form = LoginForm(request.POST) if form.is_valid(): #Validation Success username = form.cleaned_data['username'] password = form.cleaned_data['password'] #read Data From db user = UserModel.objects.filter(username=username).first() if user: #compare Password if check_password(password, user.password): #successfully Login token = SessionToken(user=user) token.create_token() token.save() ctypes.windll.user32.MessageBoxW(0, u"Login Successfull.", u"Done", 0) response = redirect('feed/') response.set_cookie(key='session_token', value=token.session_token) return response else: #Failed ctypes.windll.user32.MessageBoxW(0, u"Check Username Or Password.", u"Done", 0) response_data['message'] = 'Incorrect Password! Please try again!' ctypes.windll.user32.MessageBoxW(0, u"Check Username Or Password.", u"Done", 0) elif request.method == 'GET': # Display Login Page form = LoginForm() return render(request, 'login.html', {'form' : form})
def authenticate(request): if request.is_ajax(): strUsername = request.POST.get("username") strPassword = request.POST.get("password") else: strUsername = request.POST['username'] strPassword = request.POST['password'] result = {} # ????????? if not strUsername: result = {'status':2, 'msg':'?????????????!', 'data':''} return HttpResponse(json.dumps(result), content_type='application/json') if not strPassword: result = {'status': 2, 'msg': '????????????!', 'data': ''} return HttpResponse(json.dumps(result), content_type='application/json') correct_users = Users.objects.filter(username=strUsername) # ???django????check_password????????????django???PBKDF2????? if len(correct_users) == 1: if check_password(strPassword, correct_users[0].password): if correct_users[0].is_active: correct_users[0].last_login = getNow() correct_users[0].save() request.session['login_username'] = strUsername result = {'status':0, 'msg':'ok', 'data':''} else: result = {'status': 1, 'msg': '?????????????', 'data': ''} else: result = {'status':1, 'msg':'???????????', 'data':''} else: result = {'status': 2, 'msg': '??????????????', 'data': ''} return HttpResponse(json.dumps(result), content_type='application/json')
def authenticate(self, username=None, password=None): user_cls = self.get_user_class() try: user = user_cls.objects().get({'username':username}) except QueryError: user = None if user and check_password(password, user.password): user._meta = Meta(user) return user if not user: return None
def check_password(self, raw_password): """ Returns a boolean of whether the raw_password was correct. Handles encryption formats behind the scenes. """ return check_password(raw_password, self.password)
def check_key(request): """Check masterkey""" if not settings.ENABLE_MASTERKEY: return redirect('vaults:open_vault') if not check_seal(request): return redirect('vaults:new_key') msg = '' if request.method == "POST": checkform = CheckKeyForm(request.POST) if checkform.is_valid(): inputkey = checkform.save(commit=False) key = Key.objects.filter(user=request.user).latest('created_at') if check_password(inputkey.masterkey, key.masterkey): key.expiry = timezone.now() + timezone.timedelta( minutes=settings.MASTERKEY_SESSION_TIME) key.save() return redirect(key.get_absolute_url()) else: msg = _('Wrong master key.') elif request.method == "GET": checkform = CheckKeyForm() return render( request, "vaults/check_key.html", { 'form': checkform, 'msg': msg, } )
def edit_key(request): """Edit key""" if not settings.ENABLE_MASTERKEY: return redirect('vaults:open_vault') if not check_seal(request): return redirect('vaults:new_key') msg = '' key = Key.objects.filter(user=request.user).latest('created_at') if request.method == "POST": editform = KeyEditForm(request.POST) if editform.is_valid(): newkey = editform.save(commit=False) current_key = editform.cleaned_data['current_key'] if check_password(current_key, key.masterkey): key.masterkey = make_password(newkey.masterkey) key.created_at = timezone.now() key.save() return redirect(key.get_absolute_url()) else: msg = _('Wrong master key.') elif request.method == "GET": editform = KeyEditForm() return render( request, "vaults/edit_key.html", { 'form': editform, 'msg': msg, } )
def clean_old_password(self): old_pw = self.cleaned_data.get('old_password') if not check_password(old_pw, self.user.password): raise forms.ValidationError( self.error_messages['pw_current_wrong'], code='pw_current_wrong', ) return old_pw
def _iter_patch_candidates(cls): """helper to scan for monkeypatches. returns tuple containing: * object (module or class) * attribute of object * value of attribute * whether it should or should not be patched """ # XXX: this and assert_unpatched() could probably be refactored to use # the PatchManager class to do the heavy lifting. from django.contrib.auth import models user_attrs = ["check_password", "set_password"] model_attrs = ["check_password"] objs = [(models, model_attrs), (models.User, user_attrs)] if has_django14: from django.contrib.auth import hashers model_attrs.append("make_password") objs.append((hashers, ["check_password", "make_password", "get_hasher", "identify_hasher"])) if has_django0: user_attrs.extend(["has_usable_password", "set_unusable_password"]) for obj, patched in objs: for attr in dir(obj): if attr.startswith("_"): continue value = obj.__dict__.get(attr, UNSET) # can't use getattr() due to GAE if value is UNSET and attr not in patched: continue value = get_method_function(value) source = getattr(value, "__module__", None) if source: yield obj, attr, source, (attr in patched) #=================================================================== # verify current patch state #===================================================================
def test_01_overwrite_detection(self): "test detection of foreign monkeypatching" # NOTE: this sets things up, and spot checks two methods, # this should be enough to verify patch manager is working. # TODO: test unpatch behavior honors flag. # configure plugin to use sample context config = "[passlib]\nschemes=des_crypt\n" self.load_extension(PASSLIB_CONFIG=config) # setup helpers import django.contrib.auth.models as models from passlib.ext.django.models import _manager def dummy(): pass # mess with User.set_password, make sure it's detected orig = models.User.set_password models.User.set_password = dummy with self.assertWarningList("another library has patched.*User\.set_password"): _manager.check_all() models.User.set_password = orig # mess with models.check_password, make sure it's detected orig = models.check_password models.check_password = dummy with self.assertWarningList("another library has patched.*models:check_password"): _manager.check_all() models.check_password = orig
def setUp(self): # NOTE: omitted orig setup, want to install our extension, # and load hashers through it instead. self.load_extension(PASSLIB_CONTEXT=stock_config, check=False) from passlib.ext.django.models import password_context # update test module to use our versions of some hasher funcs from django.contrib.auth import hashers for attr in ["make_password", "check_password", "identify_hasher", "get_hasher"]: patchAttr(self, _thmod, attr, getattr(hashers, attr)) # django 1.5 tests expect empty django_des_crypt salt field if DJANGO_VERSION > (1,4): from passlib.hash import django_des_crypt patchAttr(self, django_des_crypt, "use_duplicate_salt", False) # hack: need password_context to keep up to date with hasher.iterations if DJANGO_VERSION >= (1,6): def update_hook(self): rounds = _thmod.get_hasher("pbkdf2_sha256").iterations self.update( django_pbkdf2_sha256__min_rounds=rounds, django_pbkdf2_sha256__default_rounds=rounds, django_pbkdf2_sha256__max_rounds=rounds, ) patchAttr(self, password_context, "__class__", ContextWithHook) patchAttr(self, password_context, "update_hook", update_hook) # omitting this test, since it depends on updated to django hasher settings
def login(request, email, password): user = await request.app.models.user.get_user_by_email(email) if user and check_password(password, user.password): await gen_api_key(user.id, request=request, auth='email') request.user = user return {'api_key': request.session} return exceptions.HTTPBadRequest(errors=dict( __all__=['???????????? ??? ?????? ?????? ?? ?????'] ))
def form_valid(self, form): user = self.request.user if not check_password(self.request.POST['oldpassword'], user.password): return JsonResponse({ 'error': True, 'response': {'oldpassword': 'Invalid old password'} }) if self.request.POST['newpassword'] != self.request.POST['retypepassword']: return JsonResponse({ 'error': True, 'response': {'newpassword': 'New password and Confirm Passwords did not match'} }) user.set_password(self.request.POST['newpassword']) user.save() return JsonResponse({'error': False, 'message': 'Password changed successfully'})
def authenticate(self, username=None, password=None): username = username.rstrip().lstrip().lower() login_valid = (getattr(settings, 'SETTINGS_AUTH_USER', "") == username) # TODO: Handle error if SETTINGS_AUTH_PASSWORD not set if getattr(settings, 'SETTINGS_AUTH_PASSWORD', None): pwd_valid = check_password(password, settings.SETTINGS_AUTH_PASSWORD) else: pwd_valid = False if login_valid and pwd_valid: try: user = User.objects.get(username=username) except User.DoesNotExist: # Create a new user. Note that we can set password # to anything, because it won't be checked; the password # from the external backend is checked (coming from settings). user = User( username=username, password='flubbernubber', first_name=getattr( settings, 'SETTINGS_AUTH_FIRST_NAME', ""), last_name=getattr( settings, 'SETTINGS_AUTH_LAST_NAME', ""), email=getattr( settings, 'SETTINGS_AUTH_EMAIL', ""), is_active=False) user.save() up, created = UserProfile.objects.get_or_create( user=user, user_type='BEN') group = Group.objects.get(name='BlueButton') user.groups.add(group) # Send verification email create_activation_key(user) return user return None
def test_user_change_own_password(self): self._asJaneDoe() new_password = {'new_password': 'super duper password'} response = self._client.patch("/users/%d/change_password/" % self._janeDoe.id, new_password, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) user1 = User.objects.get(username="Jane Doe") self.assertIs(check_password('super duper password', user1.password), True)
def test_user_change_other_password(self): self._asJoeBloggs() new_password = {'new_password': 'super duper password'} response = self._client.patch("/users/%d/change_password/" % self._janeDoe.id, new_password, format='json') self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) user1 = User.objects.get(username="Joe Bloggs") self.assertIs(check_password('super duper password', user1.password), False)
def test_admin_change_any_password(self): self._asAdmin() new_password = {'new_password': 'super duper password'} response = self._client.patch("/users/%d/change_password/" % self._joeBloggs.id, new_password, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) user1 = User.objects.get(username="Joe Bloggs") self.assertIs(check_password('super duper password', user1.password), True)
def check_password(self, raw_password): """ Checks the user's password against a provided password - always use this rather than directly comparing to :attr:`~mongoengine.django.auth.User.password` as the password is hashed before storage. """ return check_password(raw_password, self.password)
def test_01_overwrite_detection(self): """test detection of foreign monkeypatching""" # NOTE: this sets things up, and spot checks two methods, # this should be enough to verify patch manager is working. # TODO: test unpatch behavior honors flag. # configure plugin to use sample context config = "[passlib]\nschemes=des_crypt\n" self.load_extension(PASSLIB_CONFIG=config) # setup helpers import django.contrib.auth.models as models from passlib.ext.django.models import _manager def dummy(): pass # mess with User.set_password, make sure it's detected orig = models.User.set_password models.User.set_password = dummy with self.assertWarningList("another library has patched.*User\.set_password"): _manager.check_all() models.User.set_password = orig # mess with models.check_password, make sure it's detected orig = models.check_password models.check_password = dummy with self.assertWarningList("another library has patched.*models:check_password"): _manager.check_all() models.check_password = orig
def setUp(self): # NOTE: omitted orig setup, want to install our extension, # and load hashers through it instead. self.load_extension(PASSLIB_CONTEXT=stock_config, check=False) from passlib.ext.django.models import password_context # update test module to use our versions of some hasher funcs from django.contrib.auth import hashers for attr in ["make_password", "check_password", "identify_hasher", "get_hasher"]: patchAttr(self, test_hashers_mod, attr, getattr(hashers, attr)) # django 1.4 tests expect empty django_des_crypt salt field if DJANGO_VERSION >= (1,4): from passlib.hash import django_des_crypt patchAttr(self, django_des_crypt, "use_duplicate_salt", False) # hack: need password_context to keep up to date with hasher.iterations if DJANGO_VERSION >= (1,6): def update_hook(self): rounds = test_hashers_mod.get_hasher("pbkdf2_sha256").iterations self.update( django_pbkdf2_sha256__min_rounds=rounds, django_pbkdf2_sha256__default_rounds=rounds, django_pbkdf2_sha256__max_rounds=rounds, ) patchAttr(self, password_context, "__class__", ContextWithHook) patchAttr(self, password_context, "update_hook", update_hook) # omitting this test, since it depends on updated to django hasher settings
def authenticate(email, sign_up_type, password): try: user = UserProfile.objects.get(email=email, sign_up_type=sign_up_type) except ObjectDoesNotExist: return -1 chk_password = check_password(password=password, encoded=user.password) if chk_password is False: return -2 return user # email authentication
def put(self, request): # get data from request. try: email = request.data['email'] except MultiValueDictKeyError: return ErrorResponse.error_response(-101, "No email") try: password = request.data['password'] except MultiValueDictKeyError: return ErrorResponse.error_response(-102, "No current password") try: new_password = request.data['new_password'] except MultiValueDictKeyError: return ErrorResponse.error_response(-103, "No new_password") try: user = UserProfile.objects.get(email=email, sign_up_type='email') except ObjectDoesNotExist: return ErrorResponse.error_response(-200, "Invalid user") chk_password = check_password(password=password, encoded=user.password) if chk_password is False: return ErrorResponse.error_response(-300, "Not correct current password") user.password = make_password(password=new_password, salt=None, hasher='default') user.save() return_data = {"message": "success", "ErrorCode": 0} return Response(return_data) # Sign up and Sign in class for social user
def authenticate(self, username=None, password=None): try: user = User.objects.get(username=username) except User.DoesNotExist: return None if check_password(password, user.password): return user # try running password through same scrypt params as front end. encoded_password = scrypt.hash(str(password), str(username), 16384, 8, 1).encode('hex') if check_password(encoded_password, user.password): return user return None
def get_master_key(self, session_key): # Validate the provided session key if not check_password(session_key, self.hash): raise InvalidKey("Invalid session key") # Decrypt master key using provided session key master_key = strxor.strxor(session_key, bytes(self.cipher)) return master_key
def get_session_key(self, master_key): # Recover session key using the master key session_key = strxor.strxor(master_key, bytes(self.cipher)) # Validate the recovered session key if not check_password(session_key, self.hash): raise InvalidKey("Invalid master key") return session_key
def validate(self, plaintext): """ Validate that a given plaintext matches the stored hash. """ if not self.hash: raise Exception("Hash has not been generated for this secret.") return check_password(plaintext, self.hash, preferred=SecretValidationHasher())
def authenticate(self, username: str, password: str) -> Optional[MNUser]: # the argument names must be 'username' and 'password' because the authenticator interface is tightly coupled # to the parameter names between login forms and authenticators if "@" not in username or username.count("@") > 1: try: user = MNUser.objects.get(identifier=username) # type: MNUser except MNUser.DoesNotExist: logging.debug("No user found %s for identifier login", username) return None # if the user is a staff user, they may also log in using their identifier if user.is_staff: logging.debug("User %s is staff, allowing identifier login", username) if hashers.check_password(password, user.password): logging.debug("User %s logged in with correct password", username) return user else: logging.debug("Incorrect password for user %s (%s)", username, user.password) logging.debug("Must provide an email address. %s is not an email address", username) return None logging.debug("logging user %s in as email alias", username) mailprefix, domain = username.split("@") if Domain.objects.filter(name=domain).count() == 0: logging.debug("Domain %s does not exist", domain) return None try: user = EmailAlias.objects.get(mailprefix__istartswith=mailprefix, domain__name=domain).user except EmailAlias.DoesNotExist: return None if hashers.check_password(password, user.password): return user else: return None