feat: add user and authentication API endpoints
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, status
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_db
|
||||
from app.api.users import user_to_response
|
||||
from app.services.auth_service import (
|
||||
AuthService,
|
||||
InvalidCredentialsError,
|
||||
InvalidSessionError,
|
||||
)
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/auth", tags=["Authentication"])
|
||||
|
||||
basic_security = HTTPBasic(auto_error=False)
|
||||
|
||||
|
||||
@router.post("/sessions", status_code=status.HTTP_201_CREATED)
|
||||
def create_session(
|
||||
credentials: HTTPBasicCredentials = Depends(basic_security),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
if credentials is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Basic authentication required",
|
||||
headers={
|
||||
"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
result = AuthService(db).create_session(
|
||||
username=credentials.username,
|
||||
password=credentials.password,
|
||||
)
|
||||
|
||||
return {
|
||||
"token": result["token"],
|
||||
"token_type": result["token_type"],
|
||||
"expires_at": result["expires_at"],
|
||||
"user": user_to_response(result["user"]),
|
||||
}
|
||||
|
||||
except InvalidCredentialsError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid username or password",
|
||||
headers={
|
||||
"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'
|
||||
},
|
||||
) from None
|
||||
|
||||
|
||||
@router.delete("/sessions/current", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_current_session(
|
||||
authorization: str | None = Header(default=None),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Bearer token required",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
token = authorization[7:].strip()
|
||||
|
||||
if not token:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Bearer token required",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
try:
|
||||
AuthService(db).delete_session(token)
|
||||
except InvalidSessionError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired session",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
) from None
|
||||
@@ -0,0 +1,46 @@
|
||||
from typing import Generator
|
||||
|
||||
from fastapi import Depends, Header, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db.session import SessionLocal
|
||||
from app.db.models import User
|
||||
from app.services.auth_service import AuthService, InvalidSessionError
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def get_current_user(
|
||||
authorization: str | None = Header(default=None),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Bearer token required",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
token = authorization[7:].strip()
|
||||
|
||||
if not token:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Bearer token required",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
try:
|
||||
return AuthService(db).authenticate(token)
|
||||
except InvalidSessionError:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Invalid or expired session",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
) from None
|
||||
@@ -0,0 +1,55 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_db, get_current_user
|
||||
from app.db.models import User as UserModel
|
||||
from app.models import CreateUser, User
|
||||
from app.services.user_service import (
|
||||
UserService,
|
||||
UsernameAlreadyExistsError,
|
||||
)
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/users", tags=["Users"])
|
||||
|
||||
|
||||
def user_to_response(user: UserModel) -> User:
|
||||
return User(
|
||||
id=str(user.id),
|
||||
username=user.username,
|
||||
display_name=user.display_name,
|
||||
created_at=user.created_at,
|
||||
)
|
||||
|
||||
|
||||
@router.post("", response_model=User, status_code=status.HTTP_201_CREATED)
|
||||
def register_user(
|
||||
body: CreateUser,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
user = UserService(db).register(
|
||||
username=body.username,
|
||||
display_name=body.display_name,
|
||||
password=body.password,
|
||||
)
|
||||
return user_to_response(user)
|
||||
|
||||
except UsernameAlreadyExistsError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Username already exists",
|
||||
) from None
|
||||
|
||||
except ValueError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=str(exc),
|
||||
) from None
|
||||
|
||||
|
||||
@router.get("/me", response_model=User)
|
||||
def get_me(
|
||||
current_user: UserModel = Depends(get_current_user),
|
||||
):
|
||||
return user_to_response(current_user)
|
||||
Reference in New Issue
Block a user