1

Here is my problem: I'm tying to authenticate a custom AbstractBaseUser from shell:

>>from django.contrib import auth
>>u = auth.authenticate(username = '[email protected]', password = '123')
>>u == None
True
>>from userprofiles.models import MyUser
>> MyUser(email = '[email protected]', password = '321', date_of_birth='1999-9-9').save()
>>u = auth.authenticate(username = '[email protected]', password = '321')
>>u == None
True
>>u = auth.authenticate(email= '[email protected]', password = '321') #just to check
>>u == None
True

Tried with users saved from form (beacause of pass hash), users inserted manually in db and users made and saved from shell.

Here is my User model class:

from django.db import models
from django.utils.crypto import get_random_string
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser)
import string
import random


class MyUserManager(BaseUserManager):
  def create_user(self, email, date_of_birth, password=None):
      """
      Creates and saves a User with the given email, date of
      birth and password.
      """
      if not email:
          raise ValueError('Users must have an email address')

      user = self.model(
          email=self.normalize_email(email),
          date_of_birth=date_of_birth,
      )

      user.set_password(password)
      user.save(using=self._db)
      return user

  def create_superuser(self, email, date_of_birth, password):
      """
      Creates and saves a superuser with the given email, date of
      birth and password.
      """
      user = self.create_user(email,
                            password=password,
                            date_of_birth=date_of_birth
                            )
      user.is_admin = True
      user.save(using=self._db)
      return user


class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    date_of_birth = models.DateField()
    role = models.CharField(max_length=15, default='guest')
    confirmation_key = models.CharField(max_length=50,default = '/')
    registration_confirmed = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['date_of_birth']

def is_guest(self):
    if self.role == 'guest':
        return True
    return False

def is_restaurant_manager(self):
    if self.role == 'restmanager':
        return True
    return False

def is_system_manager(self):
    if self.role == 'sysmanager':
        return True
    return False

def get_role(self):
    return self.role

def get_full_name(self):
    # The user is identified by their email address
    return self.email

def get_short_name(self):
    # The user is identified by their email address
    return self.email

def __str__(self):              # __unicode__ on Python 2
    return self.email

def has_perm(self, perm, obj=None):
    "Does the user have a specific permission?"
    # Simplest possible answer: Yes, always
    return True

def has_module_perms(self, app_label):
    "Does the user have permissions to view the app `app_label`?"
    # Simplest possible answer: Yes, always
    return True

@property
def is_staff(self):
    "Is the user a member of staff?"
    # Simplest possible answer: All admins are staff
    return self.is_admin

def set_reg_key(self, key):
    self.confirmation_key = key

Here is the view where i save it to db:

def register_user(request):
if request.method == 'POST':
    form = UserCreationForm(request.POST)
    if form.is_valid():
        print "usao"
        form.save()

        print form.cleaned_data['email']
        emailk = form.cleaned_data['email']
        set_unique_reg_key(emailk)
        return HttpResponseRedirect('/accounts/register1success')
    else:
        print "false je"

args = {}
args.update(csrf(request))
args['form']=UserCreationForm()
return render_to_response('userprofiles/register.html', args)


def set_unique_reg_key(emailk):
    reg_key = ''.join(random.choice(string.ascii_uppercase) for i in range(12))
    uu = MyUser.objects.filter(confirmation_key=reg_key)
    if not uu:
        try:
            u = MyUser.objects.get(email=emailk)
        except(KeyError, MyUser.DoesNotExist):
            print

        u.set_reg_key(reg_key)
        print u.confirmation_key
        u.save()
    else:
        set_unique_reg_key(emailk)

Here is form:

class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password',     widget=forms.PasswordInput,required=True)
password2 = forms.CharField(label='Password confirmation',     widget=forms.PasswordInput,required=True)

class Meta:
    model = MyUser
    fields = ('email', 'date_of_birth')

def clean_password2(self):
    # Check that the two password entries match
    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError("Passwords don't match")
    return password2

def save(self, commit=True):
    # Save the provided password in hashed format
    user = super(UserCreationForm, self).save(commit=False)
    user.set_password(self.cleaned_data["password1"])
    if commit:
        user.save()
    return user

Also, i have set:

AUTH_PROFILE_MODULE = 'userprofiles.MyUser'

And, if I understood corectly authenticate should work for any model made from AbstractBaseUser..so I haven't made CustomBackend.

2 Answers 2

1

I think you should use AUTH_USER_MODEL instead of AUTH_PROFILE_MODULE if you are using Django 1.7 or later, because it is removed according th this.

Sign up to request clarification or add additional context in comments.

3 Comments

Tried, but nothing changed..and i don't belive that is the problem because this setting is from django-doc, labeled with "Documentation version: 1.8". Thanks anyway. :)
My mistake its, AUTH_USER_MODEL in 1.8..but still not working
This was correct answer, I opened debuger and saw that get_user_model() return django's user..then i checked my settings and instead of AUTH_USER_MODEL i wrote AUTH_USER_MODULE..2 days to find mistake like this :@
0

What is the name of your app? The syntax of AUTH_USER_MODEL is app.model.

Your problem might be with the authenticate function. Here's my function from my own custom model.

def authenticate(self, username=None, password=None):
        """ Authenticate a user based on email address as the user name. """
        try:
            user = UserAccount.objects.get(email=username)
            if user.check_password(password):
                return user
        except UserAccount.DoesNotExist:
            return None

Then again, you're sending the email as the username to authenticate...

4 Comments

The issue might be that you're not using a backend. Here's my authenticate function for my own custom model (in my anwser)
I could write my own function to simply check if there's user in db..but isn't the point of making custom user from AbstractBaseUser to be used instead of django's User? So authenticate should work for this..I tried to pass email parameter, and now it makes no sense, I agree(lack of ideas)..but before that I tried with username if you look again..Don't know what else can I try..
Try to change the USERNAME_FIELD of your user model to the email field. Just a stab in the dark.
USERNAME_FIELD is set to email field from the beginning

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.