當前位置: 首頁>>代碼示例>>Python>>正文


Python hashers.make_password方法代碼示例

本文整理匯總了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}) 
開發者ID:stormsha,項目名稱:StormOnline,代碼行數:27,代碼來源:views.py

示例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)


# 登錄 
開發者ID:michwh,項目名稱:onehome-server,代碼行數:25,代碼來源:views.py

示例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)) 
開發者ID:lykops,項目名稱:lykops,代碼行數:25,代碼來源:password.py

示例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}) 
開發者ID:abaoMAO,項目名稱:django_OA,代碼行數:23,代碼來源:views.py

示例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() 
開發者ID:betagouv,項目名稱:mrs,代碼行數:20,代碼來源:0002_auto_adduser.py

示例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) 
開發者ID:avuletica,項目名稱:eLearning,代碼行數:26,代碼來源:views.py

示例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() 
開發者ID:getway,項目名稱:diting,代碼行數:25,代碼來源:user.py

示例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}) 
開發者ID:myminwang,項目名稱:online,代碼行數:25,代碼來源:views.py

示例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=/') 
開發者ID:vstconsulting,項目名稱:polemarch,代碼行數:25,代碼來源:api.py

示例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)) 
開發者ID:vstconsulting,項目名稱:polemarch,代碼行數:18,代碼來源:api.py

示例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}) 
開發者ID:fengjinqi,項目名稱:website,代碼行數:21,代碼來源:views.py

示例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) 
開發者ID:blackholll,項目名稱:loonflow,代碼行數:25,代碼來源:account_base_service.py

示例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 
開發者ID:blackholll,項目名稱:loonflow,代碼行數:27,代碼來源:account_base_service.py

示例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)) 
開發者ID:haynieresearch,項目名稱:jarvis,代碼行數:24,代碼來源:test_handlers_django.py

示例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) 
開發者ID:haynieresearch,項目名稱:jarvis,代碼行數:24,代碼來源:utils.py


注:本文中的django.contrib.auth.hashers.make_password方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。