Users in initial data fixture

后端 未结 6 1672
臣服心动
臣服心动 2021-01-31 01:50

I\'m creating a few users by default in my fixtures/initial_data.json so as to have some testing \"subjects.\" The problem I\'m experiencing is password generation.

6条回答
  •  抹茶落季
    2021-01-31 01:57

    OK, I agree with the answers, but let me answer the original questions.

    How to get the password "as Django would have hashed it"?

    Let's look a the file django/contrib/auth/hashers.py:

    def make_password(password, salt=None, hasher='default'):
        """
        Turn a plain-text password into a hash for database storage
    
        Same as encode() but generates a new random salt.  If
        password is None or blank then UNUSABLE_PASSWORD will be
        returned which disallows logins.
        """
        # ...
    

    See this example session:

    ./manage.py shell
    
    >>> from django.contrib.auth.hashers import make_password, HASHERS
    >>> make_password('test')
    'pbkdf2_sha256$10000$vkRy7QauoLLj$ry+3xm3YX+YrSXbri8s3EcXDIrx5ceM+xQjtpLdw2oE='
    
    # fix salt:
    >>> make_password('test', 'abc')
    'pbkdf2_sha256$10000$abc$MqJS5OAgSmf9SD9mfoY8fgLo8sSKmEcef0AjjMp1Q7w='
    
    # use different (maybe faster, maybe unsafe!) hasher
    
    In [12]: HASHERS
    Out[12]:
    {'bcrypt': ,
     'crypt': ,
     'md5': ,
     'pbkdf2_sha1': ,
     'pbkdf2_sha256': ,
     'sha1': ,
     'unsalted_md5': ,
     'unsalted_sha1': }
    
    In [14]: [make_password('test', hasher=name) for name in HASHERS]
    Out[14]:
    ['sha1$LdKsAbJRjlVP$2eb2346387cc510f576f2f11eebdfe18b20d1be1',
     'pbkdf2_sha256$10000$Ck8gtWQJnJ9x$M/OqP548d5KcPqFuVRgXb84unjYbYDH6oyimbDndE3k=',
     'pbkdf2_sha1$10000$BJqRu5OwylVF$hUvMLIzBujt9kPbML/dei1vLiMQ=',
     'crypt$$d9grSeqDhMFek',
     '098f6bcd4621d373cade4e832627b4f6',
     'sha1$$a94a8fe5ccb19ba61c4c0873d391e987982fbbd3',
     'bcrypt$$2a$12$WlJP5zm2lmdJ4g/pSE1xF.d/8w.XRT5mo/vGlkKdglBtzcxKw7XJS',
     'md5$txHYmSYJKhD4$69286d4a1abd348fbddc9df7687e2ed4']
    

    You can also manually use the hasher's encode method, but the above utility function has you covered in an easier way.

提交回复
热议问题