0
votes

Before that , i want to say that i already see for many solutions and it still not working , thats why i ask this question

So i try to make a login form and a login module , when i insert the username and password correctly -> i already copy the value from the database so it will same 100% ---> but authentication always return none

i already print the value into the cmd and what i put is the same as the value in database ..

this is the login.html

<div id="login-page">
    <div class="container">
      <form class="form-login" method="post">
         {% csrf_token %}
        <h2 class="form-login-heading">sign in now</h2>
        <div class="login-wrap">
          <input type="text" name="username" class="form-control" placeholder="User ID">
          <br>
          <input type="password" name="password" class="form-control" placeholder="Password">
          <br>
           {% if messages %}
              <ul class="messages">
                {% for message in messages %}
                <font color="red"><li {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li></font>
                {% endfor %}
              </ul>
            {% endif %}
         
              <button class="btn btn-theme btn-block" type="submit" href=""><i class="fa fa-lock"></i> SIGN IN</button>          
              
          <hr>
          
      </form>
    </div>
  </div>

and this is the views for login (i already modified the login) and register

def login_view(request):
    if request.method == 'POST': 
        print("yes")        
        username = request.POST.get('username')
        password = request.POST.get('password')
        print(username)
        print(password)
        guest = User.objects.get(username=username)
        rolee= UserProfileInfo.objects.get(user_id = guest.id).role
        print(rolee)
        user = authenticate(username=username, password=password)  
        print(user)
        if user: 
            if rolee == 'Business Analyst':
                login(request, user)
                return redirect('/home/')
            elif rolee == 'Admin':
                login(request, user)
                return redirect('/manageuser/')
            elif rolee == 'Manager':
                login(request, user)
                return redirect('/approvallist/')
            elif rolee == 'Segment Manager':
                login(request, user)
                return redirect('/approvallist/')
        else:
            messages.error(request, "Invalid username or password!")
    form = AuthenticationForm()
    return render(request,"login.html",{"form":form})

def register(request):
    registered = False
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileInfoForm(data=request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save(commit=False)   
            clearPassNoHash = user_form.cleaned_data['password']
            varhash = make_password(clearPassNoHash,None,'md5')
            user.set_password(varhash)  
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user            
            profile.save()
            registered = True
        else:
            print(user_form.errors,profile_form.errors)
    else:
        user_form = UserForm()
        profile_form = UserProfileInfoForm()
    return render(request,'register.html',
                          {'user_form':user_form,
                           'profile_form':profile_form,
                           'registered':registered})

models.py

class UserProfileInfo(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    role = models.CharField(max_length=250, blank=True)
    description = models.TextField(max_length=250, blank=True)
    address = models.CharField(max_length=250, blank=True)
    phone = models.CharField(max_length=250, blank=True)
    cell = models.CharField(max_length=250, blank=True)
    def __str__(self):
      return self.user.username

Last one is : forms.py


class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())
    class Meta():
        model = User
        fields = ('username','email','password')

class UserProfileInfoForm(forms.ModelForm):
     class Meta():
         model = UserProfileInfo
         fields = ('role','description','address','phone','cell')

login before i modified

def login_view(request):
    if request.method == 'POST':         
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            guest = User.objects.get(username=username)
            role = guest.role
            user = authenticate(username=username, password=password)  
            if user is not None: 
                if role == 'Business Analyst':
                    login(request, user)
                    return redirect('/home/')
                elif role == 'Admin':
                    login(request, user)
                    return redirect('/manageuser/')
                elif role == 'Manager':
                    login(request, user)
                    return redirect('/approvallist/')
                elif role == 'Segment Manager':
                    login(request, user)
                    return redirect('/approvallist/')
            else:
                messages.error(request, "Invalid username or password!")
        else:
            messages.error(request, "Invalid username or password!")
    form = AuthenticationForm()
    return render(request,"login.html",{"form":form})

Note :

  1. first i already use form.is_valid() -> but it keeps return not valid so i remove the form.is_valid() so i can authenticate directly , but it always says none

  2. before i hash the password , my register password didnt hashed, and i search that authenticate need a hash password, so i try hash with the django.contrib.auth.backend.md5hashers or something in the settings.py , and already hashed, and it still not working.

3.the role is in the different model

I hope someone can fix it , already try many ways and cant get it done .. thankyou for the help <3

1
So what is AuthenticationForm? Is that the UserForm itself (from .forms import UserForm as AuthenticationForm)?Pedram Parsian
@PedramParsian from django.contrib.auth.forms import UserCreationForm, AuthenticationFormtrytocode
@PedramParsian i think the problem is in the user = authenticate(username=username,password=password) not the form = AuthenticationFormtrytocode
Are you using make_password to make hash password out of the raw password?Pedram Parsian
@PedramParsian yes ..trytocode

1 Answers

1
votes

I spot the issue, in your registration process, you are are using:

user = user_form.save(commit=False)   
clearPassNoHash = user_form.cleaned_data['password']
varhash = make_password(clearPassNoHash,None,'md5')
user.set_password(varhash)  
user.save()

Actually, the set_password will call the make_password itself, So you should do:

user = user_form.save(commit=False)   
clearPassNoHash = user_form.cleaned_data['password']
user.set_password(clearPassNoHash)  
user.save()

This is how set_password is defined:

    def set_password(self, raw_password):
        self.password = make_password(raw_password)
        self._password = raw_password ```