How to Encrypt Password before saving it to User Model Django?
Asked Answered
C

3

6

I've created a user-signup page which adds users to User Model in Django

But when the data is saved, the Password is not encrypted, i.e. stored as Text only. This creates a problem when the user tries to log in (as Django tries to Decrypt the original password, and they both don't match).

Also, I'm extending the User Model so as to add more information about the users which is saved in the Profile Model (Using a One-To-One Link)

views.py

def user_signup(request):
    if request.method == "POST":
        user_form = userSignup(request.POST)
        phone = request.POST['phone']
        address = request.POST['address']
        pincode = request.POST['pincode']
        
        if user_form.is_valid() :
            user = user_form.save()
            auth.login(request,user)
            userdata = User.objects.all()
            for userinfo in userdata:
                if userinfo.username == user.username:
                    user_id=user.id
            update_data = Profile.objects.get(pk = user_id)
            update_data.address=address
            update_data.phone=phone
            update_data.pincode=pincode
            update_data.save()
            return redirect('/')

        else:
            return HttpResponse(" SIGNUP FAILED")

    else:
        form = userSignup()
        profile_form = userSignup_profile()
        return render(request,"user_signup.html",{'form':form, 'profile_form':profile_form})


def user_logout(request):
    auth.logout(request)
    return redirect('/')

user_signup.html

<body>
    <form action="user_signup" method="POST"> 
        {% csrf_token %}
        {{form.as_p}}
        {{ profile_form.as_p}}
        <button class="primary" type="submit" >SIGNUP </button>
    </form>
</body>

Models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phone = models.CharField(max_length=10)
    address = models.TextField(max_length=200)
    pincode = models.IntegerField()

forms.py

class userSignup(forms.ModelForm):
    password = forms.CharField(max_length=50, widget = forms.PasswordInput())

    class Meta:
        model = User
        fields = ('first_name', 'last_name','username', 'password',  'email')

How can I save the new user password in Encrypted form, and not the actual password??

enter image description here

Caporetto answered 1/5, 2020 at 15:57 Comment(1)
set_passwordGeneralist
R
7
# You have to import make_password

from django.contrib.auth.hashers import make_password

# you have to pass string as parameter
password = "123"
make_password(password)



# You can write your code like this:-


def user_signup(request):
    if request.method == "POST":
        user_form = userSignup(request.POST)
        phone = request.POST['phone']
        address = request.POST['address']
        pincode = request.POST['pincode']

        if user_form.is_valid() :
            user = user_form.save(commit=False)
            user.password = make_password("123")
            user.save()
            .......
            .......
Ruphina answered 1/5, 2020 at 16:12 Comment(0)
D
2

Django make_password (source code) function converts a plain-text password into a hash that is appropriate for storing in a persistent database.

You definitely do not want to try to roll your own encryption and hashing functions for storing passwords when this function already exists.

Simply edit your views.py to:

from django.contrib.auth.hashers import make_password

def user_signup(request):
    if request.method == "POST":
        user_form = userSignup(request.POST)
        phone = request.POST['phone']
        address = request.POST['address']
        pincode = request.POST['pincode']

        if user_form.is_valid() :
            # Hash password using make_password() function
            user = user_form.save(commit=False)
            user.password = make_password(user.password)
            user.save()

            ...
Deathwatch answered 1/5, 2020 at 16:29 Comment(2)
It didn't work. Exception Type : AttributeError Exception Value: 'userSignup' object has no attribute 'password'Caporetto
you're using 'pincode' rather than 'password'. Either update the model to from pincode to password, or update the if statement in user_signup to user.pincode = make_password(user.pincode)Oyler
G
0
import crypt
# To encrypt the password. This creates a password hash with a random salt.
password_hash = crypt.crypt(password)

# To check the password.
valid_password = crypt.crypt(cleartext, password_hash) == password_hash

Source: https://docs.djangoproject.com/en/1.8/topics/auth/passwords/#django.contrib.auth.hashers.make_password

Guidebook answered 12/12, 2021 at 19:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.