
- Set up FastAPI project structure with main.py and requirements.txt - Create User model with SQLAlchemy and SQLite database - Implement JWT token-based authentication system - Add password hashing with bcrypt - Create auth endpoints: register, login, and protected /me route - Set up Alembic for database migrations - Add health check endpoint with database status - Configure CORS to allow all origins - Update README with setup instructions and environment variables
38 lines
1.2 KiB
Python
38 lines
1.2 KiB
Python
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
from sqlalchemy.orm import Session
|
|
from app.db.session import get_db
|
|
from app.models.user import User
|
|
from app.core.security import verify_token
|
|
|
|
security = HTTPBearer()
|
|
|
|
def get_current_user(
|
|
credentials: HTTPAuthorizationCredentials = Depends(security),
|
|
db: Session = Depends(get_db)
|
|
) -> User:
|
|
token = credentials.credentials
|
|
email = verify_token(token)
|
|
|
|
if email is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
user = db.query(User).filter(User.email == email).first()
|
|
if user is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
if not user.is_active:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Inactive user"
|
|
)
|
|
|
|
return user |