Flask Api for Creating, Storing and Verifying Bcrypt Hash Password

Abhishek Kumar Gupta
3 min readApr 29, 2024

--

I am writing this article because during implementing and verifying the bcrypt hash password with the hash string which is stored hash inside postgresSql db was not working. After long time R&D I didn’t get the exact solution of my problem. Hence I though I will write one article to help other developer after getting the solution. In this article I have used the following pip packages.

Hader

from flask import  request,  jsonify, Blueprint
import bcrypt
import psycopg2

admin_route = Blueprint('admin_route',__name__)

Api For Register and Saving Password inside PostgreSQL

#Api For Register for storing hash password inside PostgresSQl database
@admin_route.route('/register', methods=['POST'])
def register():
if request.method == 'POST':
conn = psycopg2.connect(database="ambika_tvs", user="postgres", password="admin", host="localhost", port="5432")

# create a cursor
cur = conn.cursor()
data = request.get_json()
# converting password to array of bytes
password = data['password']
bytes = password.encode('utf-8')

# generating the salt
salt = bcrypt.gensalt()

# Hashing the password
hash = bcrypt.hashpw(bytes, salt)
stored_password = str(hash.decode('utf-8'))
# print(hash)
selectResult = cur.execute("SELECT * FROM admins where email=(%s) or username=(%s);", (data['email'], data['username']))
if selectResult != None:
selectResult = cur.fetchone()[0]
print('selectResult')
print(selectResult)
message = 'Record created successfully'
statusCode = 200
if selectResult !=None and selectResult != 0:
message = 'Record Already Exists in our database'
statusCode=409
else:
cur.execute("INSERT INTO admins (name, username, email, password) VALUES (%s, %s, %s, %s)", (data['name'], data['username'], data['email'], stored_password))
# commit the changes
conn.commit()

# close the cursor and connection
cur.close()
conn.close()
# return hash
return jsonify(message=message, statusCode=statusCode), statusCode

Api For Sign In and Comparing Hash Password with the hash String stored inside the PostgreSQL Database

#Api For SignIn and Comparing Hash Password with the hash String stored inside the PostgresSql Database
@admin_route.route('/admin/singin', methods=['POST'])
def adminSignIn():
if request.method == 'POST':
conn = psycopg2.connect(database="ambika_tvs", user="postgres", password="admin", host="localhost", port="5432")

# create a cursor
cur = conn.cursor()
data = request.get_json()
# converting password to array of bytes
userPassword = data['password']
selectResult = cur.execute("SELECT id, email, username, password FROM admins where email=(%s) or username=(%s);", (data['username'], data['username']))
selectResult = cur.fetchone()[3]
print('selectResult')
print(selectResult)
message = 'Record match successfully'
statusCode = 200
if selectResult != 0:
userBytes = userPassword.encode('utf-8')

# checking password
result = bcrypt.checkpw(userBytes, selectResult.encode('utf8'))
if result == False:
message = 'Invalid Username or Password'
statusCode=401
else:
message = 'Unauthorized'
statusCode=401
conn.commit()

# close the cursor and connection
cur.close()
conn.close()
# return hash
return jsonify(message=message, statusCode=statusCode), statusCode

Thank you for going through the article. If you are looking for any freelancer developer related to Html, css, React, React Native, Next.js, Node.js, GraphQl, Python, Flask, Panda. Please let me know. I will be glad to help you.
To tell us about your requirement please fill the form: https://docs.google.com/forms/d/1uh343ab8uwVhCpozi_etFyV67f6zVoIiMlrYKLwOgnE/prefill

--

--