Password-Hash-API/main.py
2025-02-21 13:29:16 -05:00

69 lines
1.8 KiB
Python

# Imports
from typing import Annotated
from fastapi import FastAPI, Depends, HTTPException, Query
from sqlmodel import Field, Session, SQLModel, create_engine, select
import hashlib
import random
# Initialize the FastAPI App
app = FastAPI()
# Create the user table
class User(SQLModel, table=True):
id: int = Field(default=None, primary_key=True)
name: str = Field(index=True)
age: int
password: str
# SQLModel stuff
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
connect_args = {"check_same_thread": False}
engine = create_engine(sqlite_url, connect_args=connect_args)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def get_session():
with Session(engine) as session:
yield session
SessionDep = Annotated[Session, Depends(get_session)]
@app.on_event("startup")
def on_startup():
create_db_and_tables()
@app.get("/")
def hello_world():
return {"message": "Hello World!"}
@app.get("/hash/{password}")
def hash(password: str):
salt = random.randint(00000, 99999)
password = password + str(salt)
hashed = hashlib.sha256(password.encode()).hexdigest()
return {"hash": hashed, "salt": salt}
@app.get("/verify/{password}/{hash}/{salt}")
def verify(password: str, hash: str, salt: int):
if salt != 0:
password = password + str(salt)
hashed = hashlib.sha256(password.encode()).hexdigest()
else:
hashed = hashlib.sha256(password.encode()).hexdigest()
if hashed == hash:
return {"message": "Password is correct", "correct": True}
return {"message": "Password is incorrect", "correct": False}
@app.get("/hash/no-salt/{password}")
def no_salt(password: str):
hashed = hashlib.sha256(password.encode()).hexdigest()
return {"hash": hashed}