gpt4 book ai didi

python - 将密码字段迁移到 Django

转载 作者:太空狗 更新时间:2023-10-29 22:20:06 25 4
gpt4 key购买 nike

我以前使用过 Django(1.2 版),总体上我喜欢它……它特别擅长快速启动和运行一个全新的项目。但是,在这种情况下,我正在重写现有系统并将其移动到 Python/Django。所以,我已经有一个 MySQL 数据库,里面有一个“用户”表……这个表使用 MySQL SHA1 函数(无盐等)存储用户密码。

作为迁移的一部分,我将修复一些数据建模缺陷并移植到 PostgreSQL。

我真的很想使用 django.contrib.auth,但我不清楚我需要做什么。我已经阅读了文档,并且知道我可以将所需的用户信息和我拥有的“额外”信息分开并放入 UserProfile 中。

但是,如何处理存储在 MySQL 数据库中的密码?

有没有人处理过这个?你采取了什么方法?

最佳答案

以下是我为使事情正常进行所做的工作。我创建了一个自定义身份验证后端。注意:我使用电子邮件地址作为用户名。

这是我的代码:

from django.db.models import get_model
from django.contrib.auth.models import User
from hashlib import sha1

class MyUserAuthBackend(object):

def check_legacy_password(self, db_password, supplied_password):
return constant_time_compare(sha1(supplied_password).hexdigest(), db_password)


def authenticate(self, username=None, password=None):
""" Authenticate a user based on email address as the user name. """
try:
user = User.objects.get(email=username)

if '$' not in user.password:
if self.check_legacy_password(user.password, password):
user.set_password(password)
user.save()
return user
else:
return None

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

except User.DoesNotExist:
return None


def get_user(self, user_id):
""" Get a User object from the user_id. """
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None

然后我将以下内容添加到 settings.py 中:

AUTHENTICATION_BACKENDS = (
'my_website.my_app.my_file.MyUserAuthBackend',
)

@Dougal 的建议似乎是针对下一个 Django 版本的,但对我来说不可用(我使用的是 1.3.1)。但是,这似乎是一个更好的解决方案。

关于python - 将密码字段迁移到 Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8190642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com