Python django.contrib.auth.hashers.make_password() Examples

The following are 30 code examples of django.contrib.auth.hashers.make_password(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.auth.hashers , or try the search function .
Example #1
Source File: views.py    From django_OA with GNU General Public License v3.0 7 votes vote down vote up
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}) 
Example #2
Source File: views.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
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, "reset_pwd": modify_form}) 
Example #3
Source File: 0002_auto_adduser.py    From mrs with GNU Affero General Public License v3.0 6 votes vote down vote up
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() 
Example #4
Source File: views.py    From eLearning with GNU Lesser General Public License v2.1 6 votes vote down vote up
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) 
Example #5
Source File: api.py    From polemarch with GNU Affero General Public License v3.0 6 votes vote down vote up
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=/') 
Example #6
Source File: api.py    From polemarch with GNU Affero General Public License v3.0 6 votes vote down vote up
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)) 
Example #7
Source File: views.py    From website with MIT License 6 votes vote down vote up
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}) 
Example #8
Source File: views.py    From website with MIT License 6 votes vote down vote up
def post(self,request):
         forms = ModifyForm(request.POST)
         if forms.is_valid():
             pwd1 = forms.cleaned_data.get('password')
             pwd2 = forms.cleaned_data.get('password1')
             email = forms.cleaned_data.get('email')

             if pwd1!=pwd2:
                 return JsonResponse({'status':400,"email":email,"message":"密码不一致"})
             is_user = User.objects.filter(email=email)
             if is_user:

                User.objects.filter(email=email).update(password=make_password(pwd2))
                return JsonResponse({'status':200,"email":email,"message":"密码修改成功"})
             return JsonResponse({'status': 400, "email": email, "message": '邮箱不存在'})
         else:
            email = request.POST.get('email')
            return JsonResponse({'status':400,"email":email, "message":'验证失败请检查后提交'}) 
Example #9
Source File: views.py    From online with GNU Affero General Public License v3.0 6 votes vote down vote up
def post(self, request):
        pwdmodify_form = PwdmodifyForm(request.POST)
        res = dict()
        if pwdmodify_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 = pwdmodify_form.errors
        return HttpResponse(json.dumps(res), content_type='application/json') 
Example #10
Source File: views.py    From online with GNU Affero General Public License v3.0 6 votes vote down vote up
def post(self, request):
        """密码重置处理"""
        pwdmodify_form = PwdmodifyForm(request.POST)
        if pwdmodify_form.is_valid():
            password1 = request.POST.get('password1', '')
            password2 = request.POST.get('password2', '')
            pwdmodify_email = request.POST.get('email', '')
            pwdmodify_code = request.POST.get('pwdreset_code', '')
            if password1 == password2:
                pwdmodify_user = UserProfile.objects.get(email=pwdmodify_email)
                pwdmodify_user.password = make_password(password1)
                pwdmodify_user.save()

                pwdmodify_code_es = EmailVerification.objects.filter(code=pwdmodify_code)
                for pwdmodify_code_e in pwdmodify_code_es:
                    pwdmodify_code_e.is_delete = 1
                    pwdmodify_code_e.save()

                    return render(request, 'login.html', {'pwdreset_msg': '密码重置成功,请登录'})
            else:
                return render(request, 'password_reset.html',
                              {'pwdmodify_form': pwdmodify_form, 'msg': '两次输入不一致,请重新输入'})
        else:
            return render(request, 'password_reset.html', {'pwdmodify_form': pwdmodify_form}) 
Example #11
Source File: account_base_service.py    From loonflow with MIT License 6 votes vote down vote up
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) 
Example #12
Source File: account_base_service.py    From loonflow with MIT License 6 votes vote down vote up
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 
Example #13
Source File: test_handlers_django.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
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)) 
Example #14
Source File: views.py    From online with GNU Affero General Public License v3.0 6 votes vote down vote up
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}) 
Example #15
Source File: utils.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #16
Source File: 0003_create_system_user.py    From connect with MIT License 6 votes vote down vote up
def create_system_user(apps, schema_editor):
    """Create a new system user if one does not exist"""
    User = apps.get_model('accounts', 'User')

    system_user_email = getattr(
        settings, 'CONNECT_SYSTEM_USER_EMAIL', 'no-reply@localhost')

    # As apps.get_model() does not expose `set_unusable_password` we must make
    # our own unusable password. This can be done by sending `None` to
    # `make_password`
    unuseable_password = make_password(None)

    user, created = User.objects.get_or_create(
        email=system_user_email,
        defaults={
            'username': system_user_email,
            'is_active': True,
            'is_superuser': True,
            'last_login': now(),
            'date_joined': now(),
            'password': unuseable_password
        }
    ) 
Example #17
Source File: user.py    From diting with GNU General Public License v2.0 6 votes vote down vote up
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() 
Example #18
Source File: password.py    From lykops with Apache License 2.0 6 votes vote down vote up
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)) 
Example #19
Source File: admin.py    From OnlineJudge with MIT License 6 votes vote down vote up
def post(self, request):
        """
        Import User
        """
        data = request.data["users"]

        user_list = []
        for user_data in data:
            if len(user_data) != 3 or len(user_data[0]) > 32:
                return self.error(f"Error occurred while processing data '{user_data}'")
            user_list.append(User(username=user_data[0], password=make_password(user_data[1]), email=user_data[2]))

        try:
            with transaction.atomic():
                ret = User.objects.bulk_create(user_list)
                UserProfile.objects.bulk_create([UserProfile(user=user) for user in ret])
            return self.success()
        except IntegrityError as e:
            # Extract detail from exception message
            #    duplicate key value violates unique constraint "user_username_key"
            #    DETAIL:  Key (username)=(root11) already exists.
            return self.error(str(e).split("\n")[1]) 
Example #20
Source File: views.py    From ImitationTmall_Django with GNU General Public License v3.0 6 votes vote down vote up
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}) 
Example #21
Source File: views.py    From onehome-server with MIT License 6 votes vote down vote up
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)


# 登录 
Example #22
Source File: views.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
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}) 
Example #23
Source File: models.py    From django_mqtt with GNU General Public License v2.0 5 votes vote down vote up
def set_unusable_password(self):
        # Set a value that will never be a valid hash
        self.password = make_password(None) 
Example #24
Source File: models.py    From django_mqtt with GNU General Public License v2.0 5 votes vote down vote up
def set_password(self, raw_password):
        self.password = make_password(raw_password)
        self._password = raw_password 
Example #25
Source File: 0006_add_service_user.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def add_service_user(apps, schema_editor):
        app_name, _, model_name = settings.AUTH_USER_MODEL.rpartition('.')
        User = apps.get_model(app_name, model_name)

        service_user = User.objects.create(
            username=settings.ECOMMERCE_SERVICE_WORKER_USERNAME,
            is_superuser=True
        )
        service_user.password = make_password(None)
        service_user.save() 
Example #26
Source File: 0002_set_default_admin_password.py    From django-collaborative with MIT License 5 votes vote down vote up
def forwards(apps, schema_editor):
    username = os.getenv("COLLAB_ADMIN_USERNAME", "admin")
    email = os.getenv("COLLAB_ADMIN_EMAIL")
    password = os.getenv("COLLAB_ADMIN_PASSWORD")
    User = apps.get_model("auth", "User")
    # Don't create a new admin account if users exist (this means
    # the user has already gone through the user config or that
    # they have ran createsuperuser)
    if User.objects.count() > 0:
        logger.info("Users exist! Not creating default admin")
        return
    # Don't create blank passwords!
    if not password:
        logger.info("Password not set in environment. Bailing.")
        return
    logger.info("Creating default user=%s email=%s pass=%s" % (
        username, email, "*****" if password else "(Blank pass)"
    ))
    user = User(
        username=username,
        email=email,
        password=make_password(password),
        is_staff=True,
        is_superuser=True,
    )
    user.save() 
Example #27
Source File: views.py    From SecurityManageFramwork with GNU General Public License v3.0 5 votes vote down vote up
def strtopsd(string):
    hash_res = hashlib.md5()
    hash_res.update(make_password(string).encode('utf-8'))
    urlarg = hash_res.hexdigest()
    return urlarg 
Example #28
Source File: views.py    From logtacts with MIT License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        if request.user.is_authenticated():
            messages.warning(
                self.request,
                "Logged-in users can't accept invitations",
                )
            return redirect(reverse('contacts-list', kwargs={
                'book': self.request.current_book.id,
            }))
        invite = get_object_or_404(
            Invitation.objects,
            key=kwargs.get('key'),
            status=Invitation.SENT,
        )
        # By this point we should have a good invite.
        password_plain = get_random_string(20)
        password = make_password(password_plain)
        user = User.objects.create(
            username=invite.email,
            email=invite.email,
            password=password,
        )
        user = authenticate(username=invite.email, password=password_plain)
        if invite.book:
            self.book = invite.book
            BookOwner.objects.create_for_user(user=user, book=invite.book)
        else:
            self.book = Book.objects.create_for_user(user)
        user.save()
        login(request, user)
        invite.status = invite.ACCEPTED
        invite.save()
        response = super(AcceptInviteView, self).get(request, *args, **kwargs)
        return response 
Example #29
Source File: auth.py    From wharf with GNU Affero General Public License v3.0 5 votes vote down vote up
def __call__(self, request):
        if not request.user.is_authenticated:
            path = request.path_info.lstrip('/')
            if not any(m.match(path) for m in EXEMPT_URLS):
                redirect_to = settings.LOGIN_URL
                # Add 'next' GET variable to support redirection after login
                if len(path) > 0 and is_safe_url(url=request.path_info, allowed_hosts=None):
                    redirect_to = "%s?next=%s" %(settings.LOGIN_URL, request.path_info)
                return HttpResponseRedirect(redirect_to)
        elif not settings.ADMIN_PASSWORD.startswith("pbkdf2_sha256"):
            better_password = make_password(settings.ADMIN_PASSWORD)
            messages.warning(request, "ADMIN_PASSWORD is in plain text. Set it to %s instead" % better_password)
        return self.get_response(request) 
Example #30
Source File: oauth.py    From dvhb-hybrid with MIT License 5 votes vote down vote up
def _create_new_user(self, user_info, provider, connection):
        user = self.model(email=user_info['email'], password=make_password(get_random_string()), is_active=True)
        self.model.set_defaults(user)
        await user.save(connection=connection)
        await user.save_oauth_info(provider, user_info['id'], connection=connection)
        await user.patch_profile(user_info, connection=connection)
        logger.info(
            "Created new user email '%s' for oauth provider '%s' ID '%s'",
            user_info['email'], provider, user_info['id'])
        return user