From ec714bf9f0eb846ccf6a79945f4436f6ff8a8ef9 Mon Sep 17 00:00:00 2001 From: Automated Action Date: Sat, 17 May 2025 16:53:52 +0000 Subject: [PATCH] Implement user authentication service with FastAPI and SQLite --- README.md | 166 ++++++++++++++++- alembic.ini | 102 +++++++++++ app/__init__.py | 0 app/api/__init__.py | 0 app/api/v1/__init__.py | 0 app/api/v1/endpoints/__init__.py | 0 app/api/v1/endpoints/auth.py | 173 ++++++++++++++++++ app/api/v1/endpoints/users.py | 124 +++++++++++++ app/api/v1/router.py | 7 + app/core/__init__.py | 0 app/core/config.py | 42 +++++ app/core/database.py | 22 +++ app/core/dependencies.py | 71 +++++++ app/core/security.py | 42 +++++ app/models/__init__.py | 5 + app/models/token.py | 15 ++ app/models/user.py | 18 ++ app/schemas/__init__.py | 18 ++ app/schemas/message.py | 26 +++ app/schemas/token.py | 20 ++ app/schemas/user.py | 39 ++++ app/services/__init__.py | 0 app/services/token.py | 88 +++++++++ app/services/user.py | 111 +++++++++++ app/utils/__init__.py | 0 main.py | 34 ++++ migrations/README | 35 ++++ migrations/env.py | 82 +++++++++ migrations/script.py.mako | 24 +++ .../versions/001_create_user_token_tables.py | 65 +++++++ requirements.txt | 11 ++ 31 files changed, 1338 insertions(+), 2 deletions(-) create mode 100644 alembic.ini create mode 100644 app/__init__.py create mode 100644 app/api/__init__.py create mode 100644 app/api/v1/__init__.py create mode 100644 app/api/v1/endpoints/__init__.py create mode 100644 app/api/v1/endpoints/auth.py create mode 100644 app/api/v1/endpoints/users.py create mode 100644 app/api/v1/router.py create mode 100644 app/core/__init__.py create mode 100644 app/core/config.py create mode 100644 app/core/database.py create mode 100644 app/core/dependencies.py create mode 100644 app/core/security.py create mode 100644 app/models/__init__.py create mode 100644 app/models/token.py create mode 100644 app/models/user.py create mode 100644 app/schemas/__init__.py create mode 100644 app/schemas/message.py create mode 100644 app/schemas/token.py create mode 100644 app/schemas/user.py create mode 100644 app/services/__init__.py create mode 100644 app/services/token.py create mode 100644 app/services/user.py create mode 100644 app/utils/__init__.py create mode 100644 main.py create mode 100644 migrations/README create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/001_create_user_token_tables.py create mode 100644 requirements.txt diff --git a/README.md b/README.md index e8acfba..8523fe7 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,165 @@ -# FastAPI Application +# User Authentication Service -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A FastAPI-based user authentication service with JWT token authentication, user management, and token refresh functionality. + +## Features + +- User registration and login +- JWT token-based authentication +- Token refresh mechanism +- User profile management +- Admin user management +- SQLite database with Alembic migrations + +## Technology Stack + +- **Framework**: FastAPI +- **Database**: SQLite with SQLAlchemy ORM +- **Migrations**: Alembic +- **Authentication**: JWT (JSON Web Tokens) +- **Password Hashing**: Bcrypt +- **Dependency Management**: pip + +## Getting Started + +### Prerequisites + +- Python 3.8+ +- pip (Python package manager) + +### Installation + +1. Clone the repository: + ```bash + git clone + cd userauthenticationservice-altocj + ``` + +2. Install dependencies: + ```bash + pip install -r requirements.txt + ``` + +3. Run database migrations: + ```bash + alembic upgrade head + ``` + +4. Start the development server: + ```bash + uvicorn main:app --reload + ``` + +The API will be available at http://localhost:8000. +API documentation is available at http://localhost:8000/docs or http://localhost:8000/redoc. + +## Project Structure + +``` +app/ +├── api/ +│ └── v1/ +│ ├── endpoints/ +│ │ ├── auth.py # Authentication routes +│ │ └── users.py # User management routes +│ └── router.py # API router configuration +├── core/ +│ ├── config.py # Application configuration +│ ├── database.py # Database connection setup +│ ├── dependencies.py # Dependency injection +│ └── security.py # Authentication utilities +├── models/ +│ ├── token.py # Token database model +│ └── user.py # User database model +├── schemas/ +│ ├── message.py # Response message schemas +│ ├── token.py # Token validation schemas +│ └── user.py # User validation schemas +├── services/ +│ ├── token.py # Token service functions +│ └── user.py # User service functions +└── utils/ # Utility functions +migrations/ # Alembic migration files +main.py # Application entry point +requirements.txt # Project dependencies +``` + +## Authentication Flow + +### Registration + +1. Client sends a POST request to `/api/v1/auth/register` with email, username, and password +2. Server validates the request data +3. If the user doesn't already exist, it creates a new user with a hashed password +4. Server returns an access token and a refresh token + +### Login + +1. Client sends a POST request to `/api/v1/auth/login` with username/email and password +2. Server authenticates the user +3. If successful, server returns an access token and a refresh token + +### Authentication + +1. Client includes the access token in the Authorization header for protected endpoints: + ``` + Authorization: Bearer {access_token} + ``` + +2. Server validates the token and identifies the user + +### Token Refresh + +1. When the access token expires, client sends a POST request to `/api/v1/auth/refresh` with the refresh token +2. Server validates the refresh token and issues a new access token and refresh token +3. The old refresh token is revoked + +### Logout + +1. Client sends a POST request to `/api/v1/auth/logout` with the refresh token +2. Server revokes the refresh token, invalidating the session + +### Logout All Sessions + +1. Client sends a POST request to `/api/v1/auth/logout-all` with a valid access token +2. Server revokes all refresh tokens for the user, invalidating all sessions + +## API Endpoints + +### Authentication + +- `POST /api/v1/auth/register` - Register a new user +- `POST /api/v1/auth/login` - Login with username/email and password +- `POST /api/v1/auth/refresh` - Refresh access token +- `POST /api/v1/auth/logout` - Logout (revoke refresh token) +- `POST /api/v1/auth/logout-all` - Logout from all devices + +### User Management + +- `GET /api/v1/users/me` - Get current user profile +- `PUT /api/v1/users/me` - Update current user profile +- `GET /api/v1/users` - Get all users (admin only) +- `POST /api/v1/users` - Create a new user (admin only) +- `GET /api/v1/users/{user_id}` - Get user by ID (admin or self) +- `PUT /api/v1/users/{user_id}` - Update user by ID (admin only) + +### Health Check + +- `GET /health` - Check API health status + +## Environment Variables + +The project uses `.env` file for configuration. Here's an example: + +``` +SECRET_KEY=your-secret-key +ACCESS_TOKEN_EXPIRE_MINUTES=1440 # 24 hours +BACKEND_CORS_ORIGINS=["http://localhost:3000"] +``` + +## Security Considerations + +- Passwords are hashed using bcrypt +- JWT tokens are signed with a secret key +- Refresh tokens are stored in the database and can be revoked +- Role-based access control for admin functions \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..98965b6 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,102 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = migrations + +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the python-dateutil library that can be +# installed by adding `alembic[tz]` to the pip requirements +# string value is passed to dateutil.tz.gettz() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the +# "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to migrations/versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "version_path_separator" below. +# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions + +# version path separator; As mentioned above, this is the character used to split +# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep. +# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas. +# Valid values for version_path_separator are: +# +# version_path_separator = : +# version_path_separator = ; +# version_path_separator = space +version_path_separator = os # Use os.pathsep. Default configuration used for new projects. + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +sqlalchemy.url = sqlite:////app/storage/db/db.sqlite + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/v1/__init__.py b/app/api/v1/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/v1/endpoints/__init__.py b/app/api/v1/endpoints/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/v1/endpoints/auth.py b/app/api/v1/endpoints/auth.py new file mode 100644 index 0000000..eb8e92c --- /dev/null +++ b/app/api/v1/endpoints/auth.py @@ -0,0 +1,173 @@ +from datetime import timedelta +from typing import Any + +from fastapi import APIRouter, Depends, HTTPException, status +from fastapi.security import OAuth2PasswordRequestForm +from sqlalchemy.orm import Session + +from app.core.config import settings +from app.core.database import get_db +from app.core.dependencies import get_current_active_user +from app.core.security import create_access_token +from app.models.user import User +from app.schemas.token import Token, TokenRefresh +from app.schemas.user import UserCreate +from app.services import token as token_service +from app.services import user as user_service + +router = APIRouter() + + +@router.post("/register", response_model=Token) +def register( + user_in: UserCreate, + db: Session = Depends(get_db), +) -> Any: + """ + Register a new user and return access token + """ + # Check if user with this email already exists + user = user_service.get_by_email(db, email=user_in.email) + if user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="A user with this email already exists", + ) + + # Check if user with this username already exists + user = user_service.get_by_username(db, username=user_in.username) + if user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="A user with this username already exists", + ) + + # Create new user + user = user_service.create(db, obj_in=user_in) + + # Create access token + access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) + access_token = create_access_token( + subject=user.id, expires_delta=access_token_expires + ) + + # Create refresh token + refresh_token_obj = token_service.create_refresh_token(db, user_id=user.id) + + return { + "access_token": access_token, + "token_type": "bearer", + "refresh_token": refresh_token_obj.token, + "expires_at": refresh_token_obj.expires_at, + } + + +@router.post("/login", response_model=Token) +def login( + db: Session = Depends(get_db), + form_data: OAuth2PasswordRequestForm = Depends(), +) -> Any: + """ + OAuth2 compatible token login, get an access token for future requests + """ + user = user_service.authenticate( + db, username_or_email=form_data.username, password=form_data.password + ) + if not user: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect username/email or password", + headers={"WWW-Authenticate": "Bearer"}, + ) + + if not user_service.is_active(user): + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Inactive user", + headers={"WWW-Authenticate": "Bearer"}, + ) + + # Create access token + access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) + access_token = create_access_token( + subject=user.id, expires_delta=access_token_expires + ) + + # Create refresh token + refresh_token_obj = token_service.create_refresh_token(db, user_id=user.id) + + return { + "access_token": access_token, + "token_type": "bearer", + "refresh_token": refresh_token_obj.token, + "expires_at": refresh_token_obj.expires_at, + } + + +@router.post("/refresh", response_model=Token) +def refresh_token( + token_in: TokenRefresh, + db: Session = Depends(get_db), +) -> Any: + """ + Refresh access token + """ + refresh_token = token_service.get_by_token(db, token=token_in.refresh_token) + if not refresh_token: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid refresh token", + headers={"WWW-Authenticate": "Bearer"}, + ) + + if not token_service.is_token_valid(refresh_token): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Refresh token expired or revoked", + headers={"WWW-Authenticate": "Bearer"}, + ) + + # Revoke the used refresh token + token_service.revoke_token(db, refresh_token) + + # Create new access token + access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) + access_token = create_access_token( + subject=refresh_token.user_id, expires_delta=access_token_expires + ) + + # Create new refresh token + new_refresh_token = token_service.create_refresh_token(db, user_id=refresh_token.user_id) + + return { + "access_token": access_token, + "token_type": "bearer", + "refresh_token": new_refresh_token.token, + "expires_at": new_refresh_token.expires_at, + } + + +@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT, response_model=None) +def logout( + token_in: TokenRefresh, + db: Session = Depends(get_db), +) -> None: + """ + Logout by revoking the refresh token + """ + refresh_token = token_service.get_by_token(db, token=token_in.refresh_token) + if refresh_token: + token_service.revoke_token(db, refresh_token) + return None + + +@router.post("/logout-all", status_code=status.HTTP_204_NO_CONTENT, response_model=None) +def logout_all( + current_user: User = Depends(get_current_active_user), + db: Session = Depends(get_db), +) -> None: + """ + Logout from all devices by revoking all refresh tokens + """ + token_service.revoke_all_user_tokens(db, user_id=current_user.id) + return None \ No newline at end of file diff --git a/app/api/v1/endpoints/users.py b/app/api/v1/endpoints/users.py new file mode 100644 index 0000000..24a888d --- /dev/null +++ b/app/api/v1/endpoints/users.py @@ -0,0 +1,124 @@ +from typing import Any, List + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app.core.database import get_db +from app.core.dependencies import ( + get_current_active_superuser, + get_current_active_user, +) +from app.models.user import User +from app.schemas.user import User as UserSchema +from app.schemas.user import UserCreate, UserUpdate +from app.services import user as user_service + +router = APIRouter() + + +@router.get("/me", response_model=UserSchema) +def read_user_me( + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Get current user + """ + return current_user + + +@router.put("/me", response_model=UserSchema) +def update_user_me( + *, + db: Session = Depends(get_db), + user_in: UserUpdate, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Update own user + """ + user = user_service.update(db, db_obj=current_user, obj_in=user_in) + return user + + +# Admin endpoints +@router.get("/", response_model=List[UserSchema]) +def read_users( + db: Session = Depends(get_db), + skip: int = 0, + limit: int = 100, + current_user: User = Depends(get_current_active_superuser), +) -> Any: + """ + Retrieve users. Only for superusers. + """ + users = user_service.get_multi(db, skip=skip, limit=limit) + return users + + +@router.post("/", response_model=UserSchema) +def create_user( + *, + db: Session = Depends(get_db), + user_in: UserCreate, + current_user: User = Depends(get_current_active_superuser), +) -> Any: + """ + Create new user. Only for superusers. + """ + user = user_service.get_by_email(db, email=user_in.email) + if user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="A user with this email already exists", + ) + + user = user_service.get_by_username(db, username=user_in.username) + if user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="A user with this username already exists", + ) + + user = user_service.create(db, obj_in=user_in) + return user + + +@router.get("/{user_id}", response_model=UserSchema) +def read_user_by_id( + user_id: int, + current_user: User = Depends(get_current_active_user), + db: Session = Depends(get_db), +) -> Any: + """ + Get a specific user by id + """ + user = user_service.get_by_id(db, user_id=user_id) + if user == current_user: + return user + if not user_service.is_superuser(current_user): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="The user doesn't have enough privileges", + ) + return user + + +@router.put("/{user_id}", response_model=UserSchema) +def update_user( + *, + db: Session = Depends(get_db), + user_id: int, + user_in: UserUpdate, + current_user: User = Depends(get_current_active_superuser), +) -> Any: + """ + Update a user. Only for superusers. + """ + user = user_service.get_by_id(db, user_id=user_id) + if not user: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="User not found", + ) + user = user_service.update(db, db_obj=user, obj_in=user_in) + return user \ No newline at end of file diff --git a/app/api/v1/router.py b/app/api/v1/router.py new file mode 100644 index 0000000..c960076 --- /dev/null +++ b/app/api/v1/router.py @@ -0,0 +1,7 @@ +from fastapi import APIRouter + +from app.api.v1.endpoints import auth, users + +api_router = APIRouter() +api_router.include_router(auth.router, prefix="/auth", tags=["authentication"]) +api_router.include_router(users.router, prefix="/users", tags=["users"]) \ No newline at end of file diff --git a/app/core/__init__.py b/app/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/core/config.py b/app/core/config.py new file mode 100644 index 0000000..7f2b8a8 --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,42 @@ +from typing import List, Union +from pathlib import Path +from pydantic import AnyHttpUrl, validator +from pydantic_settings import BaseSettings + +class Settings(BaseSettings): + API_V1_STR: str = "/api/v1" + PROJECT_NAME: str = "User Authentication Service" + PROJECT_DESCRIPTION: str = "API service for user authentication" + PROJECT_VERSION: str = "0.1.0" + + # Secret key for JWT token and other security mechanisms + SECRET_KEY: str = "YOUR_SUPER_SECRET_KEY_CHANGE_THIS_IN_PRODUCTION" + # 60 minutes * 24 hours * 8 days = 8 days in minutes + ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8 + + # CORS + BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = [] + + @validator("BACKEND_CORS_ORIGINS", pre=True) + def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]: + if isinstance(v, str) and not v.startswith("["): + return [i.strip() for i in v.split(",")] + elif isinstance(v, (list, str)): + return v + raise ValueError(v) + + # Database + DB_DIR: Path = Path("/app/storage/db") + SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite" + + # Token related + TOKEN_URL: str = f"{API_V1_STR}/auth/login" + + class Config: + case_sensitive = True + env_file = ".env" + +# Create the DB directory if it doesn't exist +Settings().DB_DIR.mkdir(parents=True, exist_ok=True) + +settings = Settings() \ No newline at end of file diff --git a/app/core/database.py b/app/core/database.py new file mode 100644 index 0000000..ebd475d --- /dev/null +++ b/app/core/database.py @@ -0,0 +1,22 @@ +from sqlalchemy import create_engine +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker + +from app.core.config import settings + +engine = create_engine( + settings.SQLALCHEMY_DATABASE_URL, + connect_args={"check_same_thread": False} # Only needed for SQLite +) + +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + +Base = declarative_base() + +# Dependency to get the database session +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() \ No newline at end of file diff --git a/app/core/dependencies.py b/app/core/dependencies.py new file mode 100644 index 0000000..ee3716b --- /dev/null +++ b/app/core/dependencies.py @@ -0,0 +1,71 @@ + +from fastapi import Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer +from jose import jwt +from pydantic import ValidationError +from sqlalchemy.orm import Session + +from app.core.config import settings +from app.core.database import get_db +from app.core.security import ALGORITHM +from app.models.user import User +from app.schemas.token import TokenPayload +from app.services import user as user_service + +# OAuth2 scheme for token authentication +oauth2_scheme = OAuth2PasswordBearer(tokenUrl=settings.TOKEN_URL) + + +def get_current_user( + db: Session = Depends(get_db), token: str = Depends(oauth2_scheme) +) -> User: + """ + Get current user based on JWT token + """ + try: + payload = jwt.decode( + token, settings.SECRET_KEY, algorithms=[ALGORITHM] + ) + token_data = TokenPayload(**payload) + except (jwt.JWTError, ValidationError): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) + + user = user_service.get_by_id(db, user_id=token_data.sub) + if not user: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="User not found" + ) + return user + + +def get_current_active_user( + current_user: User = Depends(get_current_user), +) -> User: + """ + Get current active user + """ + if not user_service.is_active(current_user): + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Inactive user" + ) + return current_user + + +def get_current_active_superuser( + current_user: User = Depends(get_current_active_user), +) -> User: + """ + Get current active superuser + """ + if not user_service.is_superuser(current_user): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="The user doesn't have enough privileges" + ) + return current_user \ No newline at end of file diff --git a/app/core/security.py b/app/core/security.py new file mode 100644 index 0000000..95d69f7 --- /dev/null +++ b/app/core/security.py @@ -0,0 +1,42 @@ +from datetime import datetime, timedelta +from typing import Any, Optional, Union + +from jose import jwt +from passlib.context import CryptContext + +from app.core.config import settings + +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + +ALGORITHM = "HS256" + + +def create_access_token( + subject: Union[str, Any], expires_delta: Optional[timedelta] = None +) -> str: + """ + Create JWT access token for the given subject + """ + if expires_delta: + expire = datetime.utcnow() + expires_delta + else: + expire = datetime.utcnow() + timedelta( + minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES + ) + to_encode = {"exp": expire, "sub": str(subject)} + encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=ALGORITHM) + return encoded_jwt + + +def verify_password(plain_password: str, hashed_password: str) -> bool: + """ + Verify if the plain password matches the hashed one + """ + return pwd_context.verify(plain_password, hashed_password) + + +def get_password_hash(password: str) -> str: + """ + Hash a password for storing + """ + return pwd_context.hash(password) \ No newline at end of file diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000..9044645 --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1,5 @@ +from app.models.user import User +from app.models.token import Token + +# Add all models here so they can be imported from app.models +__all__ = ["User", "Token"] \ No newline at end of file diff --git a/app/models/token.py b/app/models/token.py new file mode 100644 index 0000000..553795d --- /dev/null +++ b/app/models/token.py @@ -0,0 +1,15 @@ +from sqlalchemy import Column, ForeignKey, Integer, String, DateTime, Boolean +from sqlalchemy.sql import func + +from app.core.database import Base + + +class Token(Base): + __tablename__ = "tokens" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False) + token = Column(String, unique=True, index=True, nullable=False) + expires_at = Column(DateTime(timezone=True), nullable=False) + is_revoked = Column(Boolean, default=False) + created_at = Column(DateTime(timezone=True), server_default=func.now()) \ No newline at end of file diff --git a/app/models/user.py b/app/models/user.py new file mode 100644 index 0000000..a2fd899 --- /dev/null +++ b/app/models/user.py @@ -0,0 +1,18 @@ +from sqlalchemy import Boolean, Column, DateTime, Integer, String +from sqlalchemy.sql import func + +from app.core.database import Base + + +class User(Base): + __tablename__ = "users" + + id = Column(Integer, primary_key=True, index=True) + email = Column(String, unique=True, index=True, nullable=False) + username = Column(String, unique=True, index=True, nullable=False) + hashed_password = Column(String, nullable=False) + full_name = Column(String, nullable=True) + is_active = Column(Boolean, default=True) + is_superuser = Column(Boolean, default=False) + created_at = Column(DateTime(timezone=True), server_default=func.now()) + updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now()) \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..c8c14f3 --- /dev/null +++ b/app/schemas/__init__.py @@ -0,0 +1,18 @@ +from app.schemas.message import Message, HTTPValidationError, ResponseBase, ResponseData +from app.schemas.token import Token, TokenPayload, TokenRefresh +from app.schemas.user import User, UserCreate, UserInDB, UserUpdate + +# Add all schemas here so they can be imported from app.schemas +__all__ = [ + "User", + "UserCreate", + "UserInDB", + "UserUpdate", + "Token", + "TokenPayload", + "TokenRefresh", + "Message", + "HTTPValidationError", + "ResponseBase", + "ResponseData" +] \ No newline at end of file diff --git a/app/schemas/message.py b/app/schemas/message.py new file mode 100644 index 0000000..ba88cae --- /dev/null +++ b/app/schemas/message.py @@ -0,0 +1,26 @@ +from typing import Any, Dict, List, Optional, Union + +from pydantic import BaseModel + + +class Message(BaseModel): + detail: str + + +class ValidationError(BaseModel): + loc: List[str] + msg: str + type: str + + +class HTTPValidationError(BaseModel): + detail: List[ValidationError] + + +class ResponseBase(BaseModel): + success: bool + message: str + + +class ResponseData(ResponseBase): + data: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None \ No newline at end of file diff --git a/app/schemas/token.py b/app/schemas/token.py new file mode 100644 index 0000000..45fe13d --- /dev/null +++ b/app/schemas/token.py @@ -0,0 +1,20 @@ +from datetime import datetime +from typing import Optional + +from pydantic import BaseModel + + +class Token(BaseModel): + access_token: str + token_type: str = "bearer" + refresh_token: Optional[str] = None + expires_at: Optional[datetime] = None + + +class TokenPayload(BaseModel): + sub: Optional[int] = None + exp: Optional[datetime] = None + + +class TokenRefresh(BaseModel): + refresh_token: str \ No newline at end of file diff --git a/app/schemas/user.py b/app/schemas/user.py new file mode 100644 index 0000000..721046d --- /dev/null +++ b/app/schemas/user.py @@ -0,0 +1,39 @@ +from datetime import datetime +from typing import Optional + +from pydantic import BaseModel, EmailStr + + +class UserBase(BaseModel): + email: Optional[EmailStr] = None + username: Optional[str] = None + is_active: Optional[bool] = True + is_superuser: bool = False + full_name: Optional[str] = None + + +class UserCreate(UserBase): + email: EmailStr + username: str + password: str + + +class UserUpdate(UserBase): + password: Optional[str] = None + + +class UserInDBBase(UserBase): + id: Optional[int] = None + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + + class Config: + orm_mode = True + + +class User(UserInDBBase): + pass + + +class UserInDB(UserInDBBase): + hashed_password: str \ No newline at end of file diff --git a/app/services/__init__.py b/app/services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/services/token.py b/app/services/token.py new file mode 100644 index 0000000..0986432 --- /dev/null +++ b/app/services/token.py @@ -0,0 +1,88 @@ +import secrets +from datetime import datetime, timedelta +from typing import Optional + +from jose import jwt, JWTError +from sqlalchemy.orm import Session + +from app.core.config import settings +from app.core.security import ALGORITHM +from app.models.token import Token + + +def create_refresh_token( + db: Session, *, user_id: int, expires_delta: Optional[timedelta] = None +) -> Token: + """ + Create a refresh token in the database + """ + if expires_delta: + expire = datetime.utcnow() + expires_delta + else: + expire = datetime.utcnow() + timedelta(days=30) # 30 days default + + # Generate a secure random token + token_value = secrets.token_urlsafe(64) + + # Create token in DB + db_token = Token( + user_id=user_id, + token=token_value, + expires_at=expire, + is_revoked=False + ) + db.add(db_token) + db.commit() + db.refresh(db_token) + + return db_token + + +def get_by_token(db: Session, token: str) -> Optional[Token]: + """ + Get a token by its value + """ + return db.query(Token).filter(Token.token == token).first() + + +def is_token_valid(token: Token) -> bool: + """ + Check if a token is valid (not expired and not revoked) + """ + now = datetime.utcnow() + return token.expires_at > now and not token.is_revoked + + +def revoke_token(db: Session, token: Token) -> Token: + """ + Revoke a token + """ + token.is_revoked = True + db.add(token) + db.commit() + db.refresh(token) + return token + + +def revoke_all_user_tokens(db: Session, user_id: int) -> None: + """ + Revoke all tokens for a user + """ + tokens = db.query(Token).filter(Token.user_id == user_id).all() + for token in tokens: + token.is_revoked = True + + db.commit() + + +def decode_token(token: str) -> Optional[dict]: + """ + Decode a JWT token + """ + try: + payload = jwt.decode( + token, settings.SECRET_KEY, algorithms=[ALGORITHM] + ) + return payload + except JWTError: + return None \ No newline at end of file diff --git a/app/services/user.py b/app/services/user.py new file mode 100644 index 0000000..86b19ad --- /dev/null +++ b/app/services/user.py @@ -0,0 +1,111 @@ +from typing import Optional, List, Dict, Any, Union + +from sqlalchemy.orm import Session + +from app.core.security import get_password_hash, verify_password +from app.models.user import User +from app.schemas.user import UserCreate, UserUpdate + + +def get_by_id(db: Session, user_id: int) -> Optional[User]: + """ + Get a user by ID + """ + return db.query(User).filter(User.id == user_id).first() + + +def get_by_email(db: Session, email: str) -> Optional[User]: + """ + Get a user by email + """ + return db.query(User).filter(User.email == email).first() + + +def get_by_username(db: Session, username: str) -> Optional[User]: + """ + Get a user by username + """ + return db.query(User).filter(User.username == username).first() + + +def get_multi( + db: Session, *, skip: int = 0, limit: int = 100 +) -> List[User]: + """ + Get multiple users with pagination + """ + return db.query(User).offset(skip).limit(limit).all() + + +def create(db: Session, *, obj_in: UserCreate) -> User: + """ + Create a new user + """ + db_obj = User( + email=obj_in.email, + username=obj_in.username, + hashed_password=get_password_hash(obj_in.password), + full_name=obj_in.full_name, + is_active=obj_in.is_active, + is_superuser=obj_in.is_superuser, + ) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + +def update( + db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]] +) -> User: + """ + Update a user + """ + if isinstance(obj_in, dict): + update_data = obj_in + else: + update_data = obj_in.dict(exclude_unset=True) + + if "password" in update_data and update_data["password"]: + hashed_password = get_password_hash(update_data["password"]) + del update_data["password"] + update_data["hashed_password"] = hashed_password + + for field in update_data: + if field in update_data: + setattr(db_obj, field, update_data[field]) + + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + +def authenticate( + db: Session, *, username_or_email: str, password: str +) -> Optional[User]: + """ + Authenticate a user by username/email and password + """ + user = get_by_username(db, username=username_or_email) + if not user: + user = get_by_email(db, email=username_or_email) + if not user: + return None + if not verify_password(password, user.hashed_password): + return None + return user + + +def is_active(user: User) -> bool: + """ + Check if user is active + """ + return user.is_active + + +def is_superuser(user: User) -> bool: + """ + Check if user is superuser + """ + return user.is_superuser \ No newline at end of file diff --git a/app/utils/__init__.py b/app/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/main.py b/main.py new file mode 100644 index 0000000..ee9d08e --- /dev/null +++ b/main.py @@ -0,0 +1,34 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from app.api.v1.router import api_router +from app.core.config import settings + +app = FastAPI( + title=settings.PROJECT_NAME, + description=settings.PROJECT_DESCRIPTION, + version=settings.PROJECT_VERSION, + openapi_url=f"{settings.API_V1_STR}/openapi.json", + docs_url="/docs", + redoc_url="/redoc", +) + +# Set all CORS enabled origins +if settings.BACKEND_CORS_ORIGINS: + app.add_middleware( + CORSMiddleware, + allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + ) + +app.include_router(api_router, prefix=settings.API_V1_STR) + +# Health check endpoint +@app.get("/health", status_code=200) +def health_check(): + return {"status": "healthy"} + +if __name__ == "__main__": + import uvicorn + uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..37a25e7 --- /dev/null +++ b/migrations/README @@ -0,0 +1,35 @@ +Generic single-database configuration with Alembic. + +For more information on Alembic, see: +https://alembic.sqlalchemy.org/en/latest/ + +To run migrations: +1. Make sure you have alembic installed: + ``` + pip install alembic + ``` + +2. Run the upgrade to the latest version: + ``` + alembic upgrade head + ``` + +3. To create a new migration: + ``` + alembic revision -m "description of changes" + ``` + +4. To downgrade: + ``` + alembic downgrade -1 + ``` + +5. To get current migration version: + ``` + alembic current + ``` + +6. To see migration history: + ``` + alembic history + ``` \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..98a5563 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,82 @@ +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +# Import models for Alembic +from app.core.database import Base + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +target_metadata = Base.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + connectable = engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + is_sqlite = connection.dialect.name == 'sqlite' + context.configure( + connection=connection, + target_metadata=target_metadata, + render_as_batch=is_sqlite, # Enable batch mode for SQLite + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() \ No newline at end of file diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..37d0cac --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} \ No newline at end of file diff --git a/migrations/versions/001_create_user_token_tables.py b/migrations/versions/001_create_user_token_tables.py new file mode 100644 index 0000000..664a5a0 --- /dev/null +++ b/migrations/versions/001_create_user_token_tables.py @@ -0,0 +1,65 @@ +"""create user token tables + +Revision ID: 001 +Revises: +Create Date: 2023-10-10 + +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.sql import func + + +# revision identifiers, used by Alembic. +revision = '001' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # Create users table + op.create_table( + 'users', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('email', sa.String(), nullable=False), + sa.Column('username', sa.String(), nullable=False), + sa.Column('hashed_password', sa.String(), nullable=False), + sa.Column('full_name', sa.String(), nullable=True), + sa.Column('is_active', sa.Boolean(), default=True), + sa.Column('is_superuser', sa.Boolean(), default=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=func.now()), + sa.Column('updated_at', sa.DateTime(timezone=True), server_default=func.now(), onupdate=func.now()), + sa.PrimaryKeyConstraint('id') + ) + + op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False) + op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True) + op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True) + + # Create tokens table + op.create_table( + 'tokens', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('token', sa.String(), nullable=False), + sa.Column('expires_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('is_revoked', sa.Boolean(), default=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=func.now()), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + + op.create_index(op.f('ix_tokens_id'), 'tokens', ['id'], unique=False) + op.create_index(op.f('ix_tokens_token'), 'tokens', ['token'], unique=True) + + +def downgrade() -> None: + op.drop_index(op.f('ix_tokens_token'), table_name='tokens') + op.drop_index(op.f('ix_tokens_id'), table_name='tokens') + op.drop_table('tokens') + + op.drop_index(op.f('ix_users_username'), table_name='users') + op.drop_index(op.f('ix_users_email'), table_name='users') + op.drop_index(op.f('ix_users_id'), table_name='users') + op.drop_table('users') \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..fa4dfae --- /dev/null +++ b/requirements.txt @@ -0,0 +1,11 @@ +fastapi==0.103.1 +uvicorn==0.23.2 +sqlalchemy==2.0.20 +alembic==1.12.0 +pydantic==2.3.0 +pydantic-settings==2.0.3 +passlib==1.7.4 +python-jose==3.3.0 +python-multipart==0.0.6 +bcrypt==4.0.1 +ruff==0.0.290 \ No newline at end of file