本文整理匯總了Python中django.contrib.auth.hashers.make_password方法的典型用法代碼示例。如果您正苦於以下問題:Python hashers.make_password方法的具體用法?Python hashers.make_password怎麽用?Python hashers.make_password使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.contrib.auth.hashers
的用法示例。
在下文中一共展示了hashers.make_password方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: post
# 需要導入模塊: from django.contrib.auth import hashers [as 別名]
# 或者: from django.contrib.auth.hashers import make_password [as 別名]
def post(self, request):
register_form = RegisterForm(request.POST)
if register_form.is_valid():
user_name = request.POST.get("email", "")
if UserProfile.objects.filter(email=user_name):
return render(request, "login.html", {"register_form": register_form, "msg": "用戶已經存在,請登陸"})
pass_word = request.POST.get("password", "")
user_profile = UserProfile()
user_profile.username = user_name
user_profile.email = user_name
user_profile.is_active = False
user_profile.password = make_password(pass_word)
user_profile.save()
# 歡迎注冊消息
user_message = UserMessage()
user_message.user = user_profile.id
user_message.message = "歡迎注冊"
user_message.save()
send_register_email(user_name, "register")
# return render(request, "send_success.html")
return render(request, "login.html", {"msg": "激活鏈接已發至注冊郵箱,請激活後登陸"})
else:
return render(request, "register.html", {"register_form": register_form})
示例2: post
# 需要導入模塊: from django.contrib.auth import hashers [as 別名]
# 或者: from django.contrib.auth.hashers import make_password [as 別名]
def post(self, request, format=None):
data = request.data
if User.objects.filter(username__exact=data.get('username')):
return Response({"stateCode": 201, "msg": "用戶已存在"}, 201)
if User.objects.filter(email__exact=data.get('email')):
return Response({"stateCode": 202, "msg": "郵箱已被注冊"}, 201)
new_user = {
'actual_name': data.get('actual_name'),
'student_id': data.get('student_id'),
'username': data.get('username'),
'email': data.get('email'),
'password': make_password(data.get('password')),
'student_card_image_url': data.get('student_card_image_url')
}
# print(new_user)
serializer = RegisterSerializer(data=new_user)
if serializer.is_valid(raise_exception=True):
serializer.save()
return Response({"stateCode": 200, "msg": "注冊成功"}, 200)
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
# 登錄
示例3: encryt
# 需要導入模塊: from django.contrib.auth import hashers [as 別名]
# 或者: from django.contrib.auth.hashers import make_password [as 別名]
def encryt(self, cleartext, is_validate=True):
'''
密碼加密
:parm
cleartext:明文密碼
is_validate:是否需要驗證密碼長度
'''
if is_validate :
result = self._validate(cleartext)
if not result[0] :
self.logger.error('密碼加密失敗,原因:提供的密碼無法通過密碼複雜度檢查,' + str(result[1]))
return (False, '提供的密碼無法通過密碼複雜度檢查,' + str(result[1]))
try :
ciphertext = make_password(cleartext, self.fixed_field, self.type)
# ciphertext = self._remove_prefix(ciphertext)
self.logger.info('密碼加密成功')
return (True, ciphertext)
except Exception as e:
self.logger.error('密碼加密失敗,原因:' + str(e))
return (False, '加密失敗,' + str(e))
示例4: post
# 需要導入模塊: from django.contrib.auth import hashers [as 別名]
# 或者: from django.contrib.auth.hashers import make_password [as 別名]
def post(self, request):
register_form = RegisterForm(request.POST)
if register_form.is_valid():
user_name = request.POST.get("email", "")
if UserProfile.objects.filter(email=user_name):
# 驗證用戶名是否已經存在
return render(request, "user_register.html", {"register_form": register_form}, {"msg": "用戶名已經存在"})
pass_word = request.POST.get("password", "")
user_profile = UserProfile()
user_profile.username = user_name
user_profile.email = user_name
user_profile.is_active = False
user_profile.password = make_password(pass_word)
user_profile.save()
# send_register_email(user_name, "register")
return render(request, "user_login.html")
else:
return render(request, "user_register.html", {"register_form": register_form})
示例5: adduser
# 需要導入模塊: from django.contrib.auth import hashers [as 別名]
# 或者: from django.contrib.auth.hashers import make_password [as 別名]
def adduser(apps, schema_editor):
if os.getenv('CI'):
return
User = apps.get_model(*settings.AUTH_USER_MODEL.split('.'))
if settings.SECRET_KEY != 'notsecret':
return
user, created = User.objects.get_or_create(
username='test',
is_superuser=True,
is_active=True,
)
if created:
user.password = make_password('test')
user.save()
示例6: admin
# 需要導入模塊: from django.contrib.auth import hashers [as 別名]
# 或者: from django.contrib.auth.hashers import make_password [as 別名]
def admin(request):
add_user_form = AddUser(request.POST or None)
queryset = UserProfile.objects.all()
search = request.GET.get("search")
if search:
queryset = queryset.filter(username__icontains=search)
context = {
"title": "Admin",
"add_user_form": add_user_form,
"queryset": queryset,
}
if add_user_form.is_valid():
instance = add_user_form.save(commit=False)
passwd = add_user_form.cleaned_data.get("password")
instance.password = make_password(password=passwd,
salt='salt', )
instance.save()
reverse('profile')
return render(request, "users/sysadmin_dashboard.html", context)
示例7: generate_fake
# 需要導入模塊: from django.contrib.auth import hashers [as 別名]
# 或者: from django.contrib.auth.hashers import make_password [as 別名]
def generate_fake(cls, count=100):
from random import seed, choice
import forgery_py
from django.db import IntegrityError
from .group import UserGroup
seed()
for i in range(count):
user = cls(username=forgery_py.internet.user_name(True),
email=forgery_py.internet.email_address(),
name=forgery_py.name.full_name(),
password=make_password(forgery_py.lorem_ipsum.word()),
role=choice(list(dict(User.ROLE_CHOICES).keys())),
wechat=forgery_py.internet.user_name(True),
comment=forgery_py.lorem_ipsum.sentence(),
created_by=choice(cls.objects.all()).username)
try:
user.save()
except IntegrityError:
print('Duplicate Error, continue ...')
continue
user.groups.add(choice(UserGroup.objects.all()))
user.save()
示例8: post
# 需要導入模塊: from django.contrib.auth import hashers [as 別名]
# 或者: from django.contrib.auth.hashers import make_password [as 別名]
def post(self, request):
register_form = RegisterForm(request.POST)
if register_form.is_valid():
email = request.POST.get('email', '')
password = request.POST.get('password', '')
if UserProfile.objects.filter(email=email): # 判斷郵箱是否已經注冊過了
return render(request, 'register.html', {'register_form': register_form, 'msg': '用戶已經存在!'})
else:
user_profile = UserProfile()
user_profile.username = email
user_profile.email = email
user_profile.password = make_password(password)
user_profile.is_active = False
user_profile.save()
try:
send_link_email(email) # 發送激活郵件
except AttributeError:
return render(request, 'register.html', {'msg': '郵箱錯誤'})
return render(request, "email_send_success.html", {'email': email, 'msg': '請前往查收並盡快激活賬戶'})
else:
return render(request, 'register.html', {'register_form': register_form})
示例9: test_is_active
# 需要導入模塊: from django.contrib.auth import hashers [as 別名]
# 或者: from django.contrib.auth.hashers import make_password [as 別名]
def test_is_active(self):
client = self._login()
AUTH_PASSWORD_VALIDATORS = self.settings_obj.AUTH_PASSWORD_VALIDATORS
AUTH_PASSWORD_VALIDATORS[1]["OPTIONS"]["min_length"] = 5
with self.settings(AUTH_PASSWORD_VALIDATORS=AUTH_PASSWORD_VALIDATORS):
userdata = {"passwords": "ab",
"is_active": True,
"first_name": "user_f_name",
"last_name": "user_l_name",
"email": "test@domain.lan"
}
self.result(client.post, self.get_url('user'), 400, userdata)
passwd = 'eadgbe'
raw_passwd = make_password(passwd)
userdata = dict(username="testuser4", password=raw_passwd, password2=raw_passwd,
raw_password=True, is_active=False)
self.result(client.post, self.get_url('user'), 201, userdata)
client = Client()
data = {'username': userdata['username'],
'password': userdata['password']}
client.post('/login/', data=data)
response = client.get('/')
self.assertRedirects(response, self.login_url + '?next=/')
示例10: test_nonoprivileged_userwork_restriction
# 需要導入模塊: from django.contrib.auth import hashers [as 別名]
# 或者: from django.contrib.auth.hashers import make_password [as 別名]
def test_nonoprivileged_userwork_restriction(self):
self.change_identity()
selfurl = self.get_url('user', self.user.id)
self.get_result("patch", selfurl, 200)
url = self.get_url('user')
self.change_identity(is_super_user=True)
olduser = self.user
self.change_identity()
# can't create users
passwd = "some_pass"
userdata = dict(username="testuser4", password=make_password(passwd),
raw_password=True, is_active=False)
self.get_result("post", url, code=403, data=userdata)
# can't modify other users
self.get_result("patch", self.get_url('user', olduser.id),
code=403, data=json.dumps(userdata))
示例11: post
# 需要導入模塊: from django.contrib.auth import hashers [as 別名]
# 或者: from django.contrib.auth.hashers import make_password [as 別名]
def post(self, request):
form = RegisterForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username','')
email = form.cleaned_data.get('email', '')
password = form.cleaned_data.get('password', '')
users = User()
users.username = username
users.password =make_password(password)
users.email = email
users.is_active = False
users.save()
token = token_confirm.generate_validate_token(username)
# message = "\n".join([u'{0},歡迎加入我的博客'.format(username), u'請訪問該鏈接,完成用戶驗證,該鏈接1個小時內有效',
# '/'.join([settings.DOMAIN, 'activate', token])])
#send_mail(u'注冊用戶驗證信息', message, settings.EMAIL_HOST_USER, [email], fail_silently=False)
send_register_email.delay(email=email,username=username,token=token,send_type="register")
return JsonResponse({'valid':True,'status':200, 'message': u"請登錄到注冊郵箱中驗證用戶,有效期為1個小時"})
return JsonResponse({'status':400,'data':form.errors,'valid':False})
示例12: add_user
# 需要導入模塊: from django.contrib.auth import hashers [as 別名]
# 或者: from django.contrib.auth.hashers import make_password [as 別名]
def add_user(cls, username: str, alias: str, email: str, phone: str, dept_id: int, is_active: int, is_admin: int,
is_workflow_admin: int, creator: str, password: str='')->tuple:
"""
新增用戶, 因為非管理員或者工作流管理員無需登錄管理後台,密碼字段留空
add user, not support set password, you need reset password
:param username:
:param alias:
:param email:
:param phone:
:param dept_id:
:param is_active:
:param is_admin:
:param is_workflow_admin:
:param creator:
:param password:
:return:
"""
password_str = make_password(password, None, 'pbkdf2_sha256')
user_obj = LoonUser(username=username, alias=alias, email=email, phone=phone, dept_id=dept_id,
is_active=is_active, is_admin=is_admin, is_workflow_admin=is_workflow_admin,
creator=creator, password=password_str)
user_obj.save()
return True, dict(user_id=user_obj.id)
示例13: reset_password
# 需要導入模塊: from django.contrib.auth import hashers [as 別名]
# 或者: from django.contrib.auth.hashers import make_password [as 別名]
def reset_password(cls, username: str='', user_id: int=0)-> tuple:
"""
reset user's password
just admin or workflow admin need login loonflow's admin,so just admin and workflow admin can rest password
:param username:
:param user_id:
:return:
"""
flag, result = False, ''
if username:
flag, result = cls.get_user_by_username(username)
if user_id:
flag, result = cls.get_user_by_user_id(user_id)
if flag:
user_obj = result
if user_obj.is_admin or user_obj.is_workflow_admin:
password_str = make_password('123456', None, 'pbkdf2_sha256')
user_obj.password = password_str
user_obj.save()
return True, 'password has been reset to 123456'
else:
return False, 'just admin or workflow admin can be reset password'
else:
return False, result
示例14: test_91_django_generation
# 需要導入模塊: from django.contrib.auth import hashers [as 別名]
# 或者: from django.contrib.auth.hashers import make_password [as 別名]
def test_91_django_generation(self):
"""test against output of Django's make_password()"""
self._require_django_support()
# XXX: esp. when it's no longer supported by django,
# should verify it's *NOT* recognized
from passlib.utils import tick
from django.contrib.auth.hashers import make_password
name = self.handler.django_name # set for all the django_* handlers
end = tick() + self.max_fuzz_time/2
generator = self.FuzzHashGenerator(self, self.getRandom())
while tick() < end:
secret, other = generator.random_password_pair()
if not secret: # django rejects empty passwords.
continue
if self.django_has_encoding_glitch and isinstance(secret, bytes):
# e.g. unsalted_md5 tried to combine salt + password before encoding to bytes,
# leading to ascii error. this works around that issue.
secret = secret.decode("utf-8")
hash = make_password(secret, hasher=name)
self.assertTrue(self.do_identify(hash))
self.assertTrue(self.do_verify(secret, hash))
self.assertFalse(self.do_verify(other, hash))
示例15: make_password
# 需要導入模塊: from django.contrib.auth import hashers [as 別名]
# 或者: from django.contrib.auth.hashers import make_password [as 別名]
def make_password(self, password, salt=None, hasher="default"):
"""
Passlib replacement for make_password()
"""
if password is None:
return self._orig_make_password(None)
# NOTE: relying on hasher coming from context, and thus having
# context-specific config baked into it.
passlib_hasher = self.django_to_passlib(hasher)
if "salt" not in passlib_hasher.setting_kwds:
# ignore salt param even if preset
pass
elif hasher.startswith("unsalted_"):
# Django uses a separate 'unsalted_sha1' hasher for "sha1$$digest",
# but passlib just reuses it's "sha1" handler ("sha1$salt$digest"). To make
# this work, have to explicitly tell the sha1 handler to use an empty salt.
passlib_hasher = passlib_hasher.using(salt="")
elif salt:
# Django make_password() autogenerates a salt if salt is bool False (None / ''),
# so we only pass the keyword on if there's actually a fixed salt.
passlib_hasher = passlib_hasher.using(salt=salt)
return passlib_hasher.hash(password)