diff --git a/README.md b/README.md index e8acfba..c0c9f05 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,122 @@ -# FastAPI Application +# User Authentication Service -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A professional and reliable user authentication service built with FastAPI and SQLite. This service provides a secure authentication flow with JWT tokens, including refresh token functionality. + +## Features + +- User registration and login +- JWT-based authentication with access and refresh tokens +- Password hashing with bcrypt +- User profile management +- Role-based access control (superuser and regular user) +- Health check endpoint +- Alembic migrations +- SQLite database + +## Project Structure + +``` +. +├── alembic.ini +├── app +│ ├── api +│ │ ├── deps.py +│ │ ├── endpoints +│ │ │ ├── auth.py +│ │ │ └── users.py +│ │ └── api.py +│ ├── core +│ │ ├── config.py +│ │ └── security.py +│ ├── db +│ │ ├── base.py +│ │ ├── base_class.py +│ │ └── session.py +│ ├── models +│ │ └── user.py +│ ├── schemas +│ │ ├── token.py +│ │ └── user.py +│ ├── services +│ │ └── user.py +│ └── storage +│ └── db +├── main.py +├── migrations +│ ├── env.py +│ ├── README +│ ├── script.py.mako +│ └── versions +│ └── 001_create_user_table.py +└── requirements.txt +``` + +## Getting Started + +### Prerequisites + +- Python 3.8 or higher + +### Installation + +1. Clone the repository +```bash +git clone +cd userauthenticationservice +``` + +2. Install dependencies +```bash +pip install -r requirements.txt +``` + +3. Run the migrations +```bash +alembic upgrade head +``` + +4. Start the server +```bash +uvicorn main:app --reload +``` + +## API Documentation + +Once the server is running, you can access the API documentation at: + +- Swagger UI: http://localhost:8000/docs +- ReDoc: http://localhost:8000/redoc + +## API Endpoints + +### Authentication + +- `POST /api/v1/auth/register` - Register a new user +- `POST /api/v1/auth/login` - Login and get tokens +- `POST /api/v1/auth/refresh-token` - Refresh access token + +### Users + +- `GET /api/v1/users/me` - Get current user profile +- `PUT /api/v1/users/me` - Update current user profile +- `GET /api/v1/users/{user_id}` - Get user by ID (superuser only) + +### Health Check + +- `GET /health` - Service health check + +## Security + +- Passwords are hashed using bcrypt +- Authentication is handled via JWT tokens +- Access tokens expire after 30 minutes +- Refresh tokens expire after 7 days +- CORS protection is enabled + +## Development + +For development, you can run the server with auto-reload: + +```bash +uvicorn main:app --reload +``` \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..9009f5b --- /dev/null +++ b/alembic.ini @@ -0,0 +1,111 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = migrations + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(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. + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +# SQLite URL example - make sure to use an absolute path for the database file +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..b96d27b --- /dev/null +++ b/app/__init__.py @@ -0,0 +1 @@ +# Make app directory a package diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..02057e7 --- /dev/null +++ b/app/api/__init__.py @@ -0,0 +1 @@ +# Make api directory a package diff --git a/app/api/api.py b/app/api/api.py new file mode 100644 index 0000000..5a94834 --- /dev/null +++ b/app/api/api.py @@ -0,0 +1,7 @@ +from fastapi import APIRouter + +from app.api.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"]) diff --git a/app/api/deps.py b/app/api/deps.py new file mode 100644 index 0000000..d10b917 --- /dev/null +++ b/app/api/deps.py @@ -0,0 +1,70 @@ + +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 import schemas +from app.core.config import settings +from app.db.session import get_db +from app.models.user import User +from app.services import user as user_service + +oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_STR}/auth/login") + + +def get_current_user( + db: Session = Depends(get_db), + token: str = Depends(oauth2_scheme), +) -> User: + """ + Get the current user from the token. + """ + try: + payload = jwt.decode( + token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM] + ) + token_data = schemas.TokenPayload(**payload) + except (jwt.JWTError, ValidationError): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Could not validate credentials", + ) + + # Get the user from the token + user = user_service.get_by_id(db, id=int(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 the 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 the 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 diff --git a/app/api/endpoints/__init__.py b/app/api/endpoints/__init__.py new file mode 100644 index 0000000..8d04f8f --- /dev/null +++ b/app/api/endpoints/__init__.py @@ -0,0 +1 @@ +# Make endpoints directory a package diff --git a/app/api/endpoints/auth.py b/app/api/endpoints/auth.py new file mode 100644 index 0000000..0ac653f --- /dev/null +++ b/app/api/endpoints/auth.py @@ -0,0 +1,146 @@ +from datetime import timedelta +from typing import Any + +from fastapi import APIRouter, Depends, HTTPException, status +from fastapi.security import OAuth2PasswordRequestForm +from jose import jwt +from pydantic import ValidationError +from sqlalchemy.orm import Session + +from app import schemas +from app.api import deps +from app.core import security +from app.core.config import settings +from app.services import user as user_service + +router = APIRouter() + + +@router.post("/register", response_model=schemas.User) +def register( + *, + db: Session = Depends(deps.get_db), + user_in: schemas.UserCreate, +) -> Any: + """ + Register a new user. + """ + # Check if user with email exists + user = user_service.get_by_email(db, email=user_in.email) + if user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Email already registered", + ) + + # Check if user with username exists + user = user_service.get_by_username(db, username=user_in.username) + if user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Username already taken", + ) + + # Create new user + user = user_service.create(db, obj_in=user_in) + return user + + +@router.post("/login", response_model=schemas.Token) +def login( + db: Session = Depends(deps.get_db), + form_data: OAuth2PasswordRequestForm = Depends(), +) -> Any: + """ + Login for access token. + """ + # Authenticate user + user = user_service.authenticate( + db, email_or_username=form_data.username, password=form_data.password + ) + if not user: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect email/username or password", + headers={"WWW-Authenticate": "Bearer"}, + ) + + # Check if user is active + if not user_service.is_active(user): + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Inactive user", + ) + + # Create access token + access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) + access_token = security.create_access_token( + user.id, expires_delta=access_token_expires + ) + + # Create refresh token + refresh_token = security.create_refresh_token(user.id) + + return { + "access_token": access_token, + "refresh_token": refresh_token, + "token_type": "bearer", + } + + +@router.post("/refresh-token", response_model=schemas.Token) +def refresh_token( + db: Session = Depends(deps.get_db), + token_data: schemas.RefreshToken = None, +) -> Any: + """ + Refresh access token. + """ + try: + # Decode the refresh token + payload = jwt.decode( + token_data.refresh_token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM] + ) + token_data = schemas.TokenPayload(**payload) + + # Check if token type is refresh + if payload.get("type") != "refresh": + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Invalid refresh token", + ) + except (jwt.JWTError, ValidationError): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Could not validate credentials", + ) + + # Get the user from the token + user = user_service.get_by_id(db, id=int(token_data.sub)) + if not user: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="User not found", + ) + + # Check if user is active + if not user_service.is_active(user): + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Inactive user", + ) + + # Create new access token + access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) + access_token = security.create_access_token( + user.id, expires_delta=access_token_expires + ) + + # Create new refresh token + refresh_token = security.create_refresh_token(user.id) + + return { + "access_token": access_token, + "refresh_token": refresh_token, + "token_type": "bearer", + } diff --git a/app/api/endpoints/users.py b/app/api/endpoints/users.py new file mode 100644 index 0000000..6f2ddc6 --- /dev/null +++ b/app/api/endpoints/users.py @@ -0,0 +1,64 @@ +from typing import Any + +from fastapi import APIRouter, Body, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app import schemas +from app.api import deps +from app.models.user import User +from app.services import user as user_service + +router = APIRouter() + + +@router.get("/me", response_model=schemas.User) +def read_user_me( + current_user: User = Depends(deps.get_current_active_user), +) -> Any: + """ + Get current user. + """ + return current_user + + +@router.put("/me", response_model=schemas.User) +def update_user_me( + *, + db: Session = Depends(deps.get_db), + full_name: str = Body(None), + password: str = Body(None), + current_user: User = Depends(deps.get_current_active_user), +) -> Any: + """ + Update current user. + """ + current_user_data = schemas.UserUpdate( + full_name=full_name or current_user.full_name, + password=password, + ) + user = user_service.update(db, db_obj=current_user, obj_in=current_user_data) + return user + + +@router.get("/{user_id}", response_model=schemas.User) +def read_user_by_id( + user_id: int, + current_user: User = Depends(deps.get_current_active_user), + db: Session = Depends(deps.get_db), +) -> Any: + """ + Get a specific user by id. + """ + user = user_service.get_by_id(db, id=user_id) + if not user: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="User not found", + ) + # Only allow superusers to access other users' data + if user.id != current_user.id and not user_service.is_superuser(current_user): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Not enough permissions", + ) + return user diff --git a/app/core/__init__.py b/app/core/__init__.py new file mode 100644 index 0000000..4fb144c --- /dev/null +++ b/app/core/__init__.py @@ -0,0 +1 @@ +# Make core directory a package diff --git a/app/core/config.py b/app/core/config.py new file mode 100644 index 0000000..af662b0 --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,41 @@ +from pathlib import Path +from typing import List, Union + +from pydantic import AnyHttpUrl, validator +from pydantic_settings import BaseSettings + + +class Settings(BaseSettings): + PROJECT_NAME: str = "User Authentication Service" + VERSION: str = "0.1.0" + API_V1_STR: str = "/api/v1" + + # SECURITY + SECRET_KEY: str = "your-secret-key-change-in-production" # Change in production! + ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 # 30 minutes + REFRESH_TOKEN_EXPIRE_DAYS: int = 7 # 7 days + ALGORITHM: str = "HS256" + + # 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) + + # DB + DB_DIR: Path = Path("/app") / "storage" / "db" + SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite" + + class Config: + case_sensitive = True + + +settings = Settings() + +# Ensure DB directory exists +settings.DB_DIR.mkdir(parents=True, exist_ok=True) diff --git a/app/core/security.py b/app/core/security.py new file mode 100644 index 0000000..2be4eda --- /dev/null +++ b/app/core/security.py @@ -0,0 +1,48 @@ +from datetime import datetime, timedelta +from typing import Any, Union + +from jose import jwt +from passlib.context import CryptContext + +from app.core.config import settings + +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + + +def create_access_token(subject: Union[str, Any], expires_delta: timedelta = None) -> str: + """ + Create a JWT access token. + """ + 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=settings.ALGORITHM) + return encoded_jwt + + +def create_refresh_token(subject: Union[str, Any]) -> str: + """ + Create a JWT refresh token. + """ + expire = datetime.utcnow() + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS) + to_encode = {"exp": expire, "sub": str(subject), "type": "refresh"} + encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) + return encoded_jwt + + +def verify_password(plain_password: str, hashed_password: str) -> bool: + """ + Verify a password against a hash. + """ + return pwd_context.verify(plain_password, hashed_password) + + +def get_password_hash(password: str) -> str: + """ + Generate a hash for a password. + """ + return pwd_context.hash(password) diff --git a/app/db/__init__.py b/app/db/__init__.py new file mode 100644 index 0000000..852948e --- /dev/null +++ b/app/db/__init__.py @@ -0,0 +1 @@ +# Make db directory a package diff --git a/app/db/base.py b/app/db/base.py new file mode 100644 index 0000000..f002e1b --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,4 @@ +# Import all the models, so that Base has them before being +# imported by Alembic +from app.db.base_class import Base # noqa +from app.models.user import User # noqa \ No newline at end of file diff --git a/app/db/base_class.py b/app/db/base_class.py new file mode 100644 index 0000000..1e2aabe --- /dev/null +++ b/app/db/base_class.py @@ -0,0 +1,14 @@ +from typing import Any + +from sqlalchemy.ext.declarative import as_declarative, declared_attr + + +@as_declarative() +class Base: + id: Any + __name__: str + + # Generate __tablename__ automatically + @declared_attr + def __tablename__(cls) -> str: + return cls.__name__.lower() diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..fe53228 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,19 @@ +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +from app.core.config import settings + +engine = create_engine( + settings.SQLALCHEMY_DATABASE_URL, + connect_args={"check_same_thread": False} # Needed for SQLite +) +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + + +# Dependency to get DB session +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000..f4efafc --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1 @@ +# Make models directory a package diff --git a/app/models/user.py b/app/models/user.py new file mode 100644 index 0000000..33b67a5 --- /dev/null +++ b/app/models/user.py @@ -0,0 +1,16 @@ +from sqlalchemy import Boolean, Column, DateTime, Integer, String +from sqlalchemy.sql import func + +from app.db.base_class import Base + + +class User(Base): + 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()) diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..efd6ed0 --- /dev/null +++ b/app/schemas/__init__.py @@ -0,0 +1,8 @@ +# Re-export schemas for easier imports +from app.schemas.token import RefreshToken, Token, TokenPayload +from app.schemas.user import User, UserCreate, UserInDB, UserInDBBase, UserUpdate + +__all__ = [ + "Token", "TokenPayload", "RefreshToken", + "User", "UserCreate", "UserUpdate", "UserInDB", "UserInDBBase", +] diff --git a/app/schemas/token.py b/app/schemas/token.py new file mode 100644 index 0000000..7094682 --- /dev/null +++ b/app/schemas/token.py @@ -0,0 +1,18 @@ +from typing import Optional + +from pydantic import BaseModel + + +class Token(BaseModel): + access_token: str + refresh_token: str + token_type: str + + +class TokenPayload(BaseModel): + sub: Optional[str] = None + exp: Optional[int] = None + + +class RefreshToken(BaseModel): + refresh_token: str diff --git a/app/schemas/user.py b/app/schemas/user.py new file mode 100644 index 0000000..4b53231 --- /dev/null +++ b/app/schemas/user.py @@ -0,0 +1,44 @@ +from datetime import datetime +from typing import Optional + +from pydantic import BaseModel, ConfigDict, EmailStr, Field + + +# Shared properties +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 + + +# Properties to receive via API on creation +class UserCreate(UserBase): + email: EmailStr + username: str = Field(..., min_length=3, max_length=50) + password: str = Field(..., min_length=8) + + +# Properties to receive via API on update +class UserUpdate(UserBase): + password: Optional[str] = Field(None, min_length=8) + + +# Properties shared by models stored in DB +class UserInDBBase(UserBase): + id: int + created_at: datetime + updated_at: datetime + + model_config = ConfigDict(from_attributes=True) + + +# Properties to return via API +class User(UserInDBBase): + pass + + +# Properties stored in DB +class UserInDB(UserInDBBase): + hashed_password: str diff --git a/app/services/__init__.py b/app/services/__init__.py new file mode 100644 index 0000000..3273d84 --- /dev/null +++ b/app/services/__init__.py @@ -0,0 +1 @@ +# Make services directory a package diff --git a/app/services/user.py b/app/services/user.py new file mode 100644 index 0000000..2b6ca4d --- /dev/null +++ b/app/services/user.py @@ -0,0 +1,96 @@ +from typing import Any, Dict, Optional, 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_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_by_id(db: Session, id: int) -> Optional[User]: + """ + Get a user by ID. + """ + return db.query(User).filter(User.id == id).first() + + +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_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.model_dump(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: + setattr(db_obj, field, update_data[field]) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + +def authenticate(db: Session, *, email_or_username: str, password: str) -> Optional[User]: + """ + Authenticate a user. + """ + user = get_by_email(db, email=email_or_username) + if not user: + # Try with username + user = get_by_username(db, username=email_or_username) + 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 a user is active. + """ + return user.is_active + + +def is_superuser(user: User) -> bool: + """ + Check if a user is a superuser. + """ + return user.is_superuser diff --git a/main.py b/main.py new file mode 100644 index 0000000..747ed59 --- /dev/null +++ b/main.py @@ -0,0 +1,39 @@ +import uvicorn +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware + +from app.api.api import api_router +from app.core.config import settings + +app = FastAPI( + title=settings.PROJECT_NAME, + version=settings.VERSION, + description="User Authentication Service API", + 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) + + +@app.get("/health", tags=["Health"]) +async def health_check(): + """ + Health check endpoint to verify the service is running. + """ + return {"status": "healthy"} + + +if __name__ == "__main__": + uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..3542e0e --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration with SQLite. \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..faeb1a0 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,78 @@ +from logging.config import fileConfig + +from alembic import context +from sqlalchemy import engine_from_config, pool + +# 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 +from app.db.base import Base # noqa +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, # Key configuration for SQLite + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() 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_table.py b/migrations/versions/001_create_user_table.py new file mode 100644 index 0000000..7e1a076 --- /dev/null +++ b/migrations/versions/001_create_user_table.py @@ -0,0 +1,42 @@ +"""create user table + +Revision ID: 001 +Revises: +Create Date: 2023-11-14 + +""" +import sqlalchemy as sa +from alembic import op +from sqlalchemy.sql import func + +# revision identifiers, used by Alembic. +revision = '001' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + 'user', + 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(), nullable=True, default=True), + sa.Column('is_superuser', sa.Boolean(), nullable=True, default=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=func.now(), nullable=True), + sa.Column('updated_at', sa.DateTime(timezone=True), server_default=func.now(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True) + op.create_index(op.f('ix_user_id'), 'user', ['id'], unique=False) + op.create_index(op.f('ix_user_username'), 'user', ['username'], unique=True) + + +def downgrade() -> None: + op.drop_index(op.f('ix_user_username'), table_name='user') + op.drop_index(op.f('ix_user_id'), table_name='user') + op.drop_index(op.f('ix_user_email'), table_name='user') + op.drop_table('user') diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..841d038 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,17 @@ +[tool.ruff] +line-length = 100 +target-version = "py38" + +[tool.ruff.lint] +select = [ + "E", # pycodestyle errors + "F", # pyflakes + "I", # isort + "W", # pycodestyle warnings +] +ignore = [ + "E501", # line too long, handled by black +] + +[tool.ruff.lint.isort] +known-third-party = ["fastapi", "pydantic", "sqlalchemy", "jose", "passlib"] \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..27946db --- /dev/null +++ b/requirements.txt @@ -0,0 +1,11 @@ +fastapi>=0.104.0,<0.105.0 +uvicorn>=0.23.2,<0.24.0 +sqlalchemy>=2.0.23,<2.1.0 +alembic>=1.12.1,<1.13.0 +pydantic>=2.4.2,<2.5.0 +pydantic-settings>=2.0.3,<2.1.0 +python-jose[cryptography]>=3.3.0,<3.4.0 +passlib[bcrypt]>=1.7.4,<1.8.0 +python-multipart>=0.0.6,<0.1.0 +ruff>=0.1.5,<0.2.0 +pathlib>=1.0.1,<1.1.0 \ No newline at end of file