简体   繁体   中英

django only allowing super user for authentication

I am getting problem with django authentication, Only superuser is able to authenticate. Here is my Model

#models.py
class UserManager(BaseUserManager):

def create_user(self, username, email, password):
    if not email:
        raise ValueError('Users must have an email address')

    elif not username:
        raise ValueError('Users must have an username')

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

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

def create_superuse..................

class User(AbstractBaseUser):
    email = models.EmailField(
    verbose_name='email address',
    max_length=255,
    unique=True,
)
    username = models.CharField(
    verbose_name='username',
    max_length=30,
    unique=True,
)

    phonenumber = PhoneNumberField(verbose_name="phonenumber",max_length=13,
                null=True,unique=True)
    name = models.CharField(max_length=30, blank=True)

    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    .............

In my setting I added this.

#settings.py
AUTH_USER_MODEL = 'accounts.User'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'accounts.backends.MyPhonenumberBackend',
)

This is my backend

#backends.py
from django.contrib.auth import get_user_model

class MyPhonenumberBackend(object):

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

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

My views

#views.py
def seller_login_view(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password  = request.POST.get('password')

        user = authenticate(username=username,password=password)

        if user:
            if user.is_active:
                login(request,user)
                return HttpResponseRedirect(reverse('home'))

            else:
                return HttpReponse('Account is not active')
        else:
            print('Someone tries to login and failed')
            print('username: {} and password {}'.format(username,password))
            return HttpResponse('Invalid Username and Password')

    else:
        return render(request,'accounts/registered/seller_login.html',{})

I am using custom template for login page

<form method="POST" action="{% url 'accounts:login' %}">
    {% csrf_token %}
    <input type="text" id="login" class="fadeIn second" name="username" placeholder="Email or Phonenumber">
    <input type="password" id="password" class="fadeIn third" name="password" placeholder="password">
    <input type="submit" class="fadeIn fourth" value="Log In">
  </form>

Now When I try to login with my superuser account it works fine but when I use other user no authentication occur(Invalid user name and password). I am unable to figure out problem, thanks in advance for help and giving me time.

Try this in your views

def login_page(request):
    if request.user.is_authenticated:
        return redirect('SOMEWHERE')
    else:
        form = LoginForm(request.POST or None)
        context = {
            "form": form
                  }

        if form.is_valid():
            username  = form.cleaned_data.get("username")
            password  = form.cleaned_data.get("password")
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login(request, user)


                return redirect(redirect_path)
            else:
                return redirect("SOMEWHERE")
        else:
            # Return an 'invalid login' error message.
            #print("Error")
    return render(request, "students/login.html", context)

This will be in forms.py and import it in your views.

class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM