简体   繁体   中英

How to Encrypt Password before saving it to User Model Django?

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, ie 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??

在此处输入图像描述

# 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()
            .......
            .......

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()

            ...

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 [official link][ www 1]

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