JobSpy/api/auth/db_utils.py

54 lines
1.5 KiB
Python
Raw Normal View History

2023-07-09 13:15:39 -07:00
from passlib.context import CryptContext
from supabase_py import create_client, Client
2023-07-09 16:42:44 -07:00
from fastapi import HTTPException, status
2023-07-09 13:15:39 -07:00
from api.core.users import UserInDB
from settings import SUPABASE_URL, SUPABASE_KEY
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
2023-07-09 16:42:44 -07:00
def create_user(user_create: UserInDB):
result = supabase.table("users").insert(user_create.dict()).execute()
print(f"Insert result: {result}")
if "error" in result and result["error"]:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"User could not be created due to {result['error']['message']}",
)
return result
2023-07-09 13:15:39 -07:00
def get_user(username: str):
2023-07-09 16:42:44 -07:00
result = supabase.table("users").select().eq("username", username).execute()
2023-07-09 13:15:39 -07:00
2023-07-09 16:42:44 -07:00
if "error" in result and result["error"]:
2023-07-09 13:15:39 -07:00
print(f"Error: {result['error']['message']}")
return None
else:
2023-07-09 16:42:44 -07:00
if result["data"]:
user_data = result["data"][0]
2023-07-09 13:15:39 -07:00
return UserInDB(**user_data)
else:
return None
2023-07-09 16:42:44 -07:00
2023-07-09 13:15:39 -07:00
def verify_password(password: str, hashed_password: str):
return pwd_context.verify(password, hashed_password)
def get_password_hash(password):
return pwd_context.hash(password)
def authenticate_user(username: str, password: str):
user = get_user(username)
if not user:
return False
if not verify_password(password, user.hashed_password):
return False
return user