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

The following are 30 code examples of django.contrib.auth.hashers.check_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: jwt.py    From dvhb-hybrid with MIT License 49224 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 #2
Source File: test_handlers_django.py    From jarvis with 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 #3
Source File: test_views.py    From django-user-management with 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 #4
Source File: views.py    From oxidizr with 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 #5
Source File: test_views.py    From django-user-management with 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
Source File: test_views.py    From django-user-management with 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
Source File: auth.py    From wharf with 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 #8
Source File: test_views.py    From django-user-management with 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 #9
Source File: test_views.py    From django-user-management with 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 #10
Source File: models.py    From healthchecks with 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 #11
Source File: user.py    From omniport-backend with 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 #12
Source File: test_handlers_django.py    From jarvis with 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 #13
Source File: user.py    From dvhb-hybrid with 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 #14
Source File: user.py    From dvhb-hybrid with 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 #15
Source File: views.py    From autoops with 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 #16
Source File: models.py    From ika with 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) 
Example #17
Source File: test_views.py    From cookiecutter-django-rest with MIT License 5 votes vote down vote up
def test_post_request_with_valid_data_succeeds(self):
        response = self.client.post(self.url, self.user_data)
        eq_(response.status_code, status.HTTP_201_CREATED)

        user = User.objects.get(pk=response.data.get('id'))
        eq_(user.username, self.user_data.get('username'))
        ok_(check_password(self.user_data.get('password'), user.password)) 
Example #18
Source File: test_serializers.py    From cookiecutter-django-rest with MIT License 5 votes vote down vote up
def test_serializer_hashes_password(self):
        serializer = CreateUserSerializer(data=self.user_data)
        ok_(serializer.is_valid())

        user = serializer.save()
        ok_(check_password(self.user_data.get('password'), user.password)) 
Example #19
Source File: test_views.py    From django-user-management with 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 #20
Source File: models.py    From django_mqtt with 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 #21
Source File: models.py    From django_mqtt with 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 #22
Source File: auth.py    From callisto-core with 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 #23
Source File: password_validation.py    From zentral with 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 #24
Source File: forms.py    From BookForum with 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 #25
Source File: forms.py    From BookForum with 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 #26
Source File: schema.py    From cms with 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 #27
Source File: custom_auth_backend.py    From MultiExplorer with 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 #28
Source File: test_password_change.py    From conf_site with 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 #29
Source File: views.py    From django-simple-forum with 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 #30
Source File: models.py    From substra-backend with 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)