当前位置: 首页>>代码示例>>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;未经允许,请勿转载。