mirror of
https://github.com/Bunsly/JobSpy.git
synced 2026-03-05 03:54:31 -08:00
feat(users): add register route
This commit is contained in:
8
api/auth/__init__.py
Normal file
8
api/auth/__init__.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from api.auth.token import router as token_router
|
||||
from api.auth.register import router as register_router
|
||||
|
||||
router = APIRouter(prefix="/auth")
|
||||
router.include_router(token_router)
|
||||
router.include_router(register_router)
|
||||
50
api/auth/auth_utils.py
Normal file
50
api/auth/auth_utils.py
Normal file
@@ -0,0 +1,50 @@
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from jose import jwt, JWTError
|
||||
from fastapi import HTTPException, status, Depends
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
|
||||
from settings import *
|
||||
from api.core.users import TokenData
|
||||
from api.auth.db_utils import UserInDB, get_user
|
||||
|
||||
load_dotenv()
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/token")
|
||||
|
||||
|
||||
def create_access_token(data: dict):
|
||||
print(JWT_SECRET_KEY)
|
||||
to_encode = data.copy()
|
||||
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
to_encode.update({"exp": expire})
|
||||
encoded_jwt = jwt.encode(to_encode, JWT_SECRET_KEY, algorithm=ALGORITHM)
|
||||
return encoded_jwt
|
||||
|
||||
|
||||
async def get_current_user(token: str = Depends(oauth2_scheme)):
|
||||
credential_exception = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
try:
|
||||
payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=[ALGORITHM])
|
||||
username: str = payload.get("sub")
|
||||
if username is None:
|
||||
raise credential_exception
|
||||
token_data = TokenData(username=username)
|
||||
except JWTError:
|
||||
raise credential_exception
|
||||
|
||||
current_user = get_user(token_data.username)
|
||||
if current_user is None:
|
||||
raise credential_exception
|
||||
return current_user
|
||||
|
||||
|
||||
async def get_active_current_user(current_user: UserInDB = Depends(get_current_user)):
|
||||
if current_user.disabled:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail="Inactive user."
|
||||
)
|
||||
return current_user
|
||||
53
api/auth/db_utils.py
Normal file
53
api/auth/db_utils.py
Normal file
@@ -0,0 +1,53 @@
|
||||
from passlib.context import CryptContext
|
||||
from supabase_py import create_client, Client
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
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)
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def get_user(username: str):
|
||||
result = supabase.table("users").select().eq("username", username).execute()
|
||||
|
||||
if "error" in result and result["error"]:
|
||||
print(f"Error: {result['error']['message']}")
|
||||
return None
|
||||
else:
|
||||
if result["data"]:
|
||||
user_data = result["data"][0]
|
||||
return UserInDB(**user_data)
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
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
|
||||
28
api/auth/register/__init__.py
Normal file
28
api/auth/register/__init__.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from api.core.users import UserCreate, UserInDB
|
||||
from api.auth.db_utils import get_user, get_password_hash, create_user
|
||||
|
||||
router = APIRouter(prefix="/register", tags=["register"])
|
||||
|
||||
|
||||
@router.post("/")
|
||||
async def register_new_user(user: UserCreate):
|
||||
existing_user = get_user(user.username)
|
||||
if existing_user is not None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Username already exists",
|
||||
)
|
||||
|
||||
hashed_password = get_password_hash(user.password)
|
||||
print(f"Hashed password: {hashed_password}")
|
||||
user_create = UserInDB(
|
||||
username=user.username,
|
||||
email=user.email,
|
||||
full_name=user.full_name,
|
||||
hashed_password=hashed_password,
|
||||
disabled=False,
|
||||
)
|
||||
create_user(user_create)
|
||||
|
||||
return {"detail": "User created successfully"}
|
||||
22
api/auth/token/__init__.py
Normal file
22
api/auth/token/__init__.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
|
||||
from api.core.users import Token
|
||||
from api.auth.db_utils import authenticate_user
|
||||
from api.auth.auth_utils import create_access_token
|
||||
|
||||
router = APIRouter(prefix="/token", tags=["token"])
|
||||
|
||||
|
||||
@router.post("/", response_model=Token)
|
||||
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
|
||||
user = authenticate_user(form_data.username, form_data.password)
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect username or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
access_token = create_access_token(data={"sub": user.username})
|
||||
return {"access_token": access_token, "token_type": "bearer"}
|
||||
Reference in New Issue
Block a user