Search code examples
pythonhtmlmysqlapachelocalhost

use if condition to compare the password using python


I have HTML form for getting the name and the password .And python codes are used to get that enter data and store in variable first_name and password.

For given name stored password is fetched from database using WHERE clause . By using if condition I have tried to compare the password fetched from database and password entered from form.If they are equal then do some action .If not do some other condition .But the problem is i am not able to understand how to assign the if condition . What i tried is as given below.:

#!"C:\python34\python.exe"
import cgitb ,cgi
import sys
import mysql.connector
cgitb.enable()
form = cgi.FieldStorage() 
print("Content-Type: text/html;charset=utf-8")
print()

# Get data from fields
first_name = form.getvalue('first_name')
password = form.getvalue('pass')
print (password)
conn = mysql.connector.connect(host='localhost',port='8051',
                                       database='test',
                                       user='root',
                                       password='next')                                
cursor = conn.cursor()                                 
if conn.is_connected():
    print('Connected to MySQL database')
cursor.execute("""SELECT pass FROM tablename1 where  name = '%s'""" % (first_name))

for row in cursor():
    if(password == row):
        print("sucess")
    else:
        print("fail")

Please check my code.And give some suggestion.


Solution

  • When a user registers for the first time, you should save his password like this:

    $password = password_hash("rasmuslerdorf", PASSWORD_DEFAULT);
    

    This should output something like $2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

    And you should store it in your database.

    Then you should verify passwords like this:

    <?php
    $hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq'; // you get it from your database
    
    if (password_verify('rasmuslerdorf', $hash)) { // 'rasmuslerdorf' is what user entered
        echo 'Password is valid!';
    } else {
        echo 'Invalid password.';
    }
    ?>
    

    Now, what is a hash? Please read this.

    EDIT: you mean something like this?

     cursor.execute("SELECT * FROM users WHERE username= ? and password= ?",
        (username, pass1))
    found = cursor.fetchone()
    if found:
        # user exists and password matches
    else:
        # user does not exist or password does not match