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
python类check_password()的实例源码
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 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 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)
models.py 文件源码
项目:django-rest-framework-mongoengine-example
作者: BurkovBA
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
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)