初始数据夹具中的用户

发布于 2024-12-13 13:18:30 字数 406 浏览 1 评论 0原文

默认情况下,我在 fixtures/initial_data.json 中创建一些用户,以便进行一些测试“主题”。我遇到的问题是密码生成。我可以在“字段”中设置密码,但这不会生成散列密码:

[
    { "model": "auth.user",
        "pk": 1,
        "fields": {
            "username": "user1",
            "password": "password"
        }
    }
]

我需要一种生成用户密码的方法。我是否必须像 Django 那样手动执行此操作并生成像 {hash_method}${salt}${hashed_pa​​ssword} 这样的字符串?

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. I could set the password in the 'fields', but that won't generate a hashed password:

[
    { "model": "auth.user",
        "pk": 1,
        "fields": {
            "username": "user1",
            "password": "password"
        }
    }
]

I need a way to generate the user's password. Do I have to do this manually and generate a string like {hash_method}${salt}${hashed_password} like Django does?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

没︽人懂的悲伤 2024-12-20 13:18:30

在这种情况下(如果您只需要几个用户)可能更容易的是通过管理员创建一些假用户帐户(包括密码),然后使用 dumpdata 将用户转储到固定文件中:

$ python manage.py dumpdata auth.User --indent 4 > users.json

它将自动为您创建固定装置,并可以稍后与 loaddata 一起使用

(如果您需要大量测试用户,您可以只创建一个假帐户并在其余固定装置中使用散列)

https://docs.djangoproject.com /en/dev/ref/django-admin/#dumpdata-appname-appname-appname-model

What might be easier in this case (and if you only need a few users) is to create some fake user accounts through the admin (including passwords) and then dump the users to a fixtures file using dumpdata:

$ python manage.py dumpdata auth.User --indent 4 > users.json

which will automatically create the fixtures for you and can be used later with loaddata

(You could just create one fake account and use the hash in the rest of your fixtures if you needed lots of test users)

https://docs.djangoproject.com/en/dev/ref/django-admin/#dumpdata-appname-appname-appname-model

深空失忆 2024-12-20 13:18:30

好吧,我同意答案,但让我回答原来的问题。

如何获取“Django 会对其进行哈希处理”的密码?

让我们看一下文件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.
    """
    # ...

请参阅此示例会话:

./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': <django.contrib.auth.hashers.BCryptPasswordHasher object at 0x29c6d50>,
 'crypt': <django.contrib.auth.hashers.CryptPasswordHasher object at 0x29c6f50>,
 'md5': <django.contrib.auth.hashers.MD5PasswordHasher object at 0x29c6e10>,
 'pbkdf2_sha1': <django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher object at 0x29c6bd0>,
 'pbkdf2_sha256': <django.contrib.auth.hashers.PBKDF2PasswordHasher object at 0x29c6cd0>,
 'sha1': <django.contrib.auth.hashers.SHA1PasswordHasher object at 0x29c6dd0>,
 'unsalted_md5': <django.contrib.auth.hashers.UnsaltedMD5PasswordHasher object at 0x29c6ed0>,
 'unsalted_sha1': <django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher object at 0x29c6e50>}

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']

您还可以手动使用哈希器的encode方法,但是上面的实用程序函数有您以更简单的方式进行了介绍。

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': <django.contrib.auth.hashers.BCryptPasswordHasher object at 0x29c6d50>,
 'crypt': <django.contrib.auth.hashers.CryptPasswordHasher object at 0x29c6f50>,
 'md5': <django.contrib.auth.hashers.MD5PasswordHasher object at 0x29c6e10>,
 'pbkdf2_sha1': <django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher object at 0x29c6bd0>,
 'pbkdf2_sha256': <django.contrib.auth.hashers.PBKDF2PasswordHasher object at 0x29c6cd0>,
 'sha1': <django.contrib.auth.hashers.SHA1PasswordHasher object at 0x29c6dd0>,
 'unsalted_md5': <django.contrib.auth.hashers.UnsaltedMD5PasswordHasher object at 0x29c6ed0>,
 'unsalted_sha1': <django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher object at 0x29c6e50>}

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.

〃温暖了心ぐ 2024-12-20 13:18:30

我在编写测试装置时遇到了同样的问题。这是我在单元测试中处理这个问题的方法。

从管理员创建数据并将其转储到固定装置中是可行的,但我不太喜欢依赖于手动执行此操作。所以这就是我所做的 -

就像您所做的那样创建固定装置,然后在 setUp 方法中为用户设置 set_password

user_fixture.json

[
    { "model": "auth.user",
        "pk": 1,
        "fields": {
            "username": "user1",
            "password": "password"
        }
    }
]

test_user.py

def setUp(self):
    self.User = get_user_model()

    # Fix the passwords of fixtures
    for user in self.User.objects.all():
        user.set_password(user.password)
        user.save()

这样我就可以干净地将密码写在fixture中,并在需要时引用它们,并且只需编辑fixt​​ure文件即可创建更多fixture。

I came across the same problem while writing fixtures for tests. Here's how I'm handling this in unit tests.

Creating data from admin and dumping them into fixture works but I don't quite like being dependent on manually doing it. So here's what I do -

Create the fixture just as you've done and then in the setUp method, set_passwords for the users.

user_fixture.json

[
    { "model": "auth.user",
        "pk": 1,
        "fields": {
            "username": "user1",
            "password": "password"
        }
    }
]

test_user.py

def setUp(self):
    self.User = get_user_model()

    # Fix the passwords of fixtures
    for user in self.User.objects.all():
        user.set_password(user.password)
        user.save()

This way I can cleanly write the passwords in fixture and refer back to them when I need to and create more fixtures simply by editing the fixture file.

暮光沉寂 2024-12-20 13:18:30

添加到 @GauravButola 的答案中,我创建了一个自定义管理命令来加载夹具并一步修复密码。当不使用测试框架来设置密码时,这非常有用。该示例适用于 django 1.11 以及可能更早的版本。

在提供固定装置的应用程序中添加您的管理命令(这是 python3 次,所以我省略了 init pys):

yourapp/
    models.py
    fixtures/
        initial_data.json
    management/
        commands/
            initdata.py

initdata.py 如下所示:

from django.core.management import BaseCommand, call_command
from django.contrib.auth.models import User
# from yourapp.models import User # if you have a custom user


class Command(BaseCommand):
    help = "DEV COMMAND: Fill databasse with a set of data for testing purposes"

    def handle(self, *args, **options):
        call_command('loaddata','initial_data')
        # Fix the passwords of fixtures
        for user in User.objects.all():
            user.set_password(user.password)
            user.save()

现在您可以通过调用以下命令加载初始数据并拥有有效的密码:

./manage.py initdata

Adding to the answer of @GauravButola, I created a custom management command to load the fixture and fix the passwords in one step. This is useful when not using a testing framework to do the setup of the passwords. The example is working with django 1.11 and probably earlier versions.

In your app providing the fixture add your management command (this is python3 times, so I omitted the init pys):

yourapp/
    models.py
    fixtures/
        initial_data.json
    management/
        commands/
            initdata.py

With initdata.py looking like this:

from django.core.management import BaseCommand, call_command
from django.contrib.auth.models import User
# from yourapp.models import User # if you have a custom user


class Command(BaseCommand):
    help = "DEV COMMAND: Fill databasse with a set of data for testing purposes"

    def handle(self, *args, **options):
        call_command('loaddata','initial_data')
        # Fix the passwords of fixtures
        for user in User.objects.all():
            user.set_password(user.password)
            user.save()

Now you can load your initial_data and have valid passwords by calling:

./manage.py initdata
善良天后 2024-12-20 13:18:30

从数据库转储用户信息:

$ python manage.py dumpdata auth.User --indent 4 > users.json

导入/加载特定 JSON 夹具的数据:

$ python manage.py loaddata users.json

Dump Users information from DataBase:

$ python manage.py dumpdata auth.User --indent 4 > users.json

Import / load data especific JSON fixture:

$ python manage.py loaddata users.json
青萝楚歌 2024-12-20 13:18:30

使用方法make_password(admin_password)
它位于 django.contrib.auth.hashers 中

Use the method make_password(admin_password).
It's in django.contrib.auth.hashers

活雷疯 2024-12-20 13:18:30

很肯定你会的。应该没那么难。最简单的方法是查看我认为的 user.set_password 函数,看看他们是如何做到的。您可以从 python 终端调用该函数,然后将其复制到您的初始数据中!

pretty sure you do. it shouldn't be that difficult. easiest way would be to look at the function user.set_password i think it is, and look how they do it. you can probably call the function from a python terminal and then copy it into your initial data!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文