skip to Main Content

I am working on a vehicle project management system, and using a custom table for storing the signup details in MySQL. When the user logins the authenticate function returns none always, I am using email and password fields for login

  1. checked the values are retrieving from database correctly or not
  2. The backend authentication

Here is userProfile model

class UserProfiles(models.Model):
full_name=models.CharField(max_length=200)
phone_number=models.IntegerField()
email=models.CharField(unique=True,max_length=20)
password=models.CharField(max_length=200)
# is_active = models.BooleanField(default=True)
# is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['full_name', 'phone_number']
def set_password(self, password):
    self.password = make_password(password)
def check_password(self, password):
    return check_password(password, self.password)

def userLogin(request):
    if request.method == 'POST':
        email = request.POST.get('email')
        password = request.POST.get('password')
        print('from loginhtml page',email,password)
        try:
            user_profile = UserProfiles.objects.get(email=email)
            user = authenticate(request, username=email, password=password)
            print("from database  ",user_profile.email,user_profile.password)
            print(user)
            if user is not None:
                login(request, user)
                messages.success(request, 'You have been logged in successfully.')
                return redirect('/DashboardPage.html')
            else:
                error_message='Invalid email or password. Please try again.'
                messages.error(request, error_message)
        except UserProfiles.DoesNotExist:
            error_message='Invalid email or password. Please try again.'
            messages.error(request, error_message)

    return render(request, 'userLogin.html')
from django.contrib.auth.backends import BaseBackend
from django.contrib.auth import get_user_model
from django.shortcuts import redirect

from .models import UserProfiles
class UserProfileBackend(BaseBackend):
    def authenticate(self, request, email=None, password=None):
        try:
            user = UserProfiles.objects.get(email=email)
            if user.check_password(password):
                return user
        except UserProfiles.DoesNotExist:
            return None

{% load static %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Vehicle Parking Management System - User Login</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="{% static 'styles/loginstyle.css' %} ">

    </head>
  <body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <a class="navbar-brand text-primary" href="#">Vehicle Parking Management System</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
         </nav>
    <div class="container mt-5">
      <h1 class="text-center mb-5"><em><strong>Welcome to the Vehicle Parking Management System</strong></em></h1>
      <div class="row">
        <div class="col-md-6 offset-md-3">
          <div class="card">
            <div class="card-body">
              <h5 class="card-title text-center">User Login</h5>
              <form action="{% url 'parkingapp:userLogin' %}" method="POST">
              {% csrf_token %}
                <div class="form-group">
                  <label for="email">Email Address</label>
                  <input type="email" class="form-control" id="email"  name='email' placeholder="Enter your email address">
                </div>
                <div class="form-group">
                  <label for="password">Password</label>
                  <input type="password" class="form-control" id="password" name="password" placeholder="Enter your password">
                </div>

                      {% if messages %}
        <ul class="messages">
            {% for message in messages %}
                <li>{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
            {% endfor %}
        </ul>
    {% endif %}
                <button type="submit" class="btn btn-primary btn-block">Login</button>
              </form>
              <div class="text-center">
              
            <p class="text-center">Don't have an existing account? <a href="{% url 'parkingapp:userSignup' %}" class="btn btn-link">Sign up here</a></p>
            </div>
            </div>
            </div>
            </div>
            </div>
            </div>
            </div>
   <script src="{% static 'js/loginscript.js' %}"></script>
            </body>
            </html>


I also tried this code , result is none

testuser = authenticate(username='[email protected]', password='sim')
        print(testuser)

Then tried printing the data fetching from table, It is retrieving the email and password.

user = authenticate(request, username=email, password=password) print("from database ",user_profile.email,user_profile.password) print(user)

from loginhtml page [email protected] vim
from database [email protected] vim
None
None

2

Answers


  1. Chosen as BEST ANSWER

    I changed the model to Django's built in table auth user and changed the code according to that. It worked for me.

    Here is my views.py

    from django.contrib.auth import authenticate, login, logout
    from django.contrib.auth.decorators import login_required
    from django.http import HttpResponse
    from django.shortcuts import render, redirect
    from django.contrib import messages
    from django.contrib.auth.models import User
    from django.views.decorators.csrf import csrf_protect
    
    
    # Create your views here.
    def index(request):
        return render(request,'adminPage.html')
    
    def userSignup(request):
          print("hello inside usersignup")
          if request.method == 'POST':
              print("hello inside POST")
              username=request.POST['user_name']
              full_name = request.POST['full_name']
              email = request.POST['email']
              password = request.POST['password']
              print("hello THE CTEDENTIALS ARE")
              print(full_name,email,password)
             
           user=User.objects.create_user(username=username,first_name=full_name, email=email,password=password)
            
            user.save()
            user = authenticate(request, username=email, password=password)
            if user is not None and hasattr(user, '_meta'):
                login(request, user)
                messages.success(request, "Registration successful." )
                return redirect('Veh_App:DashboardPage')
    
          messages.error(request, "Unsuccessful registration. Invalid information.")
          return render(request, 'userSignup.html')
    
    def userLogin(request):
        if request.method=='POST':
            username=request.POST.get('username')
            pass1=request.POST.get('password')
            print(username,pass1)
            user=authenticate(request,username=username,password=pass1)
            print(user)
            if user is not None:
                login(request,user)
                messages.info(request, f"You are now logged in as {username}.")
                return redirect('Veh_App:DashboardPage')
            else:
                context = {'error': 'Invalid credentials'}
                return render(request, 'userlogin.html', context)
        else:
            return render(request, 'userLogin.html')
    
    def LogoutPage(request):
        print("In logout bef")
        logout(request)
        print("after")
        messages.info(request, "You have successfully logged out.")
        print("In logout")
        return redirect('index')
    
    
    @login_required(login_url='login')
    def DashboardPage(request):
        return render(request,'DashboardPage.html')
    
    @csrf_protect
    def loginadmin(request):
        return render(request, 'admin_login.html')
    

  2. There are a few problems in your code. The main one being the User model. You are not using Django’s, which is a bad practice. Take a look at this example. I would recommend to rebuild your model based on this.

    Now, related to your current problem, that is happening because of the fields you are calling on authenticate and the fields you set in the custom backend.

    views.py

    def userLogin(request):
        if request.method == 'POST':
            ...
            try:
                ...
                user = authenticate(request, username=email, password=password)
                ...
                
        return render(request, 'userLogin.html')
    

    backend.py

    class UserProfileBackend(BaseBackend):
        def authenticate(self, request, email=None, password=None): # Here is the problem
            try:
                user = UserProfiles.objects.get(email=email) # Also happens in this line
                if user.check_password(password):
                    return user
            except UserProfiles.DoesNotExist:
                return None
    

    As you can see, you pass username as a param in authenticate, but try to catch it as email in your custom backend. And, since email is always none, so is the user, just modify the param accordingly:

    class UserProfileBackend(BaseBackend):
        def authenticate(self, request, username=None, password=None):
            try:
                user = UserProfiles.objects.get(email=username)
                if user.check_password(password):
                    return user
            except UserProfiles.DoesNotExist:
                return None
    

    Although, even if you fix that, another error is raised because you are not using Django’s User model (missing a field required in login). So we need to modify yours:

    models.py

    class UserProfiles(models.Model):
        last_login = models.DateTimeField(blank=True, null=True)
        ...
    

    And, of course add the backend to AUTHENTICATION_BACKENDS:

    settings.py

    AUTHENTICATION_BACKENDS = ['core.backend.UserProfileBackend']
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search