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

The following are 30 code examples for showing how to use django.contrib.auth.hashers.check_password(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

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
Project: oxidizr   Author: pixlie   File: views.py    License: GNU General Public License v2.0 6 votes vote down vote up
def form_valid(self, form):
        user_email = form.cleaned_data['email'].lower().strip()
        password = form.cleaned_data['password']
        user = authenticate(email=user_email, password=password)
        if user and user.is_active:
            login(self.request, user)
            return redirect(self.get_success_url())
        else:
            try:
                user = User.objects.get(email__iexact=user_email)
                if not check_password(password, user.password):
                    form._errors['password'] = ErrorList([u'That is not the correct Password.'])
            except User.DoesNotExist:
                form._errors['email'] = ErrorList([u'This email is not registered with us.'])
            context = self.get_context_data(form=form)
            return self.render_to_response(context) 
Example 2
Project: healthchecks   Author: healthchecks   File: models.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_token(self, token, salt):
        return salt in self.token and check_password(token, self.token) 
Example 3
Project: wharf   Author: palfrey   File: auth.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def authenticate(self, request, username=None, password=None):
        login_valid = (settings.ADMIN_LOGIN == username)
        if settings.ADMIN_PASSWORD.startswith("pbkdf2_sha256"):
            pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
        else:
            pwd_valid = password == settings.ADMIN_PASSWORD
        if login_valid and pwd_valid:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                # Create a new user. There's no need to set a password
                # because only the password from settings.py is checked.
                user = User(username=username)
                user.is_staff = True
                user.is_superuser = True
                user.save()
            return user
        return None 
Example 4
Project: django-user-management   Author: incuna   File: test_views.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_put(self):
        old_password = '0ld_passworD'
        new_password = 'n3w_Password'
        user = UserFactory.create(password=old_password)

        token = default_token_generator.make_token(user)
        uid = urlsafe_base64_encode(force_bytes(user.pk))

        request = self.create_request(
            'put',
            data={'new_password': new_password, 'new_password2': new_password},
            auth=False,
        )
        view = self.view_class.as_view()
        response = view(request, uidb64=uid, token=token)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # Get the updated user from the db
        user = User.objects.get(pk=user.pk)
        self.assertTrue(user.check_password(new_password)) 
Example 5
Project: django-user-management   Author: incuna   File: test_views.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_password_mismatch(self):
        old_password = '0ld_passworD'
        new_password = 'n3w_Password'
        invalid_password = 'different_new_password'
        user = UserFactory.create(password=old_password)

        token = default_token_generator.make_token(user)
        uid = urlsafe_base64_encode(force_bytes(user.pk))

        request = self.create_request(
            'put',
            data={
                'new_password': new_password,
                'new_password2': invalid_password,
            },
            auth=False,
        )
        view = self.view_class.as_view()
        response = view(request, uidb64=uid, token=token)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        # Get the updated user from the db
        user = User.objects.get(pk=user.pk)
        self.assertTrue(user.check_password(old_password)) 
Example 6
Project: django-user-management   Author: incuna   File: test_views.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_update(self):
        old_password = '0ld_passworD'
        new_password = 'n3w_Password'

        user = UserFactory.create(password=old_password)

        request = self.create_request(
            'put',
            user=user,
            data={
                'old_password': old_password,
                'new_password': new_password,
                'new_password2': new_password,
            })
        view = self.view_class.as_view()
        response = view(request)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        user = User.objects.get(pk=user.pk)
        self.assertTrue(user.check_password(new_password)) 
Example 7
Project: django-user-management   Author: incuna   File: test_views.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_update_wrong_old_password(self):
        old_password = '0ld_passworD'
        new_password = 'n3w_Password'

        user = UserFactory.create(password=old_password)

        request = self.create_request(
            'put',
            user=user,
            data={
                'old_password': 'invalid_password',
                'new_password': new_password,
                'new_password2': new_password,
            })
        view = self.view_class.as_view()
        response = view(request)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        user = User.objects.get(pk=user.pk)
        self.assertTrue(user.check_password(old_password)) 
Example 8
Project: django-user-management   Author: incuna   File: test_views.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_update_mismatched_passwords(self):
        old_password = '0ld_passworD'
        new_password = 'n3w_Password'
        invalid_password = 'different_new_password'

        user = UserFactory.create(password=old_password)

        request = self.create_request(
            'put',
            user=user,
            data={
                'old_password': old_password,
                'new_password': new_password,
                'new_password2': invalid_password,
            })
        view = self.view_class.as_view()
        response = view(request)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        user = User.objects.get(pk=user.pk)
        self.assertTrue(user.check_password(old_password)) 
Example 9
Project: jarvis   Author: haynieresearch   File: test_handlers_django.py    License: GNU General Public License v2.0 6 votes vote down vote up
def fuzz_verifier_django(self):
        try:
            self._require_django_support()
        except SkipTest:
            return None
        from django.contrib.auth.hashers import check_password

        def verify_django(secret, hash):
            """django/check_password"""
            if self.handler.name == "django_bcrypt" and hash.startswith("bcrypt$$2y$"):
                hash = hash.replace("$$2y$", "$$2a$")
            if 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")
            return check_password(secret, hash)
        return verify_django 
Example 10
Project: dvhb-hybrid   Author: dvhb   File: jwt.py    License: MIT License 6 votes vote down vote up
def user_login(request, email, password, connection=None):
    models = request.app.models
    user = await models.user.get_user_by_email(email, connection=connection)
    if user:
        if not user.is_active:
            raise web.HTTPForbidden(reason="User disabled")
        elif check_password(password, user.password):
            await models.user_action_log_entry.create_login(
                request, user_id=user.pk, connection=connection)
            token = request.app.context.jwt.generate(uid=user.id)
            return web.json_response(
                {
                    'uid': user.id,
                    'profile': await user.get_profile(connection=connection),
                    'token': token,
                }, headers={'Authorization': 'Bearer %s' % token},
            )
    raise web.HTTPUnauthorized(reason="Login incorrect") 
Example 11
Project: onehome-server   Author: michwh   File: views.py    License: MIT License 5 votes vote down vote up
def post(self, request, format=None):
        data = request.data
        username = data.get('username')
        password = data.get('password')
        try:
            user = User.objects.get(username__exact=username)
        except User.DoesNotExist:
            user = None
        if user:
            if check_password(password, user.password):
                serializer = UserSerializer(user)
                new_data = serializer.data
                # 记忆已登录用户,作为用户是否拥有某项权限的认证
                # self.request.session['user_username'] = user.username
                token = Token.objects.get(user_id=user.id)
                q = Auth(configs.get('qiniu').get('AK'), configs.get('qiniu').get('SK'))
                base_url = configs.get('qiniu').get('domain') + '/'
                user_image_url = q.private_download_url(base_url + new_data.get('user_image_url'), expires=86400)
                timeArray = time.strptime(str(user.last_login), "%Y-%m-%d %H:%M:%S")
                new_obj = {
                    'id': user.id,
                    # 'password': user.password,
                    'username': new_data.get('username'),
                    'token': token.key,
                    'user_image_url': user_image_url,
                    'last_login': time.mktime(timeArray),
                }
                # print(time.mktime(timeArray))
                user.last_login = time.strftime("%Y-%m-%d %H:%M:%S")
                user.save(update_fields=['last_login'])
                return Response({"stateCode": 200, "msg": new_obj}, status=HTTP_200_OK)
            else:
                return Response({"stateCode": 202, "msg": "密码不正确"}, 202)  # 密码不正确
        else:
            return Response({"stateCode": 201, "msg": "用户不存在"}, 201)  # 用户不存在


# 生成商品图片上传的token 
Example 12
Project: desec-stack   Author: desec-io   File: base.py    License: MIT License 5 votes vote down vote up
def assertToken(self, plain, user=None):
        user = user or self.owner
        self.assertTrue(any(check_password(plain, hashed, preferred='pbkdf2_sha256_iter1')
                            for hashed in Token.objects.filter(user=user).values_list('key', flat=True)))
        self.assertEqual(len(Token.make_hash(plain).split('$')), 4) 
Example 13
Project: substra-backend   Author: SubstraFoundation   File: models.py    License: Apache License 2.0 5 votes vote down vote up
def check_password(self, raw_secret):
        """
        Return a boolean of whether the raw_password was correct. Handles
        hashing formats behind the scenes.
        """
        def setter(raw_secret):
            self.set_password(raw_secret)
            # Password hash upgrades shouldn't be considered password changes.
            self._secret = None
            self.save(update_fields=["secret"])
        return check_password(raw_secret, self.secret, setter) 
Example 14
Project: django-simple-forum   Author: MicroPyramid   File: views.py    License: MIT License 5 votes vote down vote up
def form_valid(self, form):
        user = self.request.user
        if not check_password(self.request.POST['oldpassword'], user.password):
            return JsonResponse({
                'error': True,
                'response': {'oldpassword': 'Invalid old password'}
            })
        if self.request.POST['newpassword'] != self.request.POST['retypepassword']:
            return JsonResponse({
                'error': True,
                'response': {'newpassword': 'New password and Confirm Passwords did not match'}
            })
        user.set_password(self.request.POST['newpassword'])
        user.save()
        return JsonResponse({'error': False, 'message': 'Password changed successfully'}) 
Example 15
Project: conf_site   Author: pydata   File: test_password_change.py    License: MIT License 5 votes vote down vote up
def test_successful_password_change(self):
        """Verify change success when entering password properly."""
        response = self._force_login_and_change_password({
            "oldpassword": self.password,
            "password1": self.new_password,
            "password2": self.new_password,
        })
        # User should be redirected if there are no form errors.
        self.assertRedirects(
            response=response, expected_url=reverse("account_change_password")
        )
        # Verify that user's new password was set correctly.
        # Re-retrieve user so that we can access new password.
        user = get_user_model().objects.get(email=self.user.email)
        assert hashers.check_password(self.new_password, user.password) 
Example 16
Project: MultiExplorer   Author: priestc   File: custom_auth_backend.py    License: MIT License 5 votes vote down vote up
def authenticate(self, username=None, password=None):
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            return None

        if check_password(password, user.password):
            return user

        # try running password through same scrypt params as front end.
        encoded_password = scrypt.hash(str(password), str(username), 16384, 8, 1).encode('hex')
        if check_password(encoded_password, user.password):
            return user
        return None 
Example 17
Project: cms   Author: amfoss   File: schema.py    License: GNU General Public License v3.0 5 votes vote down vote up
def mutate(self, info, password, newPassword):
        infoUser = info.context.user
        user = User.objects.values().get(username=infoUser)
        match = check_password(password, user['password'])
        if match:
            infoUser.set_password(newPassword)
            infoUser.save()
            return userStatusObj(status=True)
        else:
            raise APIException('Wrong Password',
                               code='WRONG_PASSWORD') 
Example 18
Project: BookForum   Author: Arianxx   File: forms.py    License: MIT License 5 votes vote down vote up
def clean_old_password(self):
        old_password = self.cleaned_data.get('old_password')

        if not check_password(old_password, self.user.password):
            raise forms.ValidationError('密码错误')
        else:
            return old_password 
Example 19
Project: BookForum   Author: Arianxx   File: forms.py    License: MIT License 5 votes vote down vote up
def clean_password(self):
        password = self.cleaned_data['password']

        if not check_password(password, self.user.password):
            raise forms.ValidationError('密码错误')
        else:
            return password 
Example 20
Project: zentral   Author: zentralopensource   File: password_validation.py    License: Apache License 2.0 5 votes vote down vote up
def validate(self, password, user=None):
        if user is None:
            return
        if user.check_password(password):
            raise ValidationError(
               _("Please, pick a new password."),
               code='password_already_used',
               params={'min_unique_passwords': self.min_unique_passwords},
            )
        tested_passwords = 1  # 1 because we have already checked the current one
        for uph in user.userpasswordhistory_set.all().order_by("-id"):
            tested_passwords += 1
            if check_password(password, uph.password):
                raise ValidationError(
                    _("This password has already been used."),
                    code='password_already_used',
                    params={'min_unique_passwords': self.min_unique_passwords},
                )
            if self.min_unique_passwords and self.min_unique_passwords >= tested_passwords:
                break 
Example 21
Project: callisto-core   Author: project-callisto   File: auth.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def authenticate(self, request, username, password):
        username = sha256(username.encode("utf-8")).hexdigest()
        username_index = index(username)
        for user in Account.objects.filter(username_index=username_index):
            if not user or not bcrypt.checkpw(
                username.encode("utf-8"), user.encrypted_username.encode("utf-8")
            ):
                return None

            if not check_password(password, user.user.password):
                return None

            return self.get_user(user.user.id)
        return None 
Example 22
Project: django_mqtt   Author: ehooo   File: models.py    License: GNU General Public License v2.0 5 votes vote down vote up
def check_password(self, raw_password):
        """
        Return a boolean of whether the raw_password was correct. Handles
        hashing formats behind the scenes.
        """
        def setter(raw_password):  # pragma: no cover
            self.set_password(raw_password)
            # Password hash upgrades shouldn't be considered password changes.
            self._password = None
            self.save(update_fields=["password"])
        return check_password(raw_password, self.password, setter) 
Example 23
Project: django_mqtt   Author: ehooo   File: models.py    License: GNU General Public License v2.0 5 votes vote down vote up
def has_permission(self, user=None, password=None):
        allow = False
        if self.is_public():
            allow = self.allow
        else:
            if user:
                if user in self.users.all():
                    allow = self.allow
                elif self.groups.filter(pk__in=user.groups.values_list('pk')).exists():
                    allow = self.allow
                else:
                    allow = not self.allow
            if self.password and password:
                allow = self.check_password(password)
        return allow 
Example 24
Project: omniport-backend   Author: IMGIITRoorkee   File: user.py    License: GNU General Public License v3.0 5 votes vote down vote up
def check_secret_answer(self, given_answer):
        """
        Compare the given answer with the set security answer
        :param given_answer: the answer to check against the database
        :return: true if the answers match, false otherwise
        """

        return check_password(
            password=given_answer,
            encoded=self.secret_answer,
        ) 
Example 25
Project: django-user-management   Author: incuna   File: test_views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_unauthenticated_user_post(self):
        """Unauthenticated Users should be able to register."""
        request = self.create_request('post', auth=False, data=self.data)

        response = self.view_class.as_view()(request)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(len(mail.outbox), 1)

        email = mail.outbox[0]
        verify_url_regex = re.compile(
            r'''
                https://example\.com/\#/register/verify/
                [0-9A-Za-z:\-_]+/  # token
            ''',
            re.VERBOSE,
        )
        self.assertRegex(email.body, verify_url_regex)
        html_email = email.alternatives[0][0]
        self.assertRegex(html_email, verify_url_regex)

        user = User.objects.get()
        self.assertEqual(user.name, self.data['name'])
        self.assertEqual(user.email, self.data['email'])
        # Should be hash, not literal password
        self.assertNotEqual(user.password, self.data['password'])

        # Password should validate
        self.assertTrue(check_password(self.data['password'], user.password)) 
Example 26
Project: jarvis   Author: haynieresearch   File: test_handlers_django.py    License: GNU General Public License v2.0 5 votes vote down vote up
def test_90_django_reference(self):
        """run known correct hashes through Django's check_password()"""
        self._require_django_support()
        # XXX: esp. when it's no longer supported by django,
        #      should verify it's *NOT* recognized
        from django.contrib.auth.hashers import check_password
        assert self.known_correct_hashes
        for secret, hash in self.iter_known_hashes():
            self.assertTrue(check_password(secret, hash),
                            "secret=%r hash=%r failed to verify" %
                            (secret, hash))
            self.assertFalse(check_password('x' + secret, hash),
                            "mangled secret=%r hash=%r incorrect verified" %
                            (secret, hash)) 
Example 27
Project: dvhb-hybrid   Author: dvhb   File: user.py    License: MIT License 5 votes vote down vote up
def login(request, email, password, connection=None):
    user = await request.app.models.user.get_user_by_email(email, connection=connection)
    if user:
        if not user.is_active:
            raise HTTPConflict(reason="User disabled")
        elif check_password(password, user.password):
            await gen_api_key(user.id, request=request, auth='email')
            request.user = user
            await user.on_login(connection=connection)
            await request.app.m.user_action_log_entry.create_login(request, connection=connection)
            response = dict(status=200, data=dict(uid=user.id))
            return json_response(response, headers={'Authorization': request.api_key})
    raise HTTPUnauthorized(reason="Login incorrect") 
Example 28
Project: dvhb-hybrid   Author: dvhb   File: user.py    License: MIT License 5 votes vote down vote up
def change_password(request, old_password, new_password, connection=None):
    if not check_password(old_password, request.user.password):
        raise ValidationError(old_password=['Wrong password'])
    request.user['password'] = make_password(new_password)
    await request.user.save(fields=['password'], connection=connection)
    await request.app.m.user_action_log_entry.create_change_password(request, connection=connection) 
Example 29
Project: autoops   Author: hequan2017   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def password_update(request):
    if request.method == 'POST':
        form = UserPasswordForm(request.POST)
        if form.is_valid():
            old = User.objects.get(username=request.user)
            old_pass=old.password
            input_pass =form.cleaned_data['old_password']
            check = check_password(input_pass,old_pass)
         #   ps = make_password(old_p, None, 'pbkdf2_sha256')
            if  check  is True:
                if  form.cleaned_data['new_password']  == form.cleaned_data['confirm_password'] :
                    password=form.cleaned_data['new_password']
                    old.set_password(password)
                    old.save()
                    msg= "修改成功"
                else:
                    msg="两次输入的密码不一致"
                form = UserPasswordForm()
                return render(request, 'names/password.html',{'form': form, "msg": msg})
            else:
                form = UserPasswordForm()
                return render(request, 'names/password.html',{'form': form, "msg": "旧密码不对,请重新输入"})

    else:
        form = UserPasswordForm()
    return render(request, 'names/password.html',{'form': form, }) 
Example 30
Project: ika   Author: devunt   File: models.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def check_password(self, raw_password):
        def setter(_raw_password):
            self.set_password(_raw_password)
            self.save(update_fields=['password'])
        return check_password(raw_password, self.password, setter)