Spaces:
Sleeping
Sleeping
Upload auth.py
Browse files
auth.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, HTTPException, status
|
| 2 |
+
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
| 3 |
+
from jose import jwt, JWTError
|
| 4 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 5 |
+
from sqlalchemy.future import select
|
| 6 |
+
import uuid
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
|
| 9 |
+
from database.session import get_db
|
| 10 |
+
from database.models import User
|
| 11 |
+
from schemas import UserCreate, User as UserSchema, Token, UserLogin
|
| 12 |
+
from auth_utils import get_password_hash, verify_password, create_access_token, SECRET_KEY, ALGORITHM
|
| 13 |
+
|
| 14 |
+
router = APIRouter(prefix="/auth", tags=["Authentication"])
|
| 15 |
+
|
| 16 |
+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/login")
|
| 17 |
+
|
| 18 |
+
async def get_current_user(
|
| 19 |
+
token: str = Depends(oauth2_scheme),
|
| 20 |
+
db: AsyncSession = Depends(get_db)
|
| 21 |
+
) -> User:
|
| 22 |
+
credentials_exception = HTTPException(
|
| 23 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 24 |
+
detail="Could not validate credentials",
|
| 25 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 26 |
+
)
|
| 27 |
+
try:
|
| 28 |
+
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
| 29 |
+
user_id: str = payload.get("sub")
|
| 30 |
+
if user_id is None:
|
| 31 |
+
raise credentials_exception
|
| 32 |
+
except JWTError:
|
| 33 |
+
raise credentials_exception
|
| 34 |
+
|
| 35 |
+
result = await db.execute(select(User).where(User.id == uuid.UUID(user_id)))
|
| 36 |
+
user = result.scalars().first()
|
| 37 |
+
if user is None:
|
| 38 |
+
raise credentials_exception
|
| 39 |
+
if not user.is_active:
|
| 40 |
+
raise HTTPException(status_code=400, detail="Inactive user")
|
| 41 |
+
return user
|
| 42 |
+
|
| 43 |
+
@router.post("/register", response_model=UserSchema, status_code=status.HTTP_201_CREATED)
|
| 44 |
+
async def register(user_in: UserCreate, db: AsyncSession = Depends(get_db)):
|
| 45 |
+
# Check if user exists
|
| 46 |
+
result = await db.execute(select(User).where(User.email == user_in.email))
|
| 47 |
+
if result.scalars().first():
|
| 48 |
+
raise HTTPException(
|
| 49 |
+
status_code=400,
|
| 50 |
+
detail="User with this email already exists"
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
result = await db.execute(select(User).where(User.username == user_in.username))
|
| 54 |
+
if result.scalars().first():
|
| 55 |
+
raise HTTPException(
|
| 56 |
+
status_code=400,
|
| 57 |
+
detail="User with this username already exists"
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
# Create user
|
| 61 |
+
db_user = User(
|
| 62 |
+
email=user_in.email,
|
| 63 |
+
username=user_in.username,
|
| 64 |
+
name=user_in.name,
|
| 65 |
+
password_hash=get_password_hash(user_in.password),
|
| 66 |
+
role="USER",
|
| 67 |
+
status="active",
|
| 68 |
+
balance=0.0000,
|
| 69 |
+
spent=0.0000
|
| 70 |
+
)
|
| 71 |
+
db.add(db_user)
|
| 72 |
+
await db.commit()
|
| 73 |
+
await db.refresh(db_user)
|
| 74 |
+
return db_user
|
| 75 |
+
|
| 76 |
+
@router.post("/login", response_model=Token)
|
| 77 |
+
async def login(user_in: UserLogin, db: AsyncSession = Depends(get_db)):
|
| 78 |
+
result = await db.execute(select(User).where(User.email == user_in.email))
|
| 79 |
+
user = result.scalars().first()
|
| 80 |
+
|
| 81 |
+
if not user or not verify_password(user_in.password, user.password_hash):
|
| 82 |
+
raise HTTPException(
|
| 83 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 84 |
+
detail="Incorrect email or password",
|
| 85 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
if not user.is_active:
|
| 89 |
+
raise HTTPException(status_code=400, detail="Inactive user")
|
| 90 |
+
|
| 91 |
+
access_token = create_access_token(subject=user.id)
|
| 92 |
+
return {"access_token": access_token, "token_type": "bearer"}
|
| 93 |
+
|
| 94 |
+
@router.post("/token", response_model=Token)
|
| 95 |
+
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: AsyncSession = Depends(get_db)):
|
| 96 |
+
# Supports standard OAuth2 form login (username/password)
|
| 97 |
+
result = await db.execute(select(User).where(User.username == form_data.username))
|
| 98 |
+
user = result.scalars().first()
|
| 99 |
+
|
| 100 |
+
if not user or not verify_password(form_data.password, user.password_hash):
|
| 101 |
+
# Fallback to checking by email if username check failed
|
| 102 |
+
result = await db.execute(select(User).where(User.email == form_data.username))
|
| 103 |
+
user = result.scalars().first()
|
| 104 |
+
if not user or not verify_password(form_data.password, user.password_hash):
|
| 105 |
+
raise HTTPException(
|
| 106 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 107 |
+
detail="Incorrect username or password",
|
| 108 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
access_token = create_access_token(subject=user.id)
|
| 112 |
+
return {"access_token": access_token, "token_type": "bearer"}
|
| 113 |
+
|
| 114 |
+
@router.get("/me", response_model=UserSchema)
|
| 115 |
+
async def read_users_me(current_user: User = Depends(get_current_user)):
|
| 116 |
+
return current_user
|