将密码字段迁移到Django

Dav*_*d S 6 python mysql passwords django postgresql

我之前使用过Django(版本1.2)并且通常我喜欢它...它特别擅长快速启动并运行全新的项目.但是,在这种情况下,我正在重写和现有系统并将其移动到Python/Django.所以,我已经拥有一个MySQL数据库,里面有一个"users"表...这个表存储了用户密码和MySQL SHA1函数(没有盐等).

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

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

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

以前有人处理过吗?你采取了什么方法?

Dav*_*d S 8

这就是我做的事情.我创建了一个自定义身份验证后端.注意:我使用电子邮件地址作为用户名.

这是我的代码:

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
Run Code Online (Sandbox Code Playgroud)

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

AUTHENTICATION_BACKENDS = (
    'my_website.my_app.my_file.MyUserAuthBackend',
)
Run Code Online (Sandbox Code Playgroud)

来自@Dougal的建议似乎是Django的下一个版本,并且不适用于我(我使用的是1.3.1).但是,它似乎是一个更好的解决方案.