Question

I've created a User model for my django app

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)

I've also created an authentication middleware to use this model.

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

I have ammended the settings.py file correctly and if I add some print statements to this backend I can see the user details print out. I don't recall reading that I need to implement is_authenticated in the django docs. Am I missing something silly?

Was it helpful?

Solution

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.

OTHER TIPS

you dont have to reinvent the wheel. Just use Djangos build in authentication system and save yourself a lot of trouble. You can also extend it to your needs or use different authentication backends. Have a read here. HTH.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top