Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authenticate with Django 1.5

Tags:

django

i'm currently testing django 1.5 and it custom USer model, but i've some understanding problems i've created a User class in my account app, which looks like :

class User(AbstractBaseUser):
    email = models.EmailField()
    activation_key = models.CharField(max_length=255)
    is_active = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'

i can corectly register a user, who is stored in my account_user table. Now, how can i log in ? I've tried with

def login(request):
    form = AuthenticationForm()
    if request.method == 'POST':
        form = AuthenticationForm(request.POST)
        email =  request.POST['username']
        password = request.POST['password'] 
        user = authenticate(username=email, password=password)
        if user is not None:
            if user.is_active:
                login(user)
            else:
                message = 'disabled account, check validation email'
                return render(
                        request, 
                        'account-login-failed.html', 
                        {'message': message}
                )
    return render(request, 'account-login.html', {'form': form})

but user is None the it render the login form :( Why my autheticate returns me None ? Any idea ?

forms.py

class RegisterForm(forms.ModelForm):
    """ a form to create user"""
    password = forms.CharField(
            label="Password",
            widget=forms.PasswordInput()
    )
    password_confirm = forms.CharField(
            label="Password Repeat",
            widget=forms.PasswordInput()
    )
    class Meta:
        model = User
        exclude = ('last_login', 'activation_key')

    def clean_password_confirm(self):
        password = self.cleaned_data.get("password")
        password_confirm = self.cleaned_data.get("password_confirm")
        if password and password_confirm and password != password_confirm:
            raise forms.ValidationError("Password don't math")
        return password_confirm

    def clean_email(self):
        if User.objects.filter(email__iexact=self.cleaned_data.get("email")):
            raise forms.ValidationError("email already exists")
        return self.cleaned_data['email']

    def save(self):
        user = super(RegisterForm, self).save(commit=False)
        user.password = self.cleaned_data['password']
        user.activation_key = generate_sha1(user.email)
        user.save()

        return user
like image 331
billyJoe Avatar asked Dec 14 '12 17:12

billyJoe


1 Answers

The Django documentation has a really good example of using the new custom user.

From your code the only thing I see missing is the custom authentication backend.

I have a file named auth.py. The methods "authenticate" and "get_user" are required.

from models import User as CustomUser

class CustomAuth(object):

    def authenticate(self, username=None, password=None):
        try:
            user = CustomUser.objects.get(email=username)
            if user.check_password(password):
                return user
        except CustomUser.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            user = CustomUser.objects.get(pk=user_id)
            if user.is_active:
                return user
            return None
        except CustomUser.DoesNotExist:
            return None

Then the authentication backends have to be specified in your settings file

AUTHENTICATION_BACKENDS = ('apps.accounts.auth.CustomAuth')
like image 194
lval Avatar answered Oct 10 '22 04:10

lval