Compare commits

..

No commits in common. "d8d3dc907b282ecb6178358efc8789888b3de857" and "62102667fc5f1f002114da2156598c2a64db650f" have entirely different histories.

4 changed files with 43 additions and 96 deletions

View File

@ -1,16 +0,0 @@
from sql import *
from sqlmodel import select
import hashlib
def hash_password(password: str, salt: int = None):
password = f"{password}{salt}"
return hashlib.sha256(password.encode()).hexdigest()
def get_user_by_email(email: str, session) -> User | None:
statement = select(User).where(User.email == email)
return session.exec(statement).first()
def get_user_by_id(id: str, session: SessionDep) -> User | None:
statement = select(User).where(User.id == id)
return session.exec(statement).first()

95
main.py
View File

@ -1,20 +1,43 @@
# Imports # Imports
from contextlib import asynccontextmanager from typing import Annotated
from fastapi import FastAPI, HTTPException
from functions import *
from sql import *
from fastapi import FastAPI, Depends, HTTPException, Query
from sqlmodel import Field, Session, SQLModel, create_engine, select
import hashlib
import random import random
# Create DB on startup
# noinspection PyUnusedLocal
@asynccontextmanager
async def lifespan(app: FastAPI):
create_db_and_tables()
yield # Code before the yield will run on startup, code after yield won't run until the program is over
# Initialize the FastAPI App # Initialize the FastAPI App
app = FastAPI(lifespan=lifespan) 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
email: str = Field(index=True)
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("/") @app.get("/")
def hello_world(): def hello_world():
@ -23,15 +46,17 @@ def hello_world():
@app.get("/hash/{password}") @app.get("/hash/{password}")
def hash(password: str): def hash(password: str):
salt = random.randint(00000, 99999) salt = random.randint(00000, 99999)
hashed = hash_password(password, salt) password = password + str(salt)
hashed = hashlib.sha256(password.encode()).hexdigest()
return {"hash": hashed, "salt": salt} return {"hash": hashed, "salt": salt}
@app.get("/verify/{password}/{hash}/{salt}") @app.get("/verify/{password}/{hash}/{salt}")
def verify(password: str, hash: str, salt: int): def verify(password: str, hash: str, salt: int):
if salt != 0: if salt != 0:
hashed = hash_password(password, salt) password = password + str(salt)
hashed = hashlib.sha256(password.encode()).hexdigest()
else: else:
hashed = hash_password(password, salt) hashed = hashlib.sha256(password.encode()).hexdigest()
if hashed == hash: if hashed == hash:
return {"message": "Password is correct", "correct": True} return {"message": "Password is correct", "correct": True}
@ -40,41 +65,5 @@ def verify(password: str, hash: str, salt: int):
@app.get("/hash/no-salt/{password}") @app.get("/hash/no-salt/{password}")
def no_salt(password: str): def no_salt(password: str):
hashed = hash_password(password) hashed = hashlib.sha256(password.encode()).hexdigest()
return {"hash": hashed, "salt": 0} return {"hash": hashed}
@app.post('/users/create')
async def create_user(user: User, session: SessionDep) -> User | dict[str, str]:
get_user = get_user_by_email(user.email, session)
if get_user is None:
user.password = hash_password(user.password, salt=random.randint(00000, 99999))
session.add(user)
session.commit()
session.refresh(user)
return user
return {"message": "User already created"}
@app.get("/users/{type}")
async def get_user(type: str, session: SessionDep) -> User:
user = get_user_by_id(type, session)
if user is None:
user = get_user_by_email(type, session)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
@app.delete("/users/{type}")
async def delete_user(type: str, session: SessionDep) -> User | dict[str, str | bool]:
user = get_user_by_id(type, session)
if user is None:
user = get_user_by_email(type, session)
if not user:
raise HTTPException(status_code=404, detail="User not found")
session.delete(user)
session.commit()
return {"message": "User deleted", "completed": True}

View File

@ -32,5 +32,6 @@ starlette==0.45.3
typer==0.15.1 typer==0.15.1
typing_extensions==4.12.2 typing_extensions==4.12.2
uvicorn==0.34.0 uvicorn==0.34.0
uvloop==0.21.0
watchfiles==1.0.4 watchfiles==1.0.4
websockets==15.0 websockets==15.0

27
sql.py
View File

@ -1,27 +0,0 @@
from typing import Annotated
from fastapi import Depends
from sqlmodel import Field, Session, SQLModel, create_engine
# Create the user table
class User(SQLModel, table=True):
id: int = Field(default=None, primary_key=True, index=True)
name: str
age: int
email: str = Field(index=True)
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)]