我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用django.contrib.auth.hashers.make_password()。
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)
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))
def _init_test_school_master(self): if hasattr(self, '_school_master'): return self.school_master = "school_master_1LlwZyCR3" self.school_master_pswd = "123" user_data = { 'password': make_password(self.school_master_pswd), 'is_staff': True, 'is_superuser': True, } user, _ = User.objects.get_or_create(username=self.school_master, defaults=user_data) user.groups.add(Group.objects.get(name="?????")) school = models.School.objects.filter(opened=True).first() _school_master, _ = models.SchoolMaster.objects.get_or_create(user=user, defaults={ "school": school, "name": "test_schoolmaster" }) self._school_master = _school_master
def _init_test_lecturer(self): if hasattr(self, '_lecturer'): return self.lecturer = "lecturer_oUP1zwTO9" self.lecturer_pswd = "123" user_data = { 'password': make_password(self.lecturer_pswd), 'is_staff': False, 'is_superuser': False, } user, _ = User.objects.get_or_create(username=self.lecturer, defaults=user_data) _lecturer, _ = models.Lecturer.objects.get_or_create( user=user, defaults={ "subject": models.Subject.get_english(), "name": "kaoru" }) self._lecturer = _lecturer
def new_student() -> User: # ???? username = random_string()[:30] salt = random_string()[:5] password = "malalaoshi" user = User(username=username) user.email = "" user.password = make_password(password, salt) user.save() student_group = Group.objects.get(name="??") user.groups.add(student_group) # ?????? profile = Profile(user=user) profile.save() student = Student(user=user) student.save() # ???? user.save() profile.save() student.save() ret_user = authenticate(username=username, password=password) return ret_user
def new_parent()->User: # ???? username = random_string()[:30] salt = random_string()[:5] password = "malalaoshi" user = User(username=username) user.email = "" user.password = make_password(password, salt) user.save() parent_group = Group.objects.get(name="??") user.groups.add(parent_group) # ?????? profile = Profile(user=user) profile.save() parent = Parent(user=user) parent.save() # ???? user.save() profile.save() parent.save() ret_user = authenticate(username=username, password=password) return ret_user
def post(self,request): modify_form = ModifyPwdForm(request.POST) if modify_form.is_valid(): password1 = request.POST.get('password1','') password2 = request.POST.get('password2','') email = request.POST.get('email','') if password1 != password2: return render(request,'password_reset.html',{'email':email,'msg':u'?????'}) user = UserProfile.objects.get(email=email) user.password = make_password(password2) user.save() return render(request,'login.html') else: email = request.POST.get('email','') return render(request,'password_reset.html',{'email': email, 'modify_form': modify_form})
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,'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.password = make_password(pass_word) user_profile.is_active = False user_profile.save() send_register_email(user_name,'register') return render(request,'login.html',{}) else: return render(request,'register.html',{'register_form':register_form})
def edit(request, user_id): user = Users.objects.get(id=int(user_id)) if not user: return HttpResponseBadRequest(u"????") if request.POST: user.department = request.POST.get("department") user.realname = request.POST.get("realname") user.phone = request.POST.get("phone") user.role = request.POST.get("role") user.is_active = request.POST.get("is_active") password = request.POST.get("password") if password: loginUser = request.session.get('login_username') loginUserOb = Users.objects.get(username=loginUser) # ??????????????, ???????????????? if loginUser == user.username or loginUserOb.role in (1, 2): user.password = make_password(password, salt=None, hasher='default') else: context = {'errMsg': '???????????????????????????'} return render(request, 'error.html', context) user.save() return HttpResponseRedirect("/account/index") context = {'user': user, 'ROLE_DICT': ROLE_DICT, 'DEPART_DICT': DEPART_DICT} return render(request, 'account/edit.html', context)
def test_91_django_generation(self): "test against output of Django's make_password()" from passlib.tests.test_ext_django import DJANGO_VERSION # make_password() not added until 1.4 min_django_version = max(self.min_django_version, (1,4)) if DJANGO_VERSION < min_django_version: raise self.skipTest("Django >= %s not installed" % vstr(min_django_version)) 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 while tick() < end: secret, other = self.get_fuzz_password_pair() if not secret: # django 1.4 rejects empty passwords. continue if DJANGO_VERSION >= (1,5) and 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") 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))
def setUp(self): self.user_1 = G( User, is_staff=True, is_active=True, ) self.user_1.password = make_password('test_password123') self.user_1.save() self.user_2 = G( User, is_active=True, ) self.user_2.password = make_password('test_password123') self.user_2.save() self.user_3 = G( User, is_active=False, is_staff=True, ) self.user_3.password = make_password('test_password123') self.user_3.save()
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, "register.html", {"msg": "??????", 'register_form': register_form}) 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") # ???????? user_message = UserMessage() user_message.user = user_profile.id user_message.message = "?????????" user_message.save() return render(request, "login.html") else: return render(request, "register.html", {'register_form': register_form} )
def test_91_django_generation(self): """test against output of Django's make_password()""" from passlib.tests.test_ext_django import DJANGO_VERSION # make_password() not added until 1.4 min_django_version = max(self.min_django_version, (1,4)) if DJANGO_VERSION < min_django_version: raise self.skipTest("Django >= %s not installed" % vstr(min_django_version)) 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 while tick() < end: secret, other = self.get_fuzz_password_pair() if not secret: # django 1.4 rejects empty passwords. continue if DJANGO_VERSION >= (1,5) and 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") 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))
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)
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, '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, 'login.html') else: return render(request, 'register.html', {"register_form": register_form}) # ????
def post(self, request): modify_form = ModifyPwdForm(request.POST) email = request.POST.get('email', '') if modify_form.is_valid(): pwd1 = request.POST.get('password1', '') pwd2 = request.POST.get('password2', '') if pwd1 != pwd2: return render(request, 'password_reset.html', {'email': email, 'msg': '??????'}) user = UserProfile.objects.get(email=email) user.password = make_password(pwd2) user.save() return render(request, 'login.html') else: return render(request, 'password_reset.html', {'email': email, 'modify_form': modify_form}) # ????
def post(self, request): modify_form = ModifyPwdForm(request.POST) res = dict() if modify_form.is_valid(): pwd1 = request.POST.get('password1', '') pwd2 = request.POST.get('password2', '') if pwd1 != pwd2: res['status'] = 'fail' res['msg'] = '???????' return HttpResponse(json.dumps(res), content_type='application/json') user = request.user user.password = make_password(pwd2) user.save() res['status'] = 'success' res['msg'] = '??????' else: res = modify_form.errors return HttpResponse(json.dumps(res), content_type='application/json') # ?????????????
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, "register.html", {"register_form": register_form, "message": "??????,???\r\n" "????????"}) 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 = pass_word user_profile.password = make_password(pass_word) user_profile.save() send_register_email(user_name, "register") return render(request, "login.html") else: return render(request, "register.html", {"register_form": register_form})
def post(self, request): modify_form = ModifyPwdForm(request.POST) if modify_form.is_valid(): pwd1 = request.POST.get("password1", "") pwd2 = request.POST.get("password2", "") email = request.POST.get("email", "") if pwd1 != pwd2: return render(request, "password_reset.html", {"email": email, "message": "???????????,?????!"}) user = UserProfile.objects.get(email=email) user.password = make_password(pwd2) user.save() return render(request, "login.html") else: email = request.POST.get("email", "") return render(request, "password_reset.html", {"email": email, "modify_form": modify_form})
def create(self, request, *args, **kwargs): data = dict() data['phone'] = request.data['phone'] if User.objects.filter(phone=data['phone']).exists(): return Response({'error': "account exist"}, status=status.HTTP_400_BAD_REQUEST) data['name'] = request.data.get('name') data['Email'] = request.data.get('Email') password1 = request.data.get('password1') password2 = request.data.get('password2') if password1 != password2: return Response({'error': "passwords inconsistent"}, status=status.HTTP_400_BAD_REQUEST) if password1 is not None and password2 is not None: serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() user = User.objects.get(id=serializer.data['id']) user.password = make_password(password1, "a", 'pbkdf2_sha256')[22:54] user.save() return Response({'error': 0, 'data': serializer.data}, status=status.HTTP_201_CREATED) return Response({'error': "data invalid"}, status=status.HTTP_400_BAD_REQUEST)
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, "register.html", {"msg": u"?????", "register_form": register_form}) 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, "login.html") else: return render(request, "register.html",{"register_form": register_form})
def save(self, master_key=None, *args, **kwargs): if master_key is None: raise Exception("The master key must be provided to save a session key.") # Generate a random 256-bit session key if one is not already defined if self.key is None: self.key = generate_random_key() # Generate SHA256 hash using Django's built-in password hashing mechanism self.hash = make_password(self.key) # Encrypt master key using the session key self.cipher = strxor.strxor(self.key, master_key) super(SessionKey, self).save(*args, **kwargs)
def encrypt(self, secret_key): """ Generate a random initialization vector (IV) for AES. Pad the plaintext to the AES block size (16 bytes) and encrypt. Prepend the IV for use in decryption. Finally, record the SHA256 hash of the plaintext for validation upon decryption. """ if self.plaintext is None: raise Exception("Must unlock or set plaintext before locking.") # Pad and encrypt plaintext iv = os.urandom(16) aes = AES.new(secret_key, AES.MODE_CFB, iv) self.ciphertext = iv + aes.encrypt(self._pad(self.plaintext)) # Generate SHA256 using Django's built-in password hashing mechanism self.hash = make_password(self.plaintext, hasher=SecretValidationHasher()) self.plaintext = None
def post(self,request): modify_form=ModifyPwdForm(request.POST) if modify_form.is_valid(): pwd1=request.POST.get("password1","") pwd2= request.POST.get("password2", "") email=request.POST.get("email","") if pwd1 !=pwd2 : return render(request, "password_reset.html", {"email": "email","msg":"?????"}) user = UserProfile.objects.get(email=email) user.password=make_password(pwd2) user.save() return render(request,"login.html") else: email = request.POST.get("email", "") return render(request, "password_reset.html", {"email": "email","modify_form":modify_form}) # ????
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,"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() # ???????? user_message=UserMessage() user_message.user=user_profile.id user_message.message="?????????" user_message.save() send_register_email(user_name,"register") return render(request, "login.html") else: return render(request, "register.html",{'register_form':register_form}) # ????
def new_users(request): if request.method == 'POST': user_name = request.REQUEST.get('user_name') user_passwd = request.REQUEST.get('user_passwd') if user_name is not None and user_passwd is not None: pwd = make_password(user_passwd, None, 'pbkdf2_sha256') if request.META.has_key('HTTP_X_FORWARDED_FOR'): ip = request.META['HTTP_X_FORWARDED_FOR'] else: ip = request.META['REMOTE_ADDR'] insert = {"user_name": user_name, 'user_passwd': pwd, 'client_ip': ip, 'auth_group': 1} u = usermodel() uid = u.insert(insert) if uid: return HttpResponseRedirect("/users/") return render(request, 'users/new_users.html', {})
def post(self, request): modify_form = ModifyPwdForm(request.POST) email = request.POST.get('email', '') if modify_form.is_valid(): pwd1 = request.POST.get('password1', '') pwd2 = request.POST.get('password2', '') if pwd1 != pwd2: return render(request, 'password_reset.html', {'email': email, 'msg': '??????'}) user = UserProfile.objects.get(email=email) user.password = make_password(pwd2) user.save() return render(request, 'login.html') return render(request, 'password_reset.html', {'email': email, 'modify_form': modify_form}) # userprofile
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, "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.password = make_password(pass_word) user_profile.is_active = False user_profile.save() send_register_email(user_name, "register") return render(request,"login.html") else: return render(request,"register.html", {'register_form':register_form})
def post(self, request): modify_form = ModifyPwdForm(request.POST) if modify_form.is_valid(): pwd1 = request.POST.get("password1") pwd2 = request.POST.get("password2") email = request.POST.get("email") if pwd1 != pwd2: return render(request, "password_reset.html", {"modify_form":modify_form, "email":email, "msg": "?????"}) user = UserProfile.objects.get(email=email) user.password = make_password(pwd2) user.save() return render(request, "login.html") else: email = request.POST.get("email") return render(request, "password_reset.html", {"email":email, "modify_form":modify_form}) # Create your views here.
def createadmin(request): form = CreateAdmin(request.POST or None) if form.is_valid(): instance = form.save() instance.password = hashers.make_password(instance.password) instance.save() return render(request, 'auscities/admincreate.html/', {'form':form})
def register(request): form = RegisterForm(request.POST or None) if form.is_valid(): user = form.save() request.session['logged'] = 1 request.session['user'] = user.emailaddress request.session['type'] = user.usertype request.session['remember'] = False user.password = hashers.make_password(user.password) user.save() return HttpResponseRedirect('/') return render(request, 'auscities/register.html', {'form':form})
def user(request): form = EditProfile(request.POST or None) if form.is_valid(): user = User.objects.get(emailaddress__iexact=request.session['user']) user.firstname = form.cleaned_data['firstname'] user.lastname = form.cleaned_data['lastname'] user.password = hashers.make_password(form.cleaned_data['password']) user.save() return HttpResponseRedirect('/') return render(request, 'auscities/editprofile.html', {'form':form})
def __init__(self, context=None, get_user_category=None, **kwds): # init log self.log = logging.getLogger(__name__ + ".DjangoContextAdapter") # init parent, filling in default context object if context is None: context = CryptContext() super(DjangoContextAdapter, self).__init__(context=context, **kwds) # setup user category if get_user_category: assert callable(get_user_category) self.get_user_category = get_user_category # install lru cache wrappers from django.utils.lru_cache import lru_cache self.get_hashers = lru_cache()(self.get_hashers) # get copy of original make_password from django.contrib.auth.hashers import make_password if make_password.__module__.startswith("passlib."): make_password = _PatchManager.peek_unpatched_func(make_password) self._orig_make_password = make_password # get other django helpers from django.contrib.auth.hashers import is_password_usable self.is_password_usable = is_password_usable # init manager mlog = logging.getLogger(__name__ + ".DjangoContextAdapter._manager") self._manager = _PatchManager(log=mlog)
def add_test_user_into_group(apps, schema_editor): _add_test_user_into_group(apps, settings.SAMPLE_PARENT_USER_FORMULA, settings.SAMPLE_DATA_LENGTH, '??') _add_test_user_into_group(apps, settings.SAMPLE_TEACHER_USER_FORMULA, settings.SAMPLE_DATA_LENGTH, '??') _add_test_user_into_group( apps, 't_manager{id}', 10, '?????', {'password': make_password("123", settings.PASSWORD_SALT)})
def new_teacher(phone: str)->User: # ???????????????? profile = Profile.objects.filter(phone=phone).first() if profile is not None and profile.user is not None: username = random_string()[:30] salt = random_string()[:5] password = "malalaoshi" user = profile.user user.username = username user.email = "" user.password = make_password(password, salt) user.save() else: # ???? username = random_string()[:30] salt = random_string()[:5] password = "malalaoshi" user = User(username=username) user.email = "" user.password = make_password(password, salt) user.save() # ?????? profile = Profile(user=user, phone=phone) profile.save() teacher = Teacher(user=user) teacher.save() teacher_group = Group.objects.get(name="??") user.groups.add(teacher_group) ret_user = authenticate(username=username, password=password) return ret_user
def post(self, request): captcha_refresh = request.POST.get('refresh', '') hashkey = CaptchaStore.generate_key() image_url = captcha_image_url(hashkey) if captcha_refresh == 'refresh': info = {'hashkey':hashkey, 'image_url':image_url} return JsonResponse(info, safe=False) registe_form = RegisteForm(request.POST) if registe_form.is_valid(): username = request.POST.get('username', '') if UserInfo.objects.filter(username=username): return render(request, 'registe.html', {'msg':'?????', 'registe_form':registe_form}) password = request.POST.get('password', '') kind = request.POST.get('kind', '') email = request.POST.get('email', '') if UserInfo.objects.filter(email=email): return render(request, 'registe.html', {'msg':'??????', 'registe_form':registe_form}) form = UserInfo() form.username = username form.password = make_password(password) form.kind = kind form.email = email form.is_active = False form.save() emailVerify(email, 'registe') return render(request, 'verify.html') else: return render(request, 'registe.html', { 'registe_form': registe_form, 'formFail': '??????' })
def post(self, request): modify_form = ModifyPwdForm(request.POST) if modify_form.is_valid(): pwd1 = request.POST.get('password1', '') pwd2 = request.POST.get('password2', '') email = request.POST.get('email', '') if pwd1 != pwd2: return render(request, 'pwdreset.html', {'email':email, 'msg':'?????'}) user = UserInfo.objects.get(email=email) user.password = make_password(pwd1) user.save() return render(request, 'login.html') else: return render(request, 'pwdreset.html', {'modify_form':modify_form})
def post(self, request): modify_form = ModifyPwdForm(request.POST) if modify_form.is_valid(): pwd1 = request.POST.get('password1', '') pwd2 = request.POST.get('password2', '') if pwd1 != pwd2: return render(request, 'pwdreset.html', {'email':email, 'msg':'?????'}) user = UserInfo.objects.get(email=email) user.password = make_password(password1) user.save() return render(request, 'login.html') else: return render(request, 'pwdreset.html', {'email':email, 'modify_form':modify_form})
def setUp(self): super(CheckTokenTestCase, self).setUp() # The profile token is a harsh value created with the make_password. self.profile.token = make_password("secret-token") self.profile.save()
def send_instant_login_link(self, inviting_profile=None): token = str(uuid.uuid4()) self.token = make_password(token) self.save() path = reverse("hc-check-token", args=[self.user.username, token]) ctx = { "login_link": settings.SITE_ROOT + path, "inviting_profile": inviting_profile } emails.login(self.user.email, ctx)
def send_set_password_link(self): token = str(uuid.uuid4()) self.token = make_password(token) self.save() path = reverse("hc-set-password", args=[token]) ctx = {"set_password_link": settings.SITE_ROOT + path} emails.set_password(self.user.email, ctx)