From 43235eb6046b22de9132626c5c8f52271c535323 Mon Sep 17 00:00:00 2001 From: Automated Action Date: Wed, 28 May 2025 15:17:44 +0000 Subject: [PATCH] Create TechDating API backend - Setup project structure and basic FastAPI application - Define database models for users, profiles, matches, and messages - Set up database connection and create Alembic migrations - Implement user authentication and registration endpoints - Create API endpoints for profile management, matches, and messaging - Add filtering and search functionality for tech profiles - Setup environment variable configuration - Create README with project information and setup instructions --- README.md | 122 ++++++++++++++++++- alembic.ini | 102 ++++++++++++++++ app/__init__.py | 0 app/api/__init__.py | 0 app/api/deps.py | 63 ++++++++++ app/api/health.py | 26 ++++ app/api/v1/__init__.py | 0 app/api/v1/api.py | 11 ++ app/api/v1/endpoints/__init__.py | 1 + app/api/v1/endpoints/auth.py | 69 +++++++++++ app/api/v1/endpoints/matches.py | 137 +++++++++++++++++++++ app/api/v1/endpoints/messages.py | 139 ++++++++++++++++++++++ app/api/v1/endpoints/profiles.py | 135 +++++++++++++++++++++ app/api/v1/endpoints/users.py | 67 +++++++++++ app/core/__init__.py | 0 app/core/config.py | 43 +++++++ app/core/security.py | 31 +++++ app/crud/__init__.py | 6 + app/crud/base.py | 61 ++++++++++ app/crud/crud_match.py | 37 ++++++ app/crud/crud_message.py | 48 ++++++++ app/crud/crud_profile.py | 19 +++ app/crud/crud_user.py | 59 +++++++++ app/db/__init__.py | 0 app/db/session.py | 28 +++++ app/models/__init__.py | 6 + app/models/match.py | 28 +++++ app/models/message.py | 23 ++++ app/models/profile.py | 40 +++++++ app/models/user.py | 25 ++++ app/schemas/__init__.py | 13 ++ app/schemas/match.py | 44 +++++++ app/schemas/message.py | 40 +++++++ app/schemas/profile.py | 72 +++++++++++ app/schemas/token.py | 11 ++ app/schemas/user.py | 37 ++++++ app/services/__init__.py | 0 app/utils/__init__.py | 0 main.py | 64 ++++++++++ migrations/env.py | 81 +++++++++++++ migrations/script.py.mako | 26 ++++ migrations/versions/001_initial_schema.py | 111 +++++++++++++++++ requirements.txt | 14 +++ 43 files changed, 1837 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/deps.py create mode 100644 app/api/health.py create mode 100644 app/api/v1/__init__.py create mode 100644 app/api/v1/api.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/matches.py create mode 100644 app/api/v1/endpoints/messages.py create mode 100644 app/api/v1/endpoints/profiles.py create mode 100644 app/api/v1/endpoints/users.py create mode 100644 app/core/__init__.py create mode 100644 app/core/config.py create mode 100644 app/core/security.py create mode 100644 app/crud/__init__.py create mode 100644 app/crud/base.py create mode 100644 app/crud/crud_match.py create mode 100644 app/crud/crud_message.py create mode 100644 app/crud/crud_profile.py create mode 100644 app/crud/crud_user.py create mode 100644 app/db/__init__.py create mode 100644 app/db/session.py create mode 100644 app/models/__init__.py create mode 100644 app/models/match.py create mode 100644 app/models/message.py create mode 100644 app/models/profile.py create mode 100644 app/models/user.py create mode 100644 app/schemas/__init__.py create mode 100644 app/schemas/match.py create mode 100644 app/schemas/message.py create mode 100644 app/schemas/profile.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/utils/__init__.py create mode 100644 main.py create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/001_initial_schema.py create mode 100644 requirements.txt diff --git a/README.md b/README.md index e8acfba..b02d7f3 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,121 @@ -# FastAPI Application +# TechDating API -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A backend API for a dating application focused on tech professionals. + +## Features + +- User authentication and registration +- Profile management with tech-focused details +- Matching system between users +- Messaging between matched users +- Tech stack filtering for finding compatible matches + +## Tech Stack + +- **Framework**: FastAPI +- **Database**: SQLite with SQLAlchemy ORM +- **Authentication**: JWT tokens +- **Migrations**: Alembic + +## API Endpoints + +The API is organized into the following main sections: + +- `/api/v1/auth`: User registration and authentication +- `/api/v1/users`: User account management +- `/api/v1/profiles`: User profile creation and management +- `/api/v1/matches`: Match requests and responses +- `/api/v1/messages`: Messaging between matched users +- `/health`: Application health check + +## Getting Started + +### Prerequisites + +- Python 3.8+ +- pip + +### Installation + +1. Clone the repository +```bash +git clone +cd techdatingappbackend +``` + +2. Create and activate a virtual environment +```bash +python -m venv venv +source venv/bin/activate # On Windows, use: venv\Scripts\activate +``` + +3. Install dependencies +```bash +pip install -r requirements.txt +``` + +4. Set up environment variables +```bash +cp .env.example .env +# Edit .env with your desired configuration +``` + +5. Run database migrations +```bash +alembic upgrade head +``` + +6. Start the development server +```bash +uvicorn main:app --reload +``` + +The API will be available at http://localhost:8000. +API documentation will be available at http://localhost:8000/docs. + +## Project Structure + +``` +. +├── alembic.ini # Alembic configuration +├── app/ # Application code +│ ├── api/ # API endpoints +│ │ ├── v1/ # API version 1 +│ │ │ ├── endpoints/ # API endpoint implementations +│ │ │ └── api.py # API router +│ │ └── deps.py # API dependencies (auth, etc.) +│ ├── core/ # Core application code +│ │ ├── config.py # Configuration settings +│ │ └── security.py # Security utilities +│ ├── crud/ # CRUD operations +│ ├── db/ # Database setup +│ │ └── session.py # Database session management +│ ├── models/ # SQLAlchemy models +│ └── schemas/ # Pydantic schemas +├── migrations/ # Alembic migrations +│ └── versions/ # Migration scripts +├── main.py # Application entry point +├── requirements.txt # Dependencies +└── .env # Environment variables +``` + +## Development + +### Running Tests + +```bash +pytest +``` + +### Linting + +```bash +ruff . +``` + +## API Documentation + +Once the server is running, visit: + +- Swagger UI: http://localhost:8000/docs +- ReDoc: http://localhost:8000/redoc \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..a47643b --- /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 + +# SQLite URL - Using an absolute path to ensure consistent location across environments +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/deps.py b/app/api/deps.py new file mode 100644 index 0000000..6b9ea0f --- /dev/null +++ b/app/api/deps.py @@ -0,0 +1,63 @@ +from typing import Optional + +from fastapi import Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer +from jose import jwt, JWTError +from pydantic import ValidationError +from sqlalchemy.orm import Session + +from app.db.session import get_db +from app.core.config import settings +from app.core.security import verify_password +from app.schemas.token import TokenPayload +from app.models.user import User + +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: + try: + payload = jwt.decode( + token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM] + ) + token_data = TokenPayload(**payload) + except (JWTError, ValidationError): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Could not validate credentials", + ) + user = db.query(User).filter(User.id == token_data.sub).first() + if not user: + raise HTTPException(status_code=404, detail="User not found") + return user + + +def get_current_active_user( + current_user: User = Depends(get_current_user), +) -> User: + if not current_user.is_active: + raise HTTPException(status_code=400, detail="Inactive user") + return current_user + + +def get_current_active_superuser( + current_user: User = Depends(get_current_user), +) -> User: + if not current_user.is_superuser: + raise HTTPException( + status_code=403, detail="The user doesn't have enough privileges" + ) + return current_user + + +def authenticate_user(db: Session, username: str, password: str) -> Optional[User]: + user = db.query(User).filter(User.username == username).first() + if not user: + return None + if not verify_password(password, user.hashed_password): + return None + return user \ No newline at end of file diff --git a/app/api/health.py b/app/api/health.py new file mode 100644 index 0000000..4a90fe4 --- /dev/null +++ b/app/api/health.py @@ -0,0 +1,26 @@ +from fastapi import APIRouter, Depends +from sqlalchemy.orm import Session +from sqlalchemy import text + +from app.db.session import get_db + +health_router = APIRouter() + + +@health_router.get("/health", tags=["health"]) +async def health_check(db: Session = Depends(get_db)): + """ + Health check endpoint that also verifies database connectivity + """ + try: + # Check database connection + db.execute(text("SELECT 1")) + db_status = "healthy" + except Exception as e: + db_status = f"unhealthy: {str(e)}" + + return { + "status": "ok", + "database": db_status, + "version": "0.1.0" + } \ No newline at end of file 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/api.py b/app/api/v1/api.py new file mode 100644 index 0000000..43af15d --- /dev/null +++ b/app/api/v1/api.py @@ -0,0 +1,11 @@ +from fastapi import APIRouter + +from app.api.v1.endpoints import users, profiles, matches, messages, auth + +api_router = APIRouter() + +api_router.include_router(auth.router, prefix="/auth", tags=["auth"]) +api_router.include_router(users.router, prefix="/users", tags=["users"]) +api_router.include_router(profiles.router, prefix="/profiles", tags=["profiles"]) +api_router.include_router(matches.router, prefix="/matches", tags=["matches"]) +api_router.include_router(messages.router, prefix="/messages", tags=["messages"]) \ No newline at end of file diff --git a/app/api/v1/endpoints/__init__.py b/app/api/v1/endpoints/__init__.py new file mode 100644 index 0000000..5e6fdc1 --- /dev/null +++ b/app/api/v1/endpoints/__init__.py @@ -0,0 +1 @@ +# Empty init file to make the endpoints a package \ No newline at end of file diff --git a/app/api/v1/endpoints/auth.py b/app/api/v1/endpoints/auth.py new file mode 100644 index 0000000..51fabba --- /dev/null +++ b/app/api/v1/endpoints/auth.py @@ -0,0 +1,69 @@ +from datetime import timedelta +from typing import Any + +from fastapi import APIRouter, Depends, HTTPException +from fastapi.security import OAuth2PasswordRequestForm +from sqlalchemy.orm import Session + +from app.api.deps import authenticate_user, get_current_user +from app.core.config import settings +from app.core.security import create_access_token +from app.db.session import get_db +from app.schemas.token import Token +from app.schemas.user import User, UserCreate +from app.crud import user + +router = APIRouter() + + +@router.post("/login", response_model=Token) +def login_access_token( + db: Session = Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends() +) -> Any: + """ + OAuth2 compatible token login, get an access token for future requests + """ + user_obj = authenticate_user(db, form_data.username, form_data.password) + if not user_obj: + raise HTTPException(status_code=400, detail="Incorrect username or password") + access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) + return { + "access_token": create_access_token( + user_obj.id, expires_delta=access_token_expires + ), + "token_type": "bearer", + } + + +@router.post("/register", response_model=User) +def register_user( + *, + db: Session = Depends(get_db), + user_in: UserCreate, +) -> Any: + """ + Register a new user + """ + # Check if user already exists + if user.get_by_email(db, email=user_in.email): + raise HTTPException( + status_code=400, + detail="A user with this email already exists", + ) + if user.get_by_username(db, username=user_in.username): + raise HTTPException( + status_code=400, + detail="A user with this username already exists", + ) + + # Create new user + new_user = user.create(db, obj_in=user_in) + return new_user + + +@router.post("/test-token", response_model=User) +def test_token(current_user: User = Depends(get_current_user)) -> Any: + """ + Test access token + """ + return current_user \ No newline at end of file diff --git a/app/api/v1/endpoints/matches.py b/app/api/v1/endpoints/matches.py new file mode 100644 index 0000000..2c19a11 --- /dev/null +++ b/app/api/v1/endpoints/matches.py @@ -0,0 +1,137 @@ +from typing import Any, List, Optional + +from fastapi import APIRouter, Depends, HTTPException, Query, status +from sqlalchemy.orm import Session + +from app.api.deps import get_current_active_user +from app.db.session import get_db +from app.models.user import User +from app.models.match import MatchStatusEnum +from app.schemas.match import Match, MatchCreate, MatchUpdate +from app.crud import match, user as user_crud + +router = APIRouter() + + +@router.post("/", response_model=Match) +def create_match( + *, + db: Session = Depends(get_db), + match_in: MatchCreate, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Create new match request + """ + # Check if the receiver exists + receiver = user_crud.get(db, id=match_in.receiver_id) + if not receiver: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Receiver not found", + ) + + # Check if receiver is the same as sender (self-match) + if current_user.id == match_in.receiver_id: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Cannot match with yourself", + ) + + # Check if match already exists + existing_match = match.get_by_users( + db, user1_id=current_user.id, user2_id=match_in.receiver_id + ) + if existing_match: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Match already exists", + ) + + # Create match with current user as sender + match_data = match_in.dict() + match_data["sender_id"] = current_user.id + match_data["status"] = MatchStatusEnum.pending + + return match.create(db, obj_in=MatchCreate(**match_data)) + + +@router.put("/{match_id}", response_model=Match) +def update_match( + *, + db: Session = Depends(get_db), + match_id: int, + match_in: MatchUpdate, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Update match status (accept/reject) + """ + match_obj = match.get(db, id=match_id) + if not match_obj: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Match not found", + ) + + # Only the receiver can update the match status + if match_obj.receiver_id != current_user.id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Not allowed to update this match", + ) + + # Only pending matches can be updated + if match_obj.status != MatchStatusEnum.pending: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Match is already {match_obj.status}", + ) + + updated_match = match.update(db, db_obj=match_obj, obj_in=match_in) + return updated_match + + +@router.get("/", response_model=List[Match]) +def read_matches( + *, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_active_user), + status: Optional[MatchStatusEnum] = Query(None, description="Filter by status"), + skip: int = 0, + limit: int = 100, +) -> Any: + """ + Retrieve matches for current user + """ + matches = match.get_user_matches( + db, user_id=current_user.id, status=status, skip=skip, limit=limit + ) + return matches + + +@router.get("/{match_id}", response_model=Match) +def read_match( + *, + db: Session = Depends(get_db), + match_id: int, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Get match by ID + """ + match_obj = match.get(db, id=match_id) + if not match_obj: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Match not found", + ) + + # Only users involved in the match can see it + if match_obj.sender_id != current_user.id and match_obj.receiver_id != current_user.id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Not allowed to access this match", + ) + + return match_obj \ No newline at end of file diff --git a/app/api/v1/endpoints/messages.py b/app/api/v1/endpoints/messages.py new file mode 100644 index 0000000..54239a0 --- /dev/null +++ b/app/api/v1/endpoints/messages.py @@ -0,0 +1,139 @@ +from typing import Any, List + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app.api.deps import get_current_active_user +from app.db.session import get_db +from app.models.user import User +from app.models.match import MatchStatusEnum +from app.schemas.message import Message, MessageCreate +from app.crud import message, match as match_crud + +router = APIRouter() + + +@router.post("/", response_model=Message) +def create_message( + *, + db: Session = Depends(get_db), + message_in: MessageCreate, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Create new message + """ + # Check if the match exists + match_obj = match_crud.get(db, id=message_in.match_id) + if not match_obj: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Match not found", + ) + + # Only users involved in the match can send messages + if match_obj.sender_id != current_user.id and match_obj.receiver_id != current_user.id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Not allowed to send messages in this match", + ) + + # Only matched users can message each other + if match_obj.status != MatchStatusEnum.accepted: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Can only send messages in accepted matches", + ) + + # Determine the receiver based on the sender + if current_user.id == match_obj.sender_id: + receiver_id = match_obj.receiver_id + else: + receiver_id = match_obj.sender_id + + # Create message with sender and receiver information + message_data = message_in.dict() + message_data["sender_id"] = current_user.id + message_data["receiver_id"] = receiver_id + + return message.create(db, obj_in=MessageCreate(**message_data)) + + +@router.get("/match/{match_id}", response_model=List[Message]) +def read_messages_by_match( + *, + db: Session = Depends(get_db), + match_id: int, + current_user: User = Depends(get_current_active_user), + skip: int = 0, + limit: int = 100, +) -> Any: + """ + Get messages for a specific match + """ + # Check if the match exists + match_obj = match_crud.get(db, id=match_id) + if not match_obj: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Match not found", + ) + + # Only users involved in the match can read messages + if match_obj.sender_id != current_user.id and match_obj.receiver_id != current_user.id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Not allowed to access messages in this match", + ) + + # Mark messages as read + if match_obj.sender_id == current_user.id or match_obj.receiver_id == current_user.id: + message.mark_as_read(db, user_id=current_user.id, match_id=match_id) + + # Get messages + messages = message.get_by_match(db, match_id=match_id, skip=skip, limit=limit) + return messages + + +@router.get("/", response_model=List[Message]) +def read_user_messages( + *, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_active_user), + skip: int = 0, + limit: int = 100, +) -> Any: + """ + Get all messages for the current user + """ + messages = message.get_user_messages(db, user_id=current_user.id, skip=skip, limit=limit) + return messages + + +@router.put("/{message_id}/read", response_model=Message) +def mark_message_read( + *, + db: Session = Depends(get_db), + message_id: int, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Mark a message as read + """ + msg = message.get(db, id=message_id) + if not msg: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Message not found", + ) + + # Only the receiver can mark a message as read + if msg.receiver_id != current_user.id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Not allowed to mark this message as read", + ) + + # Update the message + updated_message = message.update(db, db_obj=msg, obj_in={"is_read": True}) + return updated_message \ No newline at end of file diff --git a/app/api/v1/endpoints/profiles.py b/app/api/v1/endpoints/profiles.py new file mode 100644 index 0000000..7293c02 --- /dev/null +++ b/app/api/v1/endpoints/profiles.py @@ -0,0 +1,135 @@ +from typing import Any, List, Optional + +from fastapi import APIRouter, Depends, HTTPException, Query, status +from sqlalchemy.orm import Session + +from app.api.deps import get_current_active_user +from app.db.session import get_db +from app.models.user import User +from app.schemas.profile import Profile, ProfileCreate, ProfileUpdate +from app.crud import profile + +router = APIRouter() + + +@router.get("/me", response_model=Profile) +def read_own_profile( + current_user: User = Depends(get_current_active_user), + db: Session = Depends(get_db), +) -> Any: + """ + Get current user's profile + """ + user_profile = profile.get_by_user_id(db, user_id=current_user.id) + if not user_profile: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Profile not found", + ) + return user_profile + + +@router.post("/", response_model=Profile) +def create_profile( + *, + db: Session = Depends(get_db), + profile_in: ProfileCreate, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Create new profile for current user + """ + # Check if user already has a profile + user_profile = profile.get_by_user_id(db, user_id=current_user.id) + if user_profile: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="User already has a profile", + ) + + # Create profile with current user id + profile_data = profile_in.dict() + profile_data["user_id"] = current_user.id + + return profile.create(db, obj_in=ProfileCreate(**profile_data)) + + +@router.put("/me", response_model=Profile) +def update_own_profile( + *, + db: Session = Depends(get_db), + profile_in: ProfileUpdate, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Update current user's profile + """ + user_profile = profile.get_by_user_id(db, user_id=current_user.id) + if not user_profile: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Profile not found", + ) + + updated_profile = profile.update(db, db_obj=user_profile, obj_in=profile_in) + return updated_profile + + +@router.get("/{profile_id}", response_model=Profile) +def read_profile( + *, + profile_id: int, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Get profile by ID + """ + user_profile = profile.get(db, id=profile_id) + if not user_profile: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Profile not found", + ) + + # Only show visible profiles unless it's the user's own profile + if not user_profile.is_visible and user_profile.user_id != current_user.id: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Profile not found", + ) + + return user_profile + + +@router.get("/", response_model=List[Profile]) +def list_profiles( + *, + db: Session = Depends(get_db), + current_user: User = Depends(get_current_active_user), + skip: int = 0, + limit: int = 100, + tech_stack: Optional[str] = Query(None, description="Filter by tech stack (comma separated)"), +) -> Any: + """ + List all visible profiles with optional tech stack filtering + """ + # Basic query for visible profiles + if tech_stack: + # Simple filtering based on tech stack + # In a real app, you'd implement more sophisticated filtering + tech_list = [tech.strip().lower() for tech in tech_stack.split(",")] + profiles = [] + all_profiles = profile.get_visible_profiles(db, skip=skip, limit=limit) + + for p in all_profiles: + if not p.tech_stack: + continue + + profile_tech = [tech.strip().lower() for tech in p.tech_stack.split(",")] + if any(tech in profile_tech for tech in tech_list): + profiles.append(p) + else: + profiles = profile.get_visible_profiles(db, skip=skip, limit=limit) + + return profiles \ 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..f6e0fe3 --- /dev/null +++ b/app/api/v1/endpoints/users.py @@ -0,0 +1,67 @@ +from typing import Any, List + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app.api.deps import get_current_active_user, get_current_active_superuser +from app.db.session import get_db +from app.schemas.user import User, UserUpdate +from app.crud import user + +router = APIRouter() + + +@router.get("/me", response_model=User) +def read_user_me( + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Get current user + """ + return current_user + + +@router.put("/me", response_model=User) +def update_user_me( + *, + db: Session = Depends(get_db), + user_in: UserUpdate, + current_user: User = Depends(get_current_active_user), +) -> Any: + """ + Update current user + """ + updated_user = user.update(db, db_obj=current_user, obj_in=user_in) + return updated_user + + +@router.get("/{user_id}", response_model=User) +def read_user_by_id( + user_id: int, + current_user: User = Depends(get_current_active_user), + db: Session = Depends(get_db), +) -> Any: + """ + Get user by ID + """ + user_obj = user.get(db, id=user_id) + if not user_obj: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="User not found", + ) + return user_obj + + +@router.get("/", response_model=List[User]) +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 (superuser only) + """ + users = user.get_multi(db, skip=skip, limit=limit) + return 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..bb485ae --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,43 @@ +from typing import List, Union +from pydantic import AnyHttpUrl, validator +from pydantic_settings import BaseSettings +from pathlib import Path + + +class Settings(BaseSettings): + API_V1_STR: str = "/api/v1" + PROJECT_NAME: str = "TechDating API" + PROJECT_DESCRIPTION: str = "API for a dating app focused on tech professionals" + VERSION: str = "0.1.0" + + # Security + SECRET_KEY: str = "CHANGE_ME_IN_PRODUCTION" + ALGORITHM: str = "HS256" + ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 + + # 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" + + # Other settings + DEBUG: bool = True + + class Config: + case_sensitive = True + env_file = ".env" + + +settings = Settings() + +# Ensure the database directory exists +settings.DB_DIR.mkdir(parents=True, exist_ok=True) \ No newline at end of file diff --git a/app/core/security.py b/app/core/security.py new file mode 100644 index 0000000..b964fa3 --- /dev/null +++ b/app/core/security.py @@ -0,0 +1,31 @@ +from datetime import datetime, timedelta +from typing import Any, Union, Optional + +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: Optional[timedelta] = None +) -> str: + 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 verify_password(plain_password: str, hashed_password: str) -> bool: + return pwd_context.verify(plain_password, hashed_password) + + +def get_password_hash(password: str) -> str: + return pwd_context.hash(password) \ No newline at end of file diff --git a/app/crud/__init__.py b/app/crud/__init__.py new file mode 100644 index 0000000..3f54361 --- /dev/null +++ b/app/crud/__init__.py @@ -0,0 +1,6 @@ +from app.crud.crud_user import user +from app.crud.crud_profile import profile +from app.crud.crud_match import match +from app.crud.crud_message import message + +__all__ = ["user", "profile", "match", "message"] \ No newline at end of file diff --git a/app/crud/base.py b/app/crud/base.py new file mode 100644 index 0000000..6523bcc --- /dev/null +++ b/app/crud/base.py @@ -0,0 +1,61 @@ +from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union + +from fastapi.encoders import jsonable_encoder +from pydantic import BaseModel +from sqlalchemy.orm import Session + +from app.db.session import Base + +ModelType = TypeVar("ModelType", bound=Base) +CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel) +UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel) + + +class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): + def __init__(self, model: Type[ModelType]): + """ + CRUD object with default methods to Create, Read, Update, Delete (CRUD). + """ + self.model = model + + def get(self, db: Session, id: Any) -> Optional[ModelType]: + return db.query(self.model).filter(self.model.id == id).first() + + def get_multi( + self, db: Session, *, skip: int = 0, limit: int = 100 + ) -> List[ModelType]: + return db.query(self.model).offset(skip).limit(limit).all() + + def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType: + obj_in_data = jsonable_encoder(obj_in) + db_obj = self.model(**obj_in_data) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + def update( + self, + db: Session, + *, + db_obj: ModelType, + obj_in: Union[UpdateSchemaType, Dict[str, Any]] + ) -> ModelType: + obj_data = jsonable_encoder(db_obj) + if isinstance(obj_in, dict): + update_data = obj_in + else: + update_data = obj_in.dict(exclude_unset=True) + for field in obj_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 remove(self, db: Session, *, id: int) -> ModelType: + obj = db.query(self.model).get(id) + db.delete(obj) + db.commit() + return obj \ No newline at end of file diff --git a/app/crud/crud_match.py b/app/crud/crud_match.py new file mode 100644 index 0000000..582408a --- /dev/null +++ b/app/crud/crud_match.py @@ -0,0 +1,37 @@ +from typing import List, Optional +from sqlalchemy.orm import Session +from sqlalchemy import or_, and_ + +from app.crud.base import CRUDBase +from app.models.match import Match, MatchStatusEnum +from app.schemas.match import MatchCreate, MatchUpdate + + +class CRUDMatch(CRUDBase[Match, MatchCreate, MatchUpdate]): + def get_by_users( + self, db: Session, *, user1_id: int, user2_id: int + ) -> Optional[Match]: + return db.query(Match).filter( + or_( + and_(Match.sender_id == user1_id, Match.receiver_id == user2_id), + and_(Match.sender_id == user2_id, Match.receiver_id == user1_id) + ) + ).first() + + def get_user_matches( + self, db: Session, *, user_id: int, status: Optional[MatchStatusEnum] = None, skip: int = 0, limit: int = 100 + ) -> List[Match]: + query = db.query(Match).filter( + or_( + Match.sender_id == user_id, + Match.receiver_id == user_id + ) + ) + + if status: + query = query.filter(Match.status == status) + + return query.offset(skip).limit(limit).all() + + +match = CRUDMatch(Match) \ No newline at end of file diff --git a/app/crud/crud_message.py b/app/crud/crud_message.py new file mode 100644 index 0000000..9f83add --- /dev/null +++ b/app/crud/crud_message.py @@ -0,0 +1,48 @@ +from typing import List +from sqlalchemy.orm import Session +from sqlalchemy import or_ + +from app.crud.base import CRUDBase +from app.models.message import Message +from app.schemas.message import MessageCreate, MessageUpdate + + +class CRUDMessage(CRUDBase[Message, MessageCreate, MessageUpdate]): + def get_by_match( + self, db: Session, *, match_id: int, skip: int = 0, limit: int = 100 + ) -> List[Message]: + return db.query(Message).filter( + Message.match_id == match_id + ).order_by(Message.created_at).offset(skip).limit(limit).all() + + def get_user_messages( + self, db: Session, *, user_id: int, skip: int = 0, limit: int = 100 + ) -> List[Message]: + return db.query(Message).filter( + or_( + Message.sender_id == user_id, + Message.receiver_id == user_id + ) + ).order_by(Message.created_at.desc()).offset(skip).limit(limit).all() + + def mark_as_read( + self, db: Session, *, user_id: int, match_id: int + ) -> int: + messages = db.query(Message).filter( + Message.match_id == match_id, + Message.receiver_id == user_id, + not Message.is_read + ).all() + + count = 0 + for message in messages: + message.is_read = True + count += 1 + + if count: + db.commit() + + return count + + +message = CRUDMessage(Message) \ No newline at end of file diff --git a/app/crud/crud_profile.py b/app/crud/crud_profile.py new file mode 100644 index 0000000..c8f72ab --- /dev/null +++ b/app/crud/crud_profile.py @@ -0,0 +1,19 @@ +from typing import List, Optional +from sqlalchemy.orm import Session + +from app.crud.base import CRUDBase +from app.models.profile import Profile +from app.schemas.profile import ProfileCreate, ProfileUpdate + + +class CRUDProfile(CRUDBase[Profile, ProfileCreate, ProfileUpdate]): + def get_by_user_id(self, db: Session, *, user_id: int) -> Optional[Profile]: + return db.query(Profile).filter(Profile.user_id == user_id).first() + + def get_visible_profiles( + self, db: Session, *, skip: int = 0, limit: int = 100 + ) -> List[Profile]: + return db.query(Profile).filter(Profile.is_visible).offset(skip).limit(limit).all() + + +profile = CRUDProfile(Profile) \ No newline at end of file diff --git a/app/crud/crud_user.py b/app/crud/crud_user.py new file mode 100644 index 0000000..fb215a0 --- /dev/null +++ b/app/crud/crud_user.py @@ -0,0 +1,59 @@ +from typing import Any, Dict, Optional, Union + +from sqlalchemy.orm import Session + +from app.core.security import get_password_hash, verify_password +from app.crud.base import CRUDBase +from app.models.user import User +from app.schemas.user import UserCreate, UserUpdate + + +class CRUDUser(CRUDBase[User, UserCreate, UserUpdate]): + def get_by_email(self, db: Session, *, email: str) -> Optional[User]: + return db.query(User).filter(User.email == email).first() + + def get_by_username(self, db: Session, *, username: str) -> Optional[User]: + return db.query(User).filter(User.username == username).first() + + def create(self, db: Session, *, obj_in: UserCreate) -> User: + db_obj = User( + email=obj_in.email, + username=obj_in.username, + hashed_password=get_password_hash(obj_in.password), + is_active=True, + is_superuser=False, + ) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + def update( + self, db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]] + ) -> User: + if isinstance(obj_in, dict): + update_data = obj_in + else: + update_data = obj_in.dict(exclude_unset=True) + if update_data.get("password"): + hashed_password = get_password_hash(update_data["password"]) + del update_data["password"] + update_data["hashed_password"] = hashed_password + return super().update(db, db_obj=db_obj, obj_in=update_data) + + def authenticate(self, db: Session, *, username: str, password: str) -> Optional[User]: + user = self.get_by_username(db, username=username) + if not user: + return None + if not verify_password(password, user.hashed_password): + return None + return user + + def is_active(self, user: User) -> bool: + return user.is_active + + def is_superuser(self, user: User) -> bool: + return user.is_superuser + + +user = CRUDUser(User) \ No newline at end of file diff --git a/app/db/__init__.py b/app/db/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..4223846 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,28 @@ +from sqlalchemy import create_engine +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker + +from app.core.config import settings + +# Ensure the database directory exists +settings.DB_DIR.mkdir(parents=True, exist_ok=True) + +SQLALCHEMY_DATABASE_URL = f"sqlite:///{settings.DB_DIR}/db.sqlite" + +engine = create_engine( + SQLALCHEMY_DATABASE_URL, + connect_args={"check_same_thread": False} +) + +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + +Base = declarative_base() + + +# Dependency to get DB session +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() \ No newline at end of file diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000..ddfd0c8 --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1,6 @@ +from app.models.user import User +from app.models.profile import Profile +from app.models.match import Match +from app.models.message import Message + +__all__ = ["User", "Profile", "Match", "Message"] \ No newline at end of file diff --git a/app/models/match.py b/app/models/match.py new file mode 100644 index 0000000..6fc43c2 --- /dev/null +++ b/app/models/match.py @@ -0,0 +1,28 @@ +from sqlalchemy import Column, Integer, DateTime, ForeignKey, Enum +from sqlalchemy.orm import relationship +from sqlalchemy.sql import func +import enum + +from app.db.session import Base + + +class MatchStatusEnum(str, enum.Enum): + pending = "pending" + accepted = "accepted" + rejected = "rejected" + + +class Match(Base): + __tablename__ = "matches" + + id = Column(Integer, primary_key=True, index=True) + sender_id = Column(Integer, ForeignKey("users.id"), nullable=False) + receiver_id = Column(Integer, ForeignKey("users.id"), nullable=False) + status = Column(Enum(MatchStatusEnum), default=MatchStatusEnum.pending, nullable=False) + created_at = Column(DateTime(timezone=True), server_default=func.now()) + updated_at = Column(DateTime(timezone=True), onupdate=func.now()) + + # Relationships + sender = relationship("User", foreign_keys=[sender_id], back_populates="sent_matches") + receiver = relationship("User", foreign_keys=[receiver_id], back_populates="received_matches") + messages = relationship("Message", back_populates="match") \ No newline at end of file diff --git a/app/models/message.py b/app/models/message.py new file mode 100644 index 0000000..71c2d74 --- /dev/null +++ b/app/models/message.py @@ -0,0 +1,23 @@ +from sqlalchemy import Boolean, Column, Integer, DateTime, ForeignKey, Text +from sqlalchemy.orm import relationship +from sqlalchemy.sql import func + +from app.db.session import Base + + +class Message(Base): + __tablename__ = "messages" + + id = Column(Integer, primary_key=True, index=True) + match_id = Column(Integer, ForeignKey("matches.id"), nullable=False) + sender_id = Column(Integer, ForeignKey("users.id"), nullable=False) + receiver_id = Column(Integer, ForeignKey("users.id"), nullable=False) + content = Column(Text, nullable=False) + is_read = Column(Boolean, default=False) + created_at = Column(DateTime(timezone=True), server_default=func.now()) + updated_at = Column(DateTime(timezone=True), onupdate=func.now()) + + # Relationships + match = relationship("Match", back_populates="messages") + sender = relationship("User", foreign_keys=[sender_id], back_populates="sent_messages") + receiver = relationship("User", foreign_keys=[receiver_id], back_populates="received_messages") \ No newline at end of file diff --git a/app/models/profile.py b/app/models/profile.py new file mode 100644 index 0000000..0a20397 --- /dev/null +++ b/app/models/profile.py @@ -0,0 +1,40 @@ +from sqlalchemy import Boolean, Column, Integer, String, Date, ForeignKey, Text, DateTime +from sqlalchemy.orm import relationship +from sqlalchemy.sql import func +import enum + +from app.db.session import Base + + +class GenderEnum(str, enum.Enum): + male = "male" + female = "female" + non_binary = "non_binary" + other = "other" + + +class Profile(Base): + __tablename__ = "profiles" + + id = Column(Integer, primary_key=True, index=True) + user_id = Column(Integer, ForeignKey("users.id"), unique=True, nullable=False) + full_name = Column(String, nullable=False) + bio = Column(Text, nullable=True) + gender = Column(String, nullable=False) + date_of_birth = Column(Date, nullable=False) + location = Column(String, nullable=True) + job_title = Column(String, nullable=True) + company = Column(String, nullable=True) + education = Column(String, nullable=True) + profile_picture = Column(String, nullable=True) # URL to profile picture + interests = Column(String, nullable=True) # Stored as comma-separated values + tech_stack = Column(String, nullable=True) # Stored as comma-separated values + github_url = Column(String, nullable=True) + linkedin_url = Column(String, nullable=True) + portfolio_url = Column(String, nullable=True) + is_visible = Column(Boolean, default=True) + created_at = Column(DateTime(timezone=True), server_default=func.now()) + updated_at = Column(DateTime(timezone=True), onupdate=func.now()) + + # Relationships + user = relationship("User", back_populates="profile") \ No newline at end of file diff --git a/app/models/user.py b/app/models/user.py new file mode 100644 index 0000000..2ad2b13 --- /dev/null +++ b/app/models/user.py @@ -0,0 +1,25 @@ +from sqlalchemy import Boolean, Column, Integer, String, DateTime +from sqlalchemy.orm import relationship +from sqlalchemy.sql import func + +from app.db.session 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) + 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), onupdate=func.now()) + + # Relationships + profile = relationship("Profile", back_populates="user", uselist=False) + sent_matches = relationship("Match", foreign_keys="Match.sender_id", back_populates="sender") + received_matches = relationship("Match", foreign_keys="Match.receiver_id", back_populates="receiver") + sent_messages = relationship("Message", foreign_keys="Message.sender_id", back_populates="sender") + received_messages = relationship("Message", foreign_keys="Message.receiver_id", back_populates="receiver") \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..8dfcf50 --- /dev/null +++ b/app/schemas/__init__.py @@ -0,0 +1,13 @@ +from app.schemas.user import User, UserCreate, UserUpdate, UserInDB +from app.schemas.profile import Profile, ProfileCreate, ProfileUpdate, ProfileInDB, GenderEnum +from app.schemas.match import Match, MatchCreate, MatchUpdate, MatchInDB, MatchStatusEnum +from app.schemas.message import Message, MessageCreate, MessageUpdate, MessageInDB +from app.schemas.token import Token, TokenPayload + +__all__ = [ + "User", "UserCreate", "UserUpdate", "UserInDB", + "Profile", "ProfileCreate", "ProfileUpdate", "ProfileInDB", "GenderEnum", + "Match", "MatchCreate", "MatchUpdate", "MatchInDB", "MatchStatusEnum", + "Message", "MessageCreate", "MessageUpdate", "MessageInDB", + "Token", "TokenPayload" +] \ No newline at end of file diff --git a/app/schemas/match.py b/app/schemas/match.py new file mode 100644 index 0000000..f3abb9d --- /dev/null +++ b/app/schemas/match.py @@ -0,0 +1,44 @@ +from pydantic import BaseModel +from typing import Optional +from datetime import datetime +from enum import Enum + + +class MatchStatusEnum(str, Enum): + pending = "pending" + accepted = "accepted" + rejected = "rejected" + + +class MatchBase(BaseModel): + sender_id: Optional[int] = None + receiver_id: Optional[int] = None + status: Optional[MatchStatusEnum] = None + + +class MatchCreate(MatchBase): + receiver_id: int + + +class MatchUpdate(MatchBase): + status: MatchStatusEnum + + +class MatchInDBBase(MatchBase): + id: int + sender_id: int + receiver_id: int + status: MatchStatusEnum + created_at: datetime + updated_at: Optional[datetime] = None + + class Config: + orm_mode = True + + +class Match(MatchInDBBase): + pass + + +class MatchInDB(MatchInDBBase): + pass \ No newline at end of file diff --git a/app/schemas/message.py b/app/schemas/message.py new file mode 100644 index 0000000..12bdfc8 --- /dev/null +++ b/app/schemas/message.py @@ -0,0 +1,40 @@ +from pydantic import BaseModel, Field +from typing import Optional +from datetime import datetime + + +class MessageBase(BaseModel): + match_id: Optional[int] = None + content: Optional[str] = None + is_read: Optional[bool] = False + + +class MessageCreate(MessageBase): + match_id: int + content: str = Field(..., min_length=1) + + +class MessageUpdate(MessageBase): + is_read: bool = True + + +class MessageInDBBase(MessageBase): + id: int + match_id: int + sender_id: int + receiver_id: int + content: str + is_read: bool + created_at: datetime + updated_at: Optional[datetime] = None + + class Config: + orm_mode = True + + +class Message(MessageInDBBase): + pass + + +class MessageInDB(MessageInDBBase): + pass \ No newline at end of file diff --git a/app/schemas/profile.py b/app/schemas/profile.py new file mode 100644 index 0000000..26392a7 --- /dev/null +++ b/app/schemas/profile.py @@ -0,0 +1,72 @@ +from pydantic import BaseModel, validator +from typing import Optional, List +from datetime import date, datetime +from enum import Enum + + +class GenderEnum(str, Enum): + male = "male" + female = "female" + non_binary = "non_binary" + other = "other" + + +class ProfileBase(BaseModel): + full_name: Optional[str] = None + bio: Optional[str] = None + gender: Optional[GenderEnum] = None + date_of_birth: Optional[date] = None + location: Optional[str] = None + job_title: Optional[str] = None + company: Optional[str] = None + education: Optional[str] = None + profile_picture: Optional[str] = None + interests: Optional[str] = None # Comma-separated + tech_stack: Optional[str] = None # Comma-separated + github_url: Optional[str] = None + linkedin_url: Optional[str] = None + portfolio_url: Optional[str] = None + is_visible: Optional[bool] = True + + +class ProfileCreate(ProfileBase): + full_name: str + gender: GenderEnum + date_of_birth: date + + @validator('date_of_birth') + def validate_date_of_birth(cls, v): + today = date.today() + age = today.year - v.year - ((today.month, today.day) < (v.month, v.day)) + if age < 18: + raise ValueError("User must be at least 18 years old") + return v + + +class ProfileUpdate(ProfileBase): + pass + + +class ProfileInDBBase(ProfileBase): + id: int + user_id: int + created_at: datetime + updated_at: Optional[datetime] = None + + class Config: + orm_mode = True + + +class Profile(ProfileInDBBase): + # Process comma-separated strings to lists + @property + def interests_list(self) -> List[str]: + return self.interests.split(',') if self.interests else [] + + @property + def tech_stack_list(self) -> List[str]: + return self.tech_stack.split(',') if self.tech_stack else [] + + +class ProfileInDB(ProfileInDBBase): + pass \ No newline at end of file diff --git a/app/schemas/token.py b/app/schemas/token.py new file mode 100644 index 0000000..4b0e9c5 --- /dev/null +++ b/app/schemas/token.py @@ -0,0 +1,11 @@ +from pydantic import BaseModel +from typing import Optional + + +class Token(BaseModel): + access_token: str + token_type: str + + +class TokenPayload(BaseModel): + sub: Optional[int] = None \ No newline at end of file diff --git a/app/schemas/user.py b/app/schemas/user.py new file mode 100644 index 0000000..1860e9a --- /dev/null +++ b/app/schemas/user.py @@ -0,0 +1,37 @@ +from pydantic import BaseModel, EmailStr, Field +from typing import Optional +from datetime import datetime + + +class UserBase(BaseModel): + email: Optional[EmailStr] = None + username: Optional[str] = None + is_active: Optional[bool] = True + + +class UserCreate(UserBase): + email: EmailStr + username: str = Field(..., min_length=3, max_length=50) + password: str = Field(..., min_length=8) + + +class UserUpdate(UserBase): + password: Optional[str] = Field(None, min_length=8) + + +class UserInDBBase(UserBase): + id: int + is_active: bool + created_at: datetime + 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/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..0e592a1 --- /dev/null +++ b/main.py @@ -0,0 +1,64 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from fastapi.openapi.utils import get_openapi +import uvicorn +from contextlib import asynccontextmanager +import os + +from app.core.config import settings +from app.api.v1.api import api_router +from app.api.health import health_router + +@asynccontextmanager +async def lifespan(app: FastAPI): + # Startup logic + yield + # Shutdown logic + +app = FastAPI( + title=settings.PROJECT_NAME, + description=settings.PROJECT_DESCRIPTION, + version=settings.VERSION, + openapi_url="/openapi.json", + docs_url="/docs", + redoc_url="/redoc", + lifespan=lifespan, +) + +# Set up CORS +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=["*"], + ) + +# Include routers +app.include_router(health_router) +app.include_router(api_router, prefix=settings.API_V1_STR) + +# Override the default OpenAPI schema to add our custom info +def custom_openapi(): + if app.openapi_schema: + return app.openapi_schema + openapi_schema = get_openapi( + title=settings.PROJECT_NAME, + version=settings.VERSION, + description=settings.PROJECT_DESCRIPTION, + routes=app.routes, + ) + # Custom OpenAPI schema modifications can be added here + app.openapi_schema = openapi_schema + return app.openapi_schema + +app.openapi = custom_openapi + +if __name__ == "__main__": + uvicorn.run( + "main:app", + host="0.0.0.0", + port=int(os.getenv("PORT", "8000")), + reload=settings.DEBUG, + ) \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..71e7a6a --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,81 @@ +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +# Import models for Alembic migrations +from app.db.session 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) + +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 + compare_type=True, + ) + + 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..3cf5352 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,26 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${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_initial_schema.py b/migrations/versions/001_initial_schema.py new file mode 100644 index 0000000..1e3dcf6 --- /dev/null +++ b/migrations/versions/001_initial_schema.py @@ -0,0 +1,111 @@ +"""initial schema + +Revision ID: 001 +Revises: +Create Date: 2023-09-10 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '001' +down_revision: Union[str, None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = 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('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=sa.text('(CURRENT_TIMESTAMP)'), nullable=True), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True), + sa.PrimaryKeyConstraint('id'), + ) + op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True) + op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False) + op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True) + + # Create profiles table + op.create_table( + 'profiles', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('full_name', sa.String(), nullable=False), + sa.Column('bio', sa.Text(), nullable=True), + sa.Column('gender', sa.String(), nullable=False), + sa.Column('date_of_birth', sa.Date(), nullable=False), + sa.Column('location', sa.String(), nullable=True), + sa.Column('job_title', sa.String(), nullable=True), + sa.Column('company', sa.String(), nullable=True), + sa.Column('education', sa.String(), nullable=True), + sa.Column('profile_picture', sa.String(), nullable=True), + sa.Column('interests', sa.String(), nullable=True), + sa.Column('tech_stack', sa.String(), nullable=True), + sa.Column('github_url', sa.String(), nullable=True), + sa.Column('linkedin_url', sa.String(), nullable=True), + sa.Column('portfolio_url', sa.String(), nullable=True), + sa.Column('is_visible', sa.Boolean(), nullable=True, default=True), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('user_id') + ) + op.create_index(op.f('ix_profiles_id'), 'profiles', ['id'], unique=False) + + # Create matches table + op.create_table( + 'matches', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('sender_id', sa.Integer(), nullable=False), + sa.Column('receiver_id', sa.Integer(), nullable=False), + sa.Column('status', sa.Enum('pending', 'accepted', 'rejected', name='matchstatusenum'), nullable=False, default='pending'), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['receiver_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['sender_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_matches_id'), 'matches', ['id'], unique=False) + + # Create messages table + op.create_table( + 'messages', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('match_id', sa.Integer(), nullable=False), + sa.Column('sender_id', sa.Integer(), nullable=False), + sa.Column('receiver_id', sa.Integer(), nullable=False), + sa.Column('content', sa.Text(), nullable=False), + sa.Column('is_read', sa.Boolean(), nullable=True, default=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['match_id'], ['matches.id'], ), + sa.ForeignKeyConstraint(['receiver_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['sender_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_messages_id'), 'messages', ['id'], unique=False) + + +def downgrade() -> None: + op.drop_index(op.f('ix_messages_id'), table_name='messages') + op.drop_table('messages') + op.drop_index(op.f('ix_matches_id'), table_name='matches') + op.drop_table('matches') + op.drop_index(op.f('ix_profiles_id'), table_name='profiles') + op.drop_table('profiles') + op.drop_index(op.f('ix_users_username'), table_name='users') + op.drop_index(op.f('ix_users_id'), table_name='users') + op.drop_index(op.f('ix_users_email'), 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..a62d194 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,14 @@ +fastapi>=0.103.1,<0.104.0 +uvicorn>=0.23.2,<0.24.0 +sqlalchemy>=2.0.20,<2.1.0 +alembic>=1.12.0,<1.13.0 +pydantic>=2.3.0,<2.4.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 +email-validator>=2.0.0,<2.1.0 +ruff>=0.0.287,<0.1.0 +pytest>=7.4.2,<7.5.0 +httpx>=0.24.1,<0.25.0 +python-dotenv>=1.0.0,<1.1.0 \ No newline at end of file