How to use hashed password in python

1) Install passlib  using pip command

pip install "passlib[bcrypt]"  
or 
py -m pip install "passlib[bcrypt]"

2) To check passlib install or not use below command

"pip freeze"
 or 
"py -m pip freeze"

3) Import Passlib in main.py

from passlib.context import CryptContext

4) Now define passlib hashing algorithm in main.py

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

5) Now inside user registration function use above algorithm

  #hash  the password - user.password
    hashed_password = pwd_context.hash(user.password)
    user.password = hashed_password

6) Run API using Postman and check Database

Complete Code

databse.py

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# SQLALCHEMY_DATABASE_URL = 'postgresql://<username>:<password>@<ip-address/hostname>/<database_name>'
SQLALCHEMY_DATABASE_URL = 'postgresql://postgres:123456789@localhost/fastapi_ORM_DB'

engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

schemas.py

from pydantic import BaseModel, EmailStr
from datetime import datetime


class UserCreate(BaseModel):
    email:EmailStr
    password:str

class UserOut(BaseModel):
    id: int
    email: EmailStr
    created_at: datetime

    class config:
        orm_mode = True

models.py

# from datetime import datetime
from sqlalchemy import Column, Integer, String, Boolean, TIMESTAMP, text
from sqlalchemy.sql.expression import null
from .database import Base
    
class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, nullable=False)
    email = Column(String, nullable=False, unique=True)
    password = Column(String, nullable=False)
    created_at = Column(TIMESTAMP(timezone=True), nullable=False, server_default=text('now()'))


main.py

from typing import Optional
from fastapi import FastAPI, Response, status, HTTPException, Depends
from fastapi.params import Body
from pydantic import BaseModel
from passlib.context import CryptContext
from random import randrange
import psycopg2
from psycopg2.extras import RealDictCursor
import time
from sqlalchemy.orm import Session
from .import models, schemas
from .database import engine, SessionLocal, get_db

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
models.Base.metadata.create_all(bind=engine)

app = FastAPI()

#Create User 

@app.post("/users", status_code=status.HTTP_201_CREATED, response_model=schemas.UserOut)
async def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):

    #hash  the password - user.password
    hashed_password = pwd_context.hash(user.password)
    user.password = hashed_password

    new_user = models.User(**user.dict())
    db.add(new_user)
    db.commit()
    db.refresh(new_user)

    return new_user


OR

We can extract hashing code and create new function

a) Create new file eg: utills.py

put your passlib and hash password algo in utill.py and create new password

from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

#create function for hash password
def hashPassword(password: str):
    return pwd_context.hash(password);

b) Import util file in main.py

from .import utils

c) Call hasspassword function to util file

 hashed_password = utils.hashPassword(user.password)

utils.py

from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

#create function for hash password
def hashPassword(password: str):
    return pwd_context.hash(password);

main.py

from typing import Optional
from fastapi import FastAPI, Response, status, HTTPException, Depends
from fastapi.params import Body
from pydantic import BaseModel
# from passlib.context import CryptContext
from random import randrange
import psycopg2
from psycopg2.extras import RealDictCursor
import time
from sqlalchemy.orm import Session
from .import models, schemas, utils
from .database import engine, SessionLocal, get_db

# pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
models.Base.metadata.create_all(bind=engine)

app = FastAPI()

#Create User 
@app.post("/users", status_code=status.HTTP_201_CREATED, response_model=schemas.UserOut)
async def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):

    #hash  the password - user.password
    # hashed_password = pwd_context.hash(user.password)
     hashed_password = utils.hashPassword(user.password)
     user.password = hashed_password

     new_user = models.User(**user.dict())
     db.add(new_user)
     db.commit()
     db.refresh(new_user)

     return new_user
  

Happy Learning 🙂

One thought on “How to use hashed password in python

  • September 15, 2024 at 6:41 pm
    Permalink

    Highly energetic post, I loved that bit.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *