5

我为我的 django 应用程序创建了一个用户模型

class User(Model):
    """
    The Authentication model. This contains the user type.  Both Customer and
    Business models refer back to this model.
    """
    email = EmailField(unique=True)
    name = CharField(max_length=50)
    passwd = CharField(max_length=76)
    user_type = CharField(max_length=10, choices=USER_TYPES)
    created_on = DateTimeField(auto_now_add=True)
    last_login = DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.email

    def save(self, *args, **kw):
        # If this is a new account then encrypt the password.
        # Lets not re-encrypt it everytime we save.
        if not self.created_on:
            self.passwd = sha256_crypt.encrypt(self.passwd)
        super(User, self).save(*args, **kw)

我还创建了一个身份验证中间件来使用这个模型。

from accounts.models import User
from passlib.hash import sha256_crypt

class WaitformeAuthBackend(object):
    """
    Authentication backend fo waitforme
    """

    def authenticate(self, email=None, password=None):
        print 'authenticating : ', email
        try:
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            user = None

        if user and sha256_crypt.verify(password, user.passwd):
            return user
        else:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

我已经正确修改了 settings.py 文件,如果我在这个后端添加一些打印语句,我可以看到用户详细信息打印出来。我不记得读过我需要在 django 文档中实现 is_authenticated 。我错过了什么愚蠢的东西吗?

4

2 回答 2

5

I'm not quite sure why you have created a new User model instead of using Django's built-in one and adding a linked UserProfile, which is the recommended thing to do (until 1.5 is released, when pluggable user models will be available). However, yes you need to define an is_authenticated method, which always returns True: this is exactly what the built-in model does. The reason is that if you have an actual User, it will always be authenticated: otherwise, you will have an AnonymousUser object, whose is_authenticated method always returns False.

于 2012-11-03T10:28:21.440 回答
2

你不必重新发明轮子。只需使用 Django 内置的身份验证系统,就可以省去很多麻烦。您还可以根据需要扩展它或使用不同的身份验证后端。在这里阅读。HTH。

于 2012-11-02T23:41:35.130 回答