Giter Club home page Giter Club logo

django-hashers-passlib's People

Contributors

fritz-k avatar julianwachholz avatar mathiasertl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

django-hashers-passlib's Issues

Share a patch for Django 4.2

I've been using this module to add pbkdf2_sha256 support for my Django project.

However, when I upgraded Django from 3.2 to 4.2, I encountered a problem due to the deprecation of ugettext_noop in Django 4.2, which caused errors in the project. Aside from this, Passlib worked well without any other issues.

Since both this project and its dependency, passlib, invoked ugettext_noop, it seemed that simply updating the reference to ugettext_noop (actually just replacing ugettext_noop with gettext_noop) might solve the problem.

But I found that both libraries haven't been updated for a while, and just submitting a PR here wouldn't fix the issues in both libraries. So, I tried using a patching approach to address this issue and am sharing it for others who might encounter the same problem.


My Approach

You'll need to create a new app, for example, passlib_patch, and then add a patches.py file.

from django.utils.translation import gettext_noop as _

# This file is a patch for django-hashers-passlib==0.4 and passlib==1.7.4 with Django 4.2. 
# These packages have not been updated for a long time and do not support Django 4.2.

def apply_patches():
    # Patch for passlib.ext.django.utils
    try:
        from passlib.ext.django.utils import _PasslibHasherWrapper

        # Patched safe_summary method to use the patched _ function instead of the original ugettext_noop
        def patched_safe_summary(self, encoded):
            from collections import OrderedDict
            from django.contrib.auth.hashers import mask_hash
            handler = self.passlib_handler
            items = [
                (_('algorithm'), handler.name),
            ]
            if hasattr(handler, "parsehash"):
                kwds = handler.parsehash(encoded, sanitize=mask_hash)
                for key, value in kwds.items():
                    key = self._translate_kwds.get(key, key)
                    items.append((_(key), value))
            return OrderedDict(items)

        _PasslibHasherWrapper.safe_summary = patched_safe_summary
    except ImportError as e:
        # Handle the case where passlib is not installed
        print(f"Failed to apply patch for passlib: {e}")

    # Patch for hashers_passlib
    try:
        # Check if ugettext_noop already exists, if not, add it
        from django.utils.translation import ugettext_noop
    except ImportError:
        # Dynamically add ugettext_noop pointing to gettext_noop in the django.utils.translation module
        import django.utils.translation
        django.utils.translation.ugettext_noop = _

        # Now safely import hashers_passlib since ugettext_noop has been added
        import hashers_passlib

        # Since we've successfully imported hashers_passlib, this indicates the patch has taken effect,
        # If necessary, original state can be restored here
        # However, typically, if ugettext_noop is not directly used elsewhere in the Django project, restoration may not be needed

    except Exception as e:
        print(f"Unexpected error while applying patch for hashers_passlib: {e}")

Then add the following code in apps.py:

from django.apps import AppConfig

class PasslibPatchConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'passlib_patch'

    def ready(self):
        from .patches import apply_patches
        apply_patches()

And add in __init__.py:

from . import patches

default_app_config = 'passlib_patch.apps.PasslibPatchConfig'

I wrote a tests.py file and passed the tests.

from django.test import TestCase
from django.contrib.auth import get_user_model
from passlib.hash import django_pbkdf2_sha256 as handler
from wp_user.patches import apply_patches

apply_patches()

class PasslibHashersTestCase(TestCase):
    def test_passlib_functionality(self):
        hashed = handler.hash("s3cr3t")
        self.assertTrue(handler.verify("s3cr3t", hashed), "Password verification failed!")

    def test_hashers_passlib_integration(self):
        User = get_user_model()
        user = User(username='testuser')
        user.set_password('my_password')
        user.save()

        self.assertTrue(user.check_password('my_password'), "User password verification failed!")

I can't guarantee that this code will work for everyone, but this patch did fix the error for me.

If there are any questions, feel free to discuss.

Cannot import name SortedDict while trying to log into the admin panel

I had the summary problem (which I solved upgrading to 0.2) but now I have this one while logging into admin panel.
`

Request Method: POST
http://127.0.0.1:8000/admin/login/?next=/admin/
1.11.2
ImportError
cannot import name SortedDict
E:\stack_overflower\Documents\Dev\SDKs\python\python27\lib\site-packages\hashers_passlib_init_.py in , line 23
E:\stack_overflower\Documents\Dev\SDKs\python\python27\python.exe
2.7.10
['E:\stack_overflower\Documents\Dev\Repos\BitBucket\CrossFitSassuolo', 'e:\stack_overflower\documents\dev\sdks\python\python27\scripts\src\django-mailer', 'E:\stack_overflower\Documents\Dev\SDKs\python\python27\lib\site-packages\django_spirit-0.5.0.dev0-py2.7.egg', 'E:\stack_overflower\Documents\Dev\SDKs\python\python27\lib\site-packages\pytz-2017.2-py2.7.egg', 'E:\stack_overflower\Documents\Dev\SDKs\python\python27\lib\site-packages\unicode_slugify-0.1.4-py2.7.egg', 'E:\stack_overflower\Documents\Dev\SDKs\python\python27\lib\site-packages\django_djconfig-0.5.3-py2.7.egg', 'E:\stack_overflower\Documents\Dev\SDKs\python\python27\lib\site-packages\django_infinite_scroll_pagination-0.2.0-py2.7.egg', 'E:\stack_overflower\Documents\Dev\SDKs\python\python27\lib\site-packages\mistune-0.7.1-py2.7.egg', 'E:\stack_overflower\Documents\Dev\SDKs\python\python27\lib\site-packages\whoosh-2.7.0-py2.7.egg', 'E:\stack_overflower\Documents\Dev\SDKs\python\python27\lib\site-packages\unidecode-0.4.20-py2.7.egg', 'C:\WINDOWS\SYSTEM32\python27.zip', 'E:\stack_overflower\Documents\Dev\SDKs\python\python27\DLLs', 'E:\stack_overflower\Documents\Dev\SDKs\python\python27\lib', 'E:\stack_overflower\Documents\Dev\SDKs\python\python27\lib\plat-win', 'E:\stack_overflower\Documents\Dev\SDKs\python\python27\lib\lib-tk', 'E:\stack_overflower\Documents\Dev\SDKs\python\python27', 'E:\stack_overflower\Documents\Dev\SDKs\python\python27\lib\site-packages']
Mar, 19 Set 2017 00:51:31 +0200
`

ImportError when running tests in django 1.8+

Running the test suite from django.contrib.auth.hashers import load_hashers throws an ImportError

running test
Traceback (most recent call last):
  File "setup.py", line 122, in <module>
    "Topic :: System :: Systems Administration :: Authentication/Directory",
  File "/usr/lib/python3.5/distutils/core.py", line 148, in setup
    dist.run_commands()
  File "/usr/lib/python3.5/distutils/dist.py", line 955, in run_commands
    self.run_command(cmd)
  File "/usr/lib/python3.5/distutils/dist.py", line 974, in run_command
    cmd_obj.run()
  File "setup.py", line 73, in run
    from test import test_hashers
  File "/home/fritz/projekte/django-hashers-passlib/test/test_hashers.py", line 31, in <module>
    from django.contrib.auth.hashers import load_hashers
ImportError: cannot import name 'load_hashers'

Looks like load_hashers was removed in django 1.8.

NotImplementedError() raised

Receiving this error after adding 'hashers_passlib.phpass' to PASSWORD_HASHERS in Django 1.6.2 settings. Looking at the BasePasswordHasher class in Django I see this documentation:

When creating your own hasher, you need to override algorithm,
verify(), encode() and safe_summary().

It appears that django-hashers-passlib is missing the required safe_summary() method when overriding the BasePasswordHasher class.

I hastily added a safe_summary() method to PasslibHasher that I pulled out of django.contrib.auth.hashers that works for PHPass so that I could move past this roadblock for the time being. Obviously this won't work for all hashes:

def safe_summary(self, encoded):
        from django.contrib.auth.hashers import mask_hash, _, SortedDict
        algorithm, salt, hash = encoded.split('$', 2)
        assert algorithm == self.algorithm
        return SortedDict([
            (_('algorithm'), algorithm),
            #(_('salt'), mask_hash(salt, show=2)),
            (_('hash'), mask_hash(hash)),
        ])

How to use bcrypt in Django without bycrypt$ prefix?

How can I use the provided converter to use bcrypted passwords without having a bcrypt$ prefix for all password hashes?

Using the converter 'hashers_passlib.converters.bcrypt' as PASSWORD_HASHERS is not working. django.contrib.auth.hashers.BCryptPasswordHasher is working if the passwords are having the bcrypt$ prefix.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.