From 980400187cfb511aa21251b766df9a310d12bddd Mon Sep 17 00:00:00 2001 From: Automated Action Date: Tue, 10 Jun 2025 11:00:53 +0000 Subject: [PATCH] Create FastAPI backend for communications agency website - Set up project structure with FastAPI application - Implement SQLAlchemy models for users, services, projects, team members, contacts - Create API endpoints for website functionality - Implement JWT authentication system with user roles - Add file upload functionality for media - Configure CORS and health check endpoints - Add database migrations with Alembic - Create comprehensive README with setup instructions --- README.md | 196 ++++++++++++++++++++++- alembic.ini | 85 ++++++++++ app/__init__.py | 0 app/api/__init__.py | 0 app/api/deps.py | 62 +++++++ app/api/v1/__init__.py | 0 app/api/v1/api.py | 16 ++ app/api/v1/endpoints/__init__.py | 0 app/api/v1/endpoints/auth.py | 88 ++++++++++ app/api/v1/endpoints/contact.py | 94 +++++++++++ app/api/v1/endpoints/health.py | 10 ++ app/api/v1/endpoints/projects.py | 114 +++++++++++++ app/api/v1/endpoints/services.py | 101 ++++++++++++ app/api/v1/endpoints/settings.py | 35 ++++ app/api/v1/endpoints/team.py | 95 +++++++++++ app/api/v1/endpoints/uploads.py | 77 +++++++++ app/api/v1/endpoints/users.py | 82 ++++++++++ app/core/__init__.py | 0 app/core/config.py | 44 +++++ app/core/security.py | 38 +++++ app/crud/__init__.py | 8 + app/crud/base.py | 66 ++++++++ app/crud/crud_contact.py | 19 +++ app/crud/crud_project.py | 33 ++++ app/crud/crud_service.py | 25 +++ app/crud/crud_settings.py | 23 +++ app/crud/crud_team_member.py | 22 +++ app/crud/crud_user.py | 55 +++++++ app/db/__init__.py | 0 app/db/base.py | 9 ++ app/db/base_class.py | 14 ++ app/db/session.py | 24 +++ app/models/__init__.py | 8 + app/models/contact.py | 21 +++ app/models/project.py | 23 +++ app/models/service.py | 22 +++ app/models/settings.py | 26 +++ app/models/team_member.py | 24 +++ app/models/user.py | 20 +++ app/schemas/__init__.py | 17 ++ app/schemas/contact.py | 43 +++++ app/schemas/project.py | 47 ++++++ app/schemas/service.py | 44 +++++ app/schemas/settings.py | 46 ++++++ app/schemas/team_member.py | 44 +++++ app/schemas/token.py | 12 ++ app/schemas/user.py | 43 +++++ app/services/__init__.py | 0 app/utils/__init__.py | 0 app/utils/files.py | 95 +++++++++++ app/utils/init_db.py | 49 ++++++ main.py | 78 +++++++++ migrations/README | 14 ++ migrations/env.py | 90 +++++++++++ migrations/script.py.mako | 24 +++ migrations/versions/initial_migration.py | 154 ++++++++++++++++++ requirements.txt | 15 ++ 57 files changed, 2392 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/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/contact.py create mode 100644 app/api/v1/endpoints/health.py create mode 100644 app/api/v1/endpoints/projects.py create mode 100644 app/api/v1/endpoints/services.py create mode 100644 app/api/v1/endpoints/settings.py create mode 100644 app/api/v1/endpoints/team.py create mode 100644 app/api/v1/endpoints/uploads.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_contact.py create mode 100644 app/crud/crud_project.py create mode 100644 app/crud/crud_service.py create mode 100644 app/crud/crud_settings.py create mode 100644 app/crud/crud_team_member.py create mode 100644 app/crud/crud_user.py create mode 100644 app/db/__init__.py create mode 100644 app/db/base.py create mode 100644 app/db/base_class.py create mode 100644 app/db/session.py create mode 100644 app/models/__init__.py create mode 100644 app/models/contact.py create mode 100644 app/models/project.py create mode 100644 app/models/service.py create mode 100644 app/models/settings.py create mode 100644 app/models/team_member.py create mode 100644 app/models/user.py create mode 100644 app/schemas/__init__.py create mode 100644 app/schemas/contact.py create mode 100644 app/schemas/project.py create mode 100644 app/schemas/service.py create mode 100644 app/schemas/settings.py create mode 100644 app/schemas/team_member.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 app/utils/files.py create mode 100644 app/utils/init_db.py create mode 100644 main.py create mode 100644 migrations/README create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/initial_migration.py create mode 100644 requirements.txt diff --git a/README.md b/README.md index e8acfba..f62eeca 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,195 @@ -# FastAPI Application +# Communications Agency API -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A modern FastAPI backend for a communications and creative agency website. + +## Features + +- **User Authentication**: Secure JWT-based authentication with role-based access control +- **Services Management**: Create, update, and retrieve agency services +- **Portfolio Projects**: Manage case studies and client projects +- **Team Members**: Manage team profiles and details +- **Contact Form**: Handle client inquiries and messages +- **Site Settings**: Configure global site information +- **Media Upload**: Upload and manage images and documents +- **Admin Panel API**: Secure endpoints for site administration + +## Technology Stack + +- **Framework**: FastAPI +- **Database**: SQLite +- **ORM**: SQLAlchemy +- **Migration**: Alembic +- **Authentication**: JWT (JSON Web Tokens) +- **Validation**: Pydantic +- **Linting**: Ruff + +## Project Structure + +``` +. +├── alembic.ini +├── app +│ ├── api +│ │ ├── deps.py +│ │ └── v1 +│ │ ├── api.py +│ │ └── endpoints +│ │ ├── auth.py +│ │ ├── contact.py +│ │ ├── health.py +│ │ ├── projects.py +│ │ ├── services.py +│ │ ├── settings.py +│ │ ├── team.py +│ │ ├── uploads.py +│ │ └── users.py +│ ├── core +│ │ ├── config.py +│ │ └── security.py +│ ├── crud +│ │ ├── base.py +│ │ ├── crud_contact.py +│ │ ├── crud_project.py +│ │ ├── crud_service.py +│ │ ├── crud_settings.py +│ │ ├── crud_team_member.py +│ │ └── crud_user.py +│ ├── db +│ │ ├── base.py +│ │ ├── base_class.py +│ │ └── session.py +│ ├── models +│ │ ├── contact.py +│ │ ├── project.py +│ │ ├── service.py +│ │ ├── settings.py +│ │ ├── team_member.py +│ │ └── user.py +│ ├── schemas +│ │ ├── contact.py +│ │ ├── project.py +│ │ ├── service.py +│ │ ├── settings.py +│ │ ├── team_member.py +│ │ ├── token.py +│ │ └── user.py +│ └── utils +│ ├── files.py +│ └── init_db.py +├── main.py +├── migrations +│ ├── README +│ ├── env.py +│ ├── script.py.mako +│ └── versions +│ └── initial_migration.py +└── requirements.txt +``` + +## Setup and Installation + +### Prerequisites + +- Python 3.8+ + +### Installation + +1. Clone the repository: + ```bash + git clone + cd communicationsagencywebsite + ``` + +2. Create a virtual environment: + ```bash + python -m venv venv + source venv/bin/activate # On Windows: venv\Scripts\activate + ``` + +3. Install dependencies: + ```bash + pip install -r requirements.txt + ``` + +4. Set up environment variables: + ```bash + # Create a .env file in the project root with the following variables + SECRET_KEY=your_secret_key_here + ADMIN_EMAIL=admin@example.com + ADMIN_PASSWORD=securepassword + ``` + +5. Apply database migrations: + ```bash + alembic upgrade head + ``` + +### Running the API + +Run the development server: +```bash +uvicorn main:app --host 0.0.0.0 --port 8000 --reload +``` + +The API will be available at http://localhost:8000 + +API documentation: +- Swagger UI: http://localhost:8000/docs +- ReDoc: http://localhost:8000/redoc + +## Environment Variables + +| Variable | Description | Default | +|----------|-------------|---------| +| SECRET_KEY | JWT secret key for token generation | supersecretkey123 | +| ADMIN_EMAIL | Initial admin user email | None | +| ADMIN_PASSWORD | Initial admin user password | None | +| ACCESS_TOKEN_EXPIRE_MINUTES | Token expiration time in minutes | 11520 (8 days) | + +## API Endpoints + +### Authentication +- `POST /api/v1/auth/login` - Obtain JWT token +- `POST /api/v1/auth/register` - Register a new user +- `GET /api/v1/auth/me` - Get current user info + +### Services +- `GET /api/v1/services` - List all services +- `POST /api/v1/services` - Create a new service (admin only) +- `GET /api/v1/services/{slug}` - Get service details +- `PUT /api/v1/services/{id}` - Update a service (admin only) +- `DELETE /api/v1/services/{id}` - Delete a service (admin only) + +### Projects +- `GET /api/v1/projects` - List all projects +- `GET /api/v1/projects/featured` - List featured projects +- `POST /api/v1/projects` - Create a new project (admin only) +- `GET /api/v1/projects/{slug}` - Get project details +- `PUT /api/v1/projects/{id}` - Update a project (admin only) +- `DELETE /api/v1/projects/{id}` - Delete a project (admin only) + +### Team +- `GET /api/v1/team` - List all team members +- `POST /api/v1/team` - Create a new team member (admin only) +- `GET /api/v1/team/{id}` - Get team member details +- `PUT /api/v1/team/{id}` - Update a team member (admin only) +- `DELETE /api/v1/team/{id}` - Delete a team member (admin only) + +### Contact +- `POST /api/v1/contact` - Send a contact message +- `GET /api/v1/contact` - List all contact messages (admin only) +- `PUT /api/v1/contact/{id}/read` - Mark a contact message as read (admin only) +- `DELETE /api/v1/contact/{id}` - Delete a contact message (admin only) + +### Settings +- `GET /api/v1/settings` - Get site settings +- `PUT /api/v1/settings` - Update site settings (admin only) + +### Uploads +- `POST /api/v1/uploads/images` - Upload an image (admin only) +- `POST /api/v1/uploads/documents` - Upload a document (admin only) +- `DELETE /api/v1/uploads/{file_path}` - Delete an uploaded file (admin only) + +## License + +This project is licensed under the MIT License - see the LICENSE file for details. \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..634a012 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,85 @@ +# 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 + +# timezone to use when rendering the date +# within the migration file as well as the filename. +# 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 +# version_locations = %(here)s/bar %(here)s/bat migrations/versions + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +# SQLite URL example +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 + +# 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..43fcf6c --- /dev/null +++ b/app/api/deps.py @@ -0,0 +1,62 @@ + +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 models, schemas +from app.core.config import settings +from app.db.session import get_db + +reusable_oauth2 = OAuth2PasswordBearer( + tokenUrl=f"{settings.API_V1_STR}/auth/login" +) + + +def get_current_user( + db: Session = Depends(get_db), token: str = Depends(reusable_oauth2) +) -> models.User: + """ + Validate access token and return current user + """ + 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", + ) + user = db.query(models.User).filter(models.User.id == token_data.sub).first() + if not user: + raise HTTPException(status_code=404, detail="User not found") + if not user.is_active: + raise HTTPException(status_code=400, detail="Inactive user") + return user + + +def get_current_active_user( + current_user: models.User = Depends(get_current_user), +) -> models.User: + """ + Get current active 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: models.User = Depends(get_current_user), +) -> models.User: + """ + Get current active superuser + """ + if not current_user.is_superuser: + raise HTTPException( + status_code=400, detail="The user doesn't have enough privileges" + ) + return current_user \ 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..a66b0eb --- /dev/null +++ b/app/api/v1/api.py @@ -0,0 +1,16 @@ +from fastapi import APIRouter + +from app.api.v1.endpoints import (auth, contact, health, projects, services, + settings, team, uploads, users) + +api_router = APIRouter() + +api_router.include_router(health.router, prefix="/health", tags=["Health"]) +api_router.include_router(auth.router, prefix="/auth", tags=["Authentication"]) +api_router.include_router(users.router, prefix="/users", tags=["Users"]) +api_router.include_router(services.router, prefix="/services", tags=["Services"]) +api_router.include_router(projects.router, prefix="/projects", tags=["Projects"]) +api_router.include_router(team.router, prefix="/team", tags=["Team"]) +api_router.include_router(contact.router, prefix="/contact", tags=["Contact"]) +api_router.include_router(settings.router, prefix="/settings", tags=["Settings"]) +api_router.include_router(uploads.router, prefix="/uploads", tags=["Uploads"]) \ 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..e69de29 diff --git a/app/api/v1/endpoints/auth.py b/app/api/v1/endpoints/auth.py new file mode 100644 index 0000000..52edbe6 --- /dev/null +++ b/app/api/v1/endpoints/auth.py @@ -0,0 +1,88 @@ +from datetime import timedelta +from typing import Any + +from fastapi import APIRouter, Depends, HTTPException, status +from fastapi.security import OAuth2PasswordRequestForm +from sqlalchemy.orm import Session + +from app import crud, models, schemas +from app.api import deps +from app.core import security +from app.core.config import settings + +router = APIRouter() + + +@router.post("/login", response_model=schemas.Token) +def login_access_token( + db: Session = Depends(deps.get_db), form_data: OAuth2PasswordRequestForm = Depends() +) -> Any: + """ + OAuth2 compatible token login, get an access token for future requests + """ + user = crud.user.authenticate( + db, email=form_data.username, password=form_data.password + ) + if not user: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect email or password", + ) + elif not crud.user.is_active(user): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, detail="Inactive user" + ) + access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) + return { + "access_token": security.create_access_token( + user.id, expires_delta=access_token_expires + ), + "token_type": "bearer", + } + + +@router.post("/register", response_model=schemas.User) +def register_user( + *, + db: Session = Depends(deps.get_db), + user_in: schemas.UserCreate, +) -> Any: + """ + Register a new user. + """ + user = crud.user.get_by_email(db, email=user_in.email) + if user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="User with this email already exists", + ) + user = crud.user.create(db, obj_in=user_in) + return user + + +@router.get("/me", response_model=schemas.User) +def read_users_me( + current_user: models.User = Depends(deps.get_current_active_user), +) -> Any: + """ + Get current user. + """ + return current_user + + +@router.post("/me", response_model=schemas.User) +def update_user_me( + *, + db: Session = Depends(deps.get_db), + password: str = None, + full_name: str = None, + current_user: models.User = Depends(deps.get_current_active_user), +) -> Any: + """ + Update own user. + """ + current_user_data = schemas.UserUpdate( + password=password, full_name=full_name + ) + user = crud.user.update(db, db_obj=current_user, obj_in=current_user_data) + return user \ No newline at end of file diff --git a/app/api/v1/endpoints/contact.py b/app/api/v1/endpoints/contact.py new file mode 100644 index 0000000..3facfcf --- /dev/null +++ b/app/api/v1/endpoints/contact.py @@ -0,0 +1,94 @@ +from typing import Any, List + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app import crud, models, schemas +from app.api import deps + +router = APIRouter() + + +@router.post("/", response_model=schemas.Contact) +def create_contact_message( + *, + db: Session = Depends(deps.get_db), + contact_in: schemas.ContactCreate, +) -> Any: + """ + Create new contact message. + """ + contact = crud.contact.create(db, obj_in=contact_in) + return contact + + +@router.get("/", response_model=List[schemas.Contact]) +def read_contact_messages( + db: Session = Depends(deps.get_db), + skip: int = 0, + limit: int = 100, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Retrieve contact messages. + """ + contacts = crud.contact.get_multi(db, skip=skip, limit=limit) + return contacts + + +@router.get("/{id}", response_model=schemas.Contact) +def read_contact_message( + *, + db: Session = Depends(deps.get_db), + id: int, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Get contact message by ID. + """ + contact = crud.contact.get(db, id=id) + if not contact: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Contact message not found", + ) + return contact + + +@router.put("/{id}/read", response_model=schemas.Contact) +def mark_contact_as_read( + *, + db: Session = Depends(deps.get_db), + id: int, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Mark a contact message as read. + """ + contact = crud.contact.mark_as_read(db, id=id) + if not contact: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Contact message not found", + ) + return contact + + +@router.delete("/{id}", response_model=schemas.Contact) +def delete_contact_message( + *, + db: Session = Depends(deps.get_db), + id: int, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Delete a contact message. + """ + contact = crud.contact.get(db, id=id) + if not contact: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Contact message not found", + ) + contact = crud.contact.remove(db, id=id) + return contact \ No newline at end of file diff --git a/app/api/v1/endpoints/health.py b/app/api/v1/endpoints/health.py new file mode 100644 index 0000000..d80bfff --- /dev/null +++ b/app/api/v1/endpoints/health.py @@ -0,0 +1,10 @@ +from fastapi import APIRouter, status + +router = APIRouter() + +@router.get("/", status_code=status.HTTP_200_OK) +async def get_health(): + """ + Health check endpoint to verify API status. + """ + return {"status": "healthy", "service": "Communications Agency API"} diff --git a/app/api/v1/endpoints/projects.py b/app/api/v1/endpoints/projects.py new file mode 100644 index 0000000..071b6f3 --- /dev/null +++ b/app/api/v1/endpoints/projects.py @@ -0,0 +1,114 @@ +from typing import Any, List + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app import crud, models, schemas +from app.api import deps + +router = APIRouter() + + +@router.get("/", response_model=List[schemas.Project]) +def read_projects( + db: Session = Depends(deps.get_db), + skip: int = 0, + limit: int = 100, +) -> Any: + """ + Retrieve projects. + """ + projects = crud.project.get_active(db, skip=skip, limit=limit) + return projects + + +@router.get("/featured", response_model=List[schemas.Project]) +def read_featured_projects( + db: Session = Depends(deps.get_db), + skip: int = 0, + limit: int = 100, +) -> Any: + """ + Retrieve featured projects. + """ + projects = crud.project.get_featured(db, skip=skip, limit=limit) + return projects + + +@router.post("/", response_model=schemas.Project) +def create_project( + *, + db: Session = Depends(deps.get_db), + project_in: schemas.ProjectCreate, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Create new project. + """ + project = crud.project.get_by_slug(db, slug=project_in.slug) + if project: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="A project with this slug already exists", + ) + project = crud.project.create(db, obj_in=project_in) + return project + + +@router.get("/{slug}", response_model=schemas.Project) +def read_project( + *, + db: Session = Depends(deps.get_db), + slug: str, +) -> Any: + """ + Get project by slug. + """ + project = crud.project.get_by_slug(db, slug=slug) + if not project: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Project not found", + ) + return project + + +@router.put("/{id}", response_model=schemas.Project) +def update_project( + *, + db: Session = Depends(deps.get_db), + id: int, + project_in: schemas.ProjectUpdate, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Update a project. + """ + project = crud.project.get(db, id=id) + if not project: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Project not found", + ) + project = crud.project.update(db, db_obj=project, obj_in=project_in) + return project + + +@router.delete("/{id}", response_model=schemas.Project) +def delete_project( + *, + db: Session = Depends(deps.get_db), + id: int, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Delete a project. + """ + project = crud.project.get(db, id=id) + if not project: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Project not found", + ) + project = crud.project.remove(db, id=id) + return project \ No newline at end of file diff --git a/app/api/v1/endpoints/services.py b/app/api/v1/endpoints/services.py new file mode 100644 index 0000000..ee72a9e --- /dev/null +++ b/app/api/v1/endpoints/services.py @@ -0,0 +1,101 @@ +from typing import Any, List + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app import crud, models, schemas +from app.api import deps + +router = APIRouter() + + +@router.get("/", response_model=List[schemas.Service]) +def read_services( + db: Session = Depends(deps.get_db), + skip: int = 0, + limit: int = 100, +) -> Any: + """ + Retrieve services. + """ + services = crud.service.get_active(db, skip=skip, limit=limit) + return services + + +@router.post("/", response_model=schemas.Service) +def create_service( + *, + db: Session = Depends(deps.get_db), + service_in: schemas.ServiceCreate, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Create new service. + """ + service = crud.service.get_by_slug(db, slug=service_in.slug) + if service: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="A service with this slug already exists", + ) + service = crud.service.create(db, obj_in=service_in) + return service + + +@router.get("/{slug}", response_model=schemas.Service) +def read_service( + *, + db: Session = Depends(deps.get_db), + slug: str, +) -> Any: + """ + Get service by slug. + """ + service = crud.service.get_by_slug(db, slug=slug) + if not service: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Service not found", + ) + return service + + +@router.put("/{id}", response_model=schemas.Service) +def update_service( + *, + db: Session = Depends(deps.get_db), + id: int, + service_in: schemas.ServiceUpdate, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Update a service. + """ + service = crud.service.get(db, id=id) + if not service: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Service not found", + ) + service = crud.service.update(db, db_obj=service, obj_in=service_in) + return service + + +@router.delete("/{id}", response_model=schemas.Service) +def delete_service( + *, + db: Session = Depends(deps.get_db), + id: int, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Delete a service. + """ + service = crud.service.get(db, id=id) + if not service: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Service not found", + ) + service = crud.service.remove(db, id=id) + return service \ No newline at end of file diff --git a/app/api/v1/endpoints/settings.py b/app/api/v1/endpoints/settings.py new file mode 100644 index 0000000..84fc2d6 --- /dev/null +++ b/app/api/v1/endpoints/settings.py @@ -0,0 +1,35 @@ +from typing import Any + +from fastapi import APIRouter, Depends +from sqlalchemy.orm import Session + +from app import crud, models, schemas +from app.api import deps + +router = APIRouter() + + +@router.get("/", response_model=schemas.Settings) +def read_settings( + db: Session = Depends(deps.get_db), +) -> Any: + """ + Retrieve site settings. + """ + settings = crud.settings.get_settings(db) + return settings + + +@router.put("/", response_model=schemas.Settings) +def update_settings( + *, + db: Session = Depends(deps.get_db), + settings_in: schemas.SettingsUpdate, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Update site settings. + """ + settings = crud.settings.get_settings(db) + settings = crud.settings.update(db, db_obj=settings, obj_in=settings_in) + return settings \ No newline at end of file diff --git a/app/api/v1/endpoints/team.py b/app/api/v1/endpoints/team.py new file mode 100644 index 0000000..978c9d1 --- /dev/null +++ b/app/api/v1/endpoints/team.py @@ -0,0 +1,95 @@ +from typing import Any, List + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app import crud, models, schemas +from app.api import deps + +router = APIRouter() + + +@router.get("/", response_model=List[schemas.TeamMember]) +def read_team_members( + db: Session = Depends(deps.get_db), + skip: int = 0, + limit: int = 100, +) -> Any: + """ + Retrieve team members. + """ + team_members = crud.team_member.get_active(db, skip=skip, limit=limit) + return team_members + + +@router.post("/", response_model=schemas.TeamMember) +def create_team_member( + *, + db: Session = Depends(deps.get_db), + team_member_in: schemas.TeamMemberCreate, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Create new team member. + """ + team_member = crud.team_member.create(db, obj_in=team_member_in) + return team_member + + +@router.get("/{id}", response_model=schemas.TeamMember) +def read_team_member( + *, + db: Session = Depends(deps.get_db), + id: int, +) -> Any: + """ + Get team member by ID. + """ + team_member = crud.team_member.get(db, id=id) + if not team_member: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Team member not found", + ) + return team_member + + +@router.put("/{id}", response_model=schemas.TeamMember) +def update_team_member( + *, + db: Session = Depends(deps.get_db), + id: int, + team_member_in: schemas.TeamMemberUpdate, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Update a team member. + """ + team_member = crud.team_member.get(db, id=id) + if not team_member: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Team member not found", + ) + team_member = crud.team_member.update(db, db_obj=team_member, obj_in=team_member_in) + return team_member + + +@router.delete("/{id}", response_model=schemas.TeamMember) +def delete_team_member( + *, + db: Session = Depends(deps.get_db), + id: int, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Delete a team member. + """ + team_member = crud.team_member.get(db, id=id) + if not team_member: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Team member not found", + ) + team_member = crud.team_member.remove(db, id=id) + return team_member \ No newline at end of file diff --git a/app/api/v1/endpoints/uploads.py b/app/api/v1/endpoints/uploads.py new file mode 100644 index 0000000..4027992 --- /dev/null +++ b/app/api/v1/endpoints/uploads.py @@ -0,0 +1,77 @@ +from typing import Any, Dict + +from fastapi import APIRouter, Depends, File, HTTPException, UploadFile, status + +from app import models +from app.api import deps +from app.utils import files + +router = APIRouter() + + +@router.post("/images/", response_model=Dict[str, str]) +async def upload_image( + *, + file: UploadFile = File(...), + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Upload an image file. + """ + try: + file_path = await files.save_image(file) + return {"file_path": file_path} + except HTTPException: + raise + except Exception as e: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=f"Error uploading file: {str(e)}", + ) + + +@router.post("/documents/", response_model=Dict[str, str]) +async def upload_document( + *, + file: UploadFile = File(...), + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Upload a document file. + """ + try: + file_path = await files.save_document(file) + return {"file_path": file_path} + except HTTPException: + raise + except Exception as e: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=f"Error uploading file: {str(e)}", + ) + + +@router.delete("/{file_path:path}", response_model=Dict[str, bool]) +async def delete_uploaded_file( + *, + file_path: str, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Delete an uploaded file. + """ + try: + success = files.delete_file(file_path) + if not success: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="File not found", + ) + return {"success": True} + except HTTPException: + raise + except Exception as e: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=f"Error deleting file: {str(e)}", + ) \ 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..5c923dc --- /dev/null +++ b/app/api/v1/endpoints/users.py @@ -0,0 +1,82 @@ +from typing import Any, List + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app import crud, models, schemas +from app.api import deps + +router = APIRouter() + + +@router.get("/", response_model=List[schemas.User]) +def read_users( + db: Session = Depends(deps.get_db), + skip: int = 0, + limit: int = 100, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Retrieve users. + """ + users = crud.user.get_multi(db, skip=skip, limit=limit) + return users + + +@router.get("/{user_id}", response_model=schemas.User) +def read_user_by_id( + user_id: int, + current_user: models.User = Depends(deps.get_current_active_superuser), + db: Session = Depends(deps.get_db), +) -> Any: + """ + Get a specific user by id. + """ + user = crud.user.get(db, id=user_id) + if not user: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="The user with this ID does not exist in the system", + ) + return user + + +@router.put("/{user_id}", response_model=schemas.User) +def update_user( + *, + db: Session = Depends(deps.get_db), + user_id: int, + user_in: schemas.UserUpdate, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Update a user. + """ + user = crud.user.get(db, id=user_id) + if not user: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="The user with this ID does not exist in the system", + ) + user = crud.user.update(db, db_obj=user, obj_in=user_in) + return user + + +@router.delete("/{user_id}", response_model=schemas.User) +def delete_user( + *, + db: Session = Depends(deps.get_db), + user_id: int, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Delete a user. + """ + user = crud.user.get(db, id=user_id) + if not user: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="The user with this ID does not exist in the system", + ) + user = crud.user.remove(db, id=user_id) + return user \ 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..a3e8ef6 --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,44 @@ +import os +from typing import List, Optional, Union + +from pydantic import AnyHttpUrl, EmailStr, field_validator +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Settings(BaseSettings): + model_config = SettingsConfigDict(env_file=".env", extra="ignore", case_sensitive=True) + + # Base API settings + API_V1_STR: str = "/api/v1" + PROJECT_NAME: str = "Communications Agency API" + PROJECT_DESCRIPTION: str = "Backend API for a Communications and Creative Agency Website" + VERSION: str = "0.1.0" + + # CORS settings + BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = [] + + @field_validator("BACKEND_CORS_ORIGINS", mode="before") + 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) + + # Security settings + SECRET_KEY: str = os.environ.get("SECRET_KEY", "supersecretkey123") + ALGORITHM: str = "HS256" + ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8 # 8 days + + # Admin user + ADMIN_EMAIL: Optional[EmailStr] = None + ADMIN_PASSWORD: Optional[str] = None + + # Database settings + DATABASE_URI: Optional[str] = None + + class Config: + case_sensitive = True + + +settings = Settings() \ No newline at end of file diff --git a/app/core/security.py b/app/core/security.py new file mode 100644 index 0000000..5061e31 --- /dev/null +++ b/app/core/security.py @@ -0,0 +1,38 @@ +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 for the given subject + """ + if expires_delta: + expire = datetime.utcnow() + expires_delta + else: + expire = datetime.utcnow() + timedelta( + minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES + ) + to_encode = {"exp": expire, "sub": str(subject)} + encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) + return encoded_jwt + + +def verify_password(plain_password: str, hashed_password: str) -> bool: + """ + Verify that a plain password matches a hashed password + """ + return pwd_context.verify(plain_password, hashed_password) + + +def get_password_hash(password: str) -> str: + """ + Hash a password + """ + 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..57b7837 --- /dev/null +++ b/app/crud/__init__.py @@ -0,0 +1,8 @@ +from app.crud.crud_contact import contact as contact +from app.crud.crud_project import project as project +from app.crud.crud_service import service as service +from app.crud.crud_settings import settings as settings +from app.crud.crud_team_member import team_member as team_member +from app.crud.crud_user import user as user + +__all__ = ["contact", "project", "service", "settings", "team_member", "user"] \ No newline at end of file diff --git a/app/crud/base.py b/app/crud/base.py new file mode 100644 index 0000000..43040ef --- /dev/null +++ b/app/crud/base.py @@ -0,0 +1,66 @@ +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.base_class 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). + + **Parameters** + + * `model`: A SQLAlchemy model class + * `schema`: A Pydantic model (schema) class + """ + 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_contact.py b/app/crud/crud_contact.py new file mode 100644 index 0000000..51aba8c --- /dev/null +++ b/app/crud/crud_contact.py @@ -0,0 +1,19 @@ +from sqlalchemy.orm import Session + +from app.crud.base import CRUDBase +from app.models.contact import Contact +from app.schemas.contact import ContactCreate, ContactUpdate + + +class CRUDContact(CRUDBase[Contact, ContactCreate, ContactUpdate]): + def mark_as_read(self, db: Session, *, id: int) -> Contact: + db_obj = self.get(db, id=id) + if db_obj: + db_obj.is_read = True + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + +contact = CRUDContact(Contact) \ No newline at end of file diff --git a/app/crud/crud_project.py b/app/crud/crud_project.py new file mode 100644 index 0000000..9cff590 --- /dev/null +++ b/app/crud/crud_project.py @@ -0,0 +1,33 @@ +from typing import List, Optional + +from sqlalchemy.orm import Session + +from app.crud.base import CRUDBase +from app.models.project import Project +from app.schemas.project import ProjectCreate, ProjectUpdate + + +class CRUDProject(CRUDBase[Project, ProjectCreate, ProjectUpdate]): + def get_by_slug(self, db: Session, *, slug: str) -> Optional[Project]: + return db.query(Project).filter(Project.slug == slug).first() + + def get_active(self, db: Session, *, skip: int = 0, limit: int = 100) -> List[Project]: + return ( + db.query(Project) + .filter(Project.is_active) + .offset(skip) + .limit(limit) + .all() + ) + + def get_featured(self, db: Session, *, skip: int = 0, limit: int = 100) -> List[Project]: + return ( + db.query(Project) + .filter(Project.is_active, Project.is_featured) + .offset(skip) + .limit(limit) + .all() + ) + + +project = CRUDProject(Project) \ No newline at end of file diff --git a/app/crud/crud_service.py b/app/crud/crud_service.py new file mode 100644 index 0000000..a744bfd --- /dev/null +++ b/app/crud/crud_service.py @@ -0,0 +1,25 @@ +from typing import List, Optional + +from sqlalchemy.orm import Session + +from app.crud.base import CRUDBase +from app.models.service import Service +from app.schemas.service import ServiceCreate, ServiceUpdate + + +class CRUDService(CRUDBase[Service, ServiceCreate, ServiceUpdate]): + def get_by_slug(self, db: Session, *, slug: str) -> Optional[Service]: + return db.query(Service).filter(Service.slug == slug).first() + + def get_active(self, db: Session, *, skip: int = 0, limit: int = 100) -> List[Service]: + return ( + db.query(Service) + .filter(Service.is_active) + .order_by(Service.order.asc()) + .offset(skip) + .limit(limit) + .all() + ) + + +service = CRUDService(Service) \ No newline at end of file diff --git a/app/crud/crud_settings.py b/app/crud/crud_settings.py new file mode 100644 index 0000000..c874760 --- /dev/null +++ b/app/crud/crud_settings.py @@ -0,0 +1,23 @@ +from sqlalchemy.orm import Session + +from app.crud.base import CRUDBase +from app.models.settings import Settings +from app.schemas.settings import SettingsCreate, SettingsUpdate + + +class CRUDSettings(CRUDBase[Settings, SettingsCreate, SettingsUpdate]): + def get_settings(self, db: Session) -> Settings: + """Get the site settings. Creates default settings if none exist.""" + settings = db.query(Settings).first() + if not settings: + settings = self.create( + db, + obj_in=SettingsCreate( + site_name="Communications Agency", + contact_email="info@example.com", + ), + ) + return settings + + +settings = CRUDSettings(Settings) \ No newline at end of file diff --git a/app/crud/crud_team_member.py b/app/crud/crud_team_member.py new file mode 100644 index 0000000..17491b6 --- /dev/null +++ b/app/crud/crud_team_member.py @@ -0,0 +1,22 @@ +from typing import List + +from sqlalchemy.orm import Session + +from app.crud.base import CRUDBase +from app.models.team_member import TeamMember +from app.schemas.team_member import TeamMemberCreate, TeamMemberUpdate + + +class CRUDTeamMember(CRUDBase[TeamMember, TeamMemberCreate, TeamMemberUpdate]): + def get_active(self, db: Session, *, skip: int = 0, limit: int = 100) -> List[TeamMember]: + return ( + db.query(TeamMember) + .filter(TeamMember.is_active) + .order_by(TeamMember.order.asc()) + .offset(skip) + .limit(limit) + .all() + ) + + +team_member = CRUDTeamMember(TeamMember) \ 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..646ba85 --- /dev/null +++ b/app/crud/crud_user.py @@ -0,0 +1,55 @@ +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 create(self, db: Session, *, obj_in: UserCreate) -> User: + db_obj = User( + email=obj_in.email, + 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( + 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, *, email: str, password: str) -> Optional[User]: + user = self.get_by_email(db, email=email) + 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/base.py b/app/db/base.py new file mode 100644 index 0000000..826f14e --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,9 @@ +# 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.contact import Contact # noqa +from app.models.project import Project # noqa +from app.models.service import Service # noqa +from app.models.settings import Settings # noqa +from app.models.team_member import TeamMember # 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..a240a3f --- /dev/null +++ b/app/db/base_class.py @@ -0,0 +1,14 @@ +from typing import Any + +from sqlalchemy.ext.declarative import declared_attr +from sqlalchemy.orm import DeclarativeBase + + +class Base(DeclarativeBase): + id: Any + __name__: str + + # Generate __tablename__ automatically + @declared_attr + def __tablename__(cls) -> str: + return cls.__name__.lower() \ No newline at end of file diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..33f280d --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,24 @@ +from pathlib import Path + +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +# Ensure storage directory exists +DB_DIR = Path("/app") / "storage" / "db" +DB_DIR.mkdir(parents=True, exist_ok=True) + +SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite" + +engine = create_engine( + SQLALCHEMY_DATABASE_URL, + connect_args={"check_same_thread": False} +) +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + + +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..85ce460 --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1,8 @@ +from app.models.contact import Contact as Contact +from app.models.project import Project as Project +from app.models.service import Service as Service +from app.models.settings import Settings as Settings +from app.models.team_member import TeamMember as TeamMember +from app.models.user import User as User + +__all__ = ["Contact", "Project", "Service", "Settings", "TeamMember", "User"] \ No newline at end of file diff --git a/app/models/contact.py b/app/models/contact.py new file mode 100644 index 0000000..accac8b --- /dev/null +++ b/app/models/contact.py @@ -0,0 +1,21 @@ +from datetime import datetime +from typing import Optional + +from sqlalchemy import Boolean, DateTime, Integer, String, Text +from sqlalchemy.orm import Mapped, mapped_column + +from app.db.base_class import Base + + +class Contact(Base): + id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True) + name: Mapped[str] = mapped_column(String(100), nullable=False) + email: Mapped[str] = mapped_column(String(100), nullable=False, index=True) + phone: Mapped[Optional[str]] = mapped_column(String(20)) + subject: Mapped[Optional[str]] = mapped_column(String(200)) + message: Mapped[str] = mapped_column(Text, nullable=False) + is_read: Mapped[bool] = mapped_column(Boolean, default=False) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow) + updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, + default=datetime.utcnow, + onupdate=datetime.utcnow) \ No newline at end of file diff --git a/app/models/project.py b/app/models/project.py new file mode 100644 index 0000000..16d2c48 --- /dev/null +++ b/app/models/project.py @@ -0,0 +1,23 @@ +from datetime import datetime +from typing import Optional + +from sqlalchemy import Boolean, DateTime, Integer, String, Text +from sqlalchemy.orm import Mapped, mapped_column + +from app.db.base_class import Base + + +class Project(Base): + id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True) + title: Mapped[str] = mapped_column(String(100), index=True, nullable=False) + slug: Mapped[str] = mapped_column(String(100), unique=True, index=True, nullable=False) + description: Mapped[str] = mapped_column(Text, nullable=False) + client: Mapped[str] = mapped_column(String(100), index=True) + completion_date: Mapped[Optional[datetime]] = mapped_column(DateTime) + featured_image: Mapped[Optional[str]] = mapped_column(String(255)) + is_featured: Mapped[bool] = mapped_column(Boolean, default=False) + is_active: Mapped[bool] = mapped_column(Boolean, default=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow) + updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, + default=datetime.utcnow, + onupdate=datetime.utcnow) \ No newline at end of file diff --git a/app/models/service.py b/app/models/service.py new file mode 100644 index 0000000..980a9e2 --- /dev/null +++ b/app/models/service.py @@ -0,0 +1,22 @@ +from datetime import datetime +from typing import Optional + +from sqlalchemy import Boolean, DateTime, Integer, String, Text +from sqlalchemy.orm import Mapped, mapped_column + +from app.db.base_class import Base + + +class Service(Base): + id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True) + title: Mapped[str] = mapped_column(String(100), index=True, nullable=False) + slug: Mapped[str] = mapped_column(String(100), unique=True, index=True, nullable=False) + description: Mapped[str] = mapped_column(Text, nullable=False) + icon: Mapped[Optional[str]] = mapped_column(String(255)) + image_path: Mapped[Optional[str]] = mapped_column(String(255)) + is_active: Mapped[bool] = mapped_column(Boolean, default=True) + order: Mapped[int] = mapped_column(Integer, default=0) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow) + updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, + default=datetime.utcnow, + onupdate=datetime.utcnow) \ No newline at end of file diff --git a/app/models/settings.py b/app/models/settings.py new file mode 100644 index 0000000..68b42e2 --- /dev/null +++ b/app/models/settings.py @@ -0,0 +1,26 @@ +from datetime import datetime +from typing import Optional + +from sqlalchemy import DateTime, Integer, String, Text +from sqlalchemy.orm import Mapped, mapped_column + +from app.db.base_class import Base + + +class Settings(Base): + id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True) + site_name: Mapped[str] = mapped_column(String(100), nullable=False) + site_description: Mapped[Optional[str]] = mapped_column(Text) + contact_email: Mapped[str] = mapped_column(String(100), nullable=False) + contact_phone: Mapped[Optional[str]] = mapped_column(String(20)) + address: Mapped[Optional[str]] = mapped_column(Text) + facebook: Mapped[Optional[str]] = mapped_column(String(255)) + twitter: Mapped[Optional[str]] = mapped_column(String(255)) + linkedin: Mapped[Optional[str]] = mapped_column(String(255)) + instagram: Mapped[Optional[str]] = mapped_column(String(255)) + logo_path: Mapped[Optional[str]] = mapped_column(String(255)) + favicon_path: Mapped[Optional[str]] = mapped_column(String(255)) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow) + updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, + default=datetime.utcnow, + onupdate=datetime.utcnow) \ No newline at end of file diff --git a/app/models/team_member.py b/app/models/team_member.py new file mode 100644 index 0000000..4ba22f7 --- /dev/null +++ b/app/models/team_member.py @@ -0,0 +1,24 @@ +from datetime import datetime +from typing import Optional + +from sqlalchemy import Boolean, DateTime, Integer, String, Text +from sqlalchemy.orm import Mapped, mapped_column + +from app.db.base_class import Base + + +class TeamMember(Base): + id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True) + name: Mapped[str] = mapped_column(String(100), nullable=False, index=True) + position: Mapped[str] = mapped_column(String(100), nullable=False) + bio: Mapped[Optional[str]] = mapped_column(Text) + photo: Mapped[Optional[str]] = mapped_column(String(255)) + email: Mapped[Optional[str]] = mapped_column(String(100)) + linkedin: Mapped[Optional[str]] = mapped_column(String(255)) + twitter: Mapped[Optional[str]] = mapped_column(String(255)) + is_active: Mapped[bool] = mapped_column(Boolean, default=True) + order: Mapped[int] = mapped_column(Integer, default=0) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow) + updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, + default=datetime.utcnow, + onupdate=datetime.utcnow) \ No newline at end of file diff --git a/app/models/user.py b/app/models/user.py new file mode 100644 index 0000000..47c854e --- /dev/null +++ b/app/models/user.py @@ -0,0 +1,20 @@ +from datetime import datetime +from typing import Optional + +from sqlalchemy import Boolean, DateTime, Integer, String +from sqlalchemy.orm import Mapped, mapped_column + +from app.db.base_class import Base + + +class User(Base): + id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True) + email: Mapped[str] = mapped_column(String, unique=True, index=True, nullable=False) + full_name: Mapped[str] = mapped_column(String, index=True) + hashed_password: Mapped[str] = mapped_column(String, nullable=False) + is_active: Mapped[bool] = mapped_column(Boolean, default=True) + is_superuser: Mapped[bool] = mapped_column(Boolean, default=False) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow) + updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, + default=datetime.utcnow, + onupdate=datetime.utcnow) \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..f4b8e6f --- /dev/null +++ b/app/schemas/__init__.py @@ -0,0 +1,17 @@ +from app.schemas.contact import Contact as Contact, ContactCreate as ContactCreate, ContactUpdate as ContactUpdate +from app.schemas.project import Project as Project, ProjectCreate as ProjectCreate, ProjectUpdate as ProjectUpdate +from app.schemas.service import Service as Service, ServiceCreate as ServiceCreate, ServiceUpdate as ServiceUpdate +from app.schemas.settings import Settings as Settings, SettingsCreate as SettingsCreate, SettingsUpdate as SettingsUpdate +from app.schemas.team_member import TeamMember as TeamMember, TeamMemberCreate as TeamMemberCreate, TeamMemberUpdate as TeamMemberUpdate +from app.schemas.token import Token as Token, TokenPayload as TokenPayload +from app.schemas.user import User as User, UserCreate as UserCreate, UserUpdate as UserUpdate + +__all__ = [ + "Contact", "ContactCreate", "ContactUpdate", + "Project", "ProjectCreate", "ProjectUpdate", + "Service", "ServiceCreate", "ServiceUpdate", + "Settings", "SettingsCreate", "SettingsUpdate", + "TeamMember", "TeamMemberCreate", "TeamMemberUpdate", + "Token", "TokenPayload", + "User", "UserCreate", "UserUpdate", +] \ No newline at end of file diff --git a/app/schemas/contact.py b/app/schemas/contact.py new file mode 100644 index 0000000..8c4d9eb --- /dev/null +++ b/app/schemas/contact.py @@ -0,0 +1,43 @@ +from datetime import datetime +from typing import Optional + +from pydantic import BaseModel, EmailStr, Field + + +# Shared properties +class ContactBase(BaseModel): + name: Optional[str] = None + email: Optional[EmailStr] = None + phone: Optional[str] = None + subject: Optional[str] = None + message: Optional[str] = None + is_read: Optional[bool] = False + + +# Properties to receive via API on creation +class ContactCreate(ContactBase): + name: str = Field(..., min_length=1, max_length=100) + email: EmailStr + message: str + + +# Properties to receive via API on update +class ContactUpdate(ContactBase): + pass + + +class ContactInDBBase(ContactBase): + id: int + name: str + email: EmailStr + message: str + created_at: datetime + updated_at: Optional[datetime] = None + + class Config: + from_attributes = True + + +# Additional properties to return via API +class Contact(ContactInDBBase): + pass \ No newline at end of file diff --git a/app/schemas/project.py b/app/schemas/project.py new file mode 100644 index 0000000..763317e --- /dev/null +++ b/app/schemas/project.py @@ -0,0 +1,47 @@ +from datetime import datetime +from typing import Optional + +from pydantic import BaseModel, Field + + +# Shared properties +class ProjectBase(BaseModel): + title: Optional[str] = None + slug: Optional[str] = None + description: Optional[str] = None + client: Optional[str] = None + completion_date: Optional[datetime] = None + featured_image: Optional[str] = None + is_featured: Optional[bool] = False + is_active: Optional[bool] = True + + +# Properties to receive via API on creation +class ProjectCreate(ProjectBase): + title: str = Field(..., min_length=1, max_length=100) + slug: str = Field(..., min_length=1, max_length=100) + description: str + client: str = Field(..., min_length=1, max_length=100) + + +# Properties to receive via API on update +class ProjectUpdate(ProjectBase): + pass + + +class ProjectInDBBase(ProjectBase): + id: int + title: str + slug: str + description: str + client: str + created_at: datetime + updated_at: Optional[datetime] = None + + class Config: + from_attributes = True + + +# Additional properties to return via API +class Project(ProjectInDBBase): + pass \ No newline at end of file diff --git a/app/schemas/service.py b/app/schemas/service.py new file mode 100644 index 0000000..87d61ce --- /dev/null +++ b/app/schemas/service.py @@ -0,0 +1,44 @@ +from datetime import datetime +from typing import Optional + +from pydantic import BaseModel, Field + + +# Shared properties +class ServiceBase(BaseModel): + title: Optional[str] = None + slug: Optional[str] = None + description: Optional[str] = None + icon: Optional[str] = None + image_path: Optional[str] = None + is_active: Optional[bool] = True + order: Optional[int] = 0 + + +# Properties to receive via API on creation +class ServiceCreate(ServiceBase): + title: str = Field(..., min_length=1, max_length=100) + slug: str = Field(..., min_length=1, max_length=100) + description: str + + +# Properties to receive via API on update +class ServiceUpdate(ServiceBase): + pass + + +class ServiceInDBBase(ServiceBase): + id: int + title: str + slug: str + description: str + created_at: datetime + updated_at: Optional[datetime] = None + + class Config: + from_attributes = True + + +# Additional properties to return via API +class Service(ServiceInDBBase): + pass \ No newline at end of file diff --git a/app/schemas/settings.py b/app/schemas/settings.py new file mode 100644 index 0000000..f59a698 --- /dev/null +++ b/app/schemas/settings.py @@ -0,0 +1,46 @@ +from datetime import datetime +from typing import Optional + +from pydantic import BaseModel, EmailStr, Field + + +# Shared properties +class SettingsBase(BaseModel): + site_name: Optional[str] = None + site_description: Optional[str] = None + contact_email: Optional[EmailStr] = None + contact_phone: Optional[str] = None + address: Optional[str] = None + facebook: Optional[str] = None + twitter: Optional[str] = None + linkedin: Optional[str] = None + instagram: Optional[str] = None + logo_path: Optional[str] = None + favicon_path: Optional[str] = None + + +# Properties to receive via API on creation +class SettingsCreate(SettingsBase): + site_name: str = Field(..., min_length=1, max_length=100) + contact_email: EmailStr + + +# Properties to receive via API on update +class SettingsUpdate(SettingsBase): + pass + + +class SettingsInDBBase(SettingsBase): + id: int + site_name: str + contact_email: EmailStr + created_at: datetime + updated_at: Optional[datetime] = None + + class Config: + from_attributes = True + + +# Additional properties to return via API +class Settings(SettingsInDBBase): + pass \ No newline at end of file diff --git a/app/schemas/team_member.py b/app/schemas/team_member.py new file mode 100644 index 0000000..1211402 --- /dev/null +++ b/app/schemas/team_member.py @@ -0,0 +1,44 @@ +from datetime import datetime +from typing import Optional + +from pydantic import BaseModel, EmailStr, Field + + +# Shared properties +class TeamMemberBase(BaseModel): + name: Optional[str] = None + position: Optional[str] = None + bio: Optional[str] = None + photo: Optional[str] = None + email: Optional[EmailStr] = None + linkedin: Optional[str] = None + twitter: Optional[str] = None + is_active: Optional[bool] = True + order: Optional[int] = 0 + + +# Properties to receive via API on creation +class TeamMemberCreate(TeamMemberBase): + name: str = Field(..., min_length=1, max_length=100) + position: str = Field(..., min_length=1, max_length=100) + + +# Properties to receive via API on update +class TeamMemberUpdate(TeamMemberBase): + pass + + +class TeamMemberInDBBase(TeamMemberBase): + id: int + name: str + position: str + created_at: datetime + updated_at: Optional[datetime] = None + + class Config: + from_attributes = True + + +# Additional properties to return via API +class TeamMember(TeamMemberInDBBase): + 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..69541e2 --- /dev/null +++ b/app/schemas/token.py @@ -0,0 +1,12 @@ +from typing import Optional + +from pydantic import BaseModel + + +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..44bacd1 --- /dev/null +++ b/app/schemas/user.py @@ -0,0 +1,43 @@ +from datetime import datetime +from typing import Optional + +from pydantic import BaseModel, EmailStr, Field + + +# Shared properties +class UserBase(BaseModel): + email: Optional[EmailStr] = None + full_name: Optional[str] = None + is_active: Optional[bool] = True + is_superuser: bool = False + + +# Properties to receive via API on creation +class UserCreate(UserBase): + email: EmailStr + password: str = Field(..., min_length=8) + + +# Properties to receive via API on update +class UserUpdate(UserBase): + password: Optional[str] = Field(None, min_length=8) + + +class UserInDBBase(UserBase): + id: int + email: EmailStr + created_at: datetime + updated_at: Optional[datetime] = None + + class Config: + from_attributes = True + + +# Additional properties to return via API +class User(UserInDBBase): + pass + + +# Additional properties stored in DB but not returned +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/app/utils/files.py b/app/utils/files.py new file mode 100644 index 0000000..e8c45c6 --- /dev/null +++ b/app/utils/files.py @@ -0,0 +1,95 @@ +import os +import shutil +import uuid +from pathlib import Path +from typing import List + +from fastapi import HTTPException, UploadFile, status + +# Define allowed extensions +ALLOWED_IMAGE_EXTENSIONS = {"png", "jpg", "jpeg", "gif", "webp"} +ALLOWED_DOCUMENT_EXTENSIONS = {"pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "txt"} + +# Define storage paths +STORAGE_DIR = Path("/app") / "storage" +IMAGES_DIR = STORAGE_DIR / "images" +DOCUMENTS_DIR = STORAGE_DIR / "documents" + +# Create directories if they don't exist +IMAGES_DIR.mkdir(parents=True, exist_ok=True) +DOCUMENTS_DIR.mkdir(parents=True, exist_ok=True) + + +def validate_file_extension(filename: str, allowed_extensions: List[str]) -> bool: + """ + Validate if the file extension is allowed + """ + return filename.split(".")[-1].lower() in allowed_extensions + + +async def save_upload_file( + upload_file: UploadFile, destination: Path, allowed_extensions: List[str] +) -> str: + """ + Save an uploaded file to the destination directory + """ + if not validate_file_extension(upload_file.filename, allowed_extensions): + valid_extensions = ", ".join(allowed_extensions) + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"File extension not allowed. Allowed extensions: {valid_extensions}", + ) + + # Generate a unique filename to prevent overwriting + file_extension = upload_file.filename.split(".")[-1].lower() + new_filename = f"{uuid.uuid4()}.{file_extension}" + file_path = destination / new_filename + + # Write file + with open(file_path, "wb") as buffer: + shutil.copyfileobj(upload_file.file, buffer) + + return str(file_path.relative_to(STORAGE_DIR)) + + +async def save_image(upload_file: UploadFile) -> str: + """ + Save an uploaded image + """ + return await save_upload_file(upload_file, IMAGES_DIR, ALLOWED_IMAGE_EXTENSIONS) + + +async def save_document(upload_file: UploadFile) -> str: + """ + Save an uploaded document + """ + return await save_upload_file(upload_file, DOCUMENTS_DIR, ALLOWED_DOCUMENT_EXTENSIONS) + + +def delete_file(file_path: str) -> bool: + """ + Delete a file from storage + """ + # Ensure the file path is relative to the storage directory + if file_path.startswith("/"): + file_path = file_path.lstrip("/") + + full_path = STORAGE_DIR / file_path + + # Security check: ensure the file is within the storage directory + try: + if not full_path.resolve().is_relative_to(STORAGE_DIR.resolve()): + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Invalid file path", + ) + except ValueError: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Invalid file path", + ) + + if full_path.exists(): + os.remove(full_path) + return True + return False \ No newline at end of file diff --git a/app/utils/init_db.py b/app/utils/init_db.py new file mode 100644 index 0000000..0d809da --- /dev/null +++ b/app/utils/init_db.py @@ -0,0 +1,49 @@ +import logging + + +from app import crud, schemas +from app.core.config import settings +from app.db.session import SessionLocal + +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + + +def init_db() -> None: + """ + Initialize the database with a superuser if needed. + """ + db = SessionLocal() + try: + # Check if admin email and password are set + if settings.ADMIN_EMAIL and settings.ADMIN_PASSWORD: + # Check if superuser exists + user = crud.user.get_by_email(db, email=settings.ADMIN_EMAIL) + if not user: + user_in = schemas.UserCreate( + email=settings.ADMIN_EMAIL, + password=settings.ADMIN_PASSWORD, + full_name="Admin", + is_superuser=True, + ) + user = crud.user.create(db, obj_in=user_in) + logger.info(f"Admin user created with email: {settings.ADMIN_EMAIL}") + else: + logger.info(f"Admin user already exists with email: {settings.ADMIN_EMAIL}") + else: + logger.warning( + "Admin user not created. " + "Set ADMIN_EMAIL and ADMIN_PASSWORD environment variables." + ) + + # Initialize settings if they don't exist + settings_obj = crud.settings.get_settings(db) + logger.info(f"Settings initialized with site name: {settings_obj.site_name}") + finally: + db.close() + + +if __name__ == "__main__": + logger.info("Creating initial data") + init_db() + logger.info("Initial data created") \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..6495bb3 --- /dev/null +++ b/main.py @@ -0,0 +1,78 @@ +import uvicorn +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from fastapi.openapi.utils import get_openapi + +from app.api.v1.api import api_router +from app.core.config import settings +from app.utils.init_db import init_db + +app = FastAPI( + title=settings.PROJECT_NAME, + description=settings.PROJECT_DESCRIPTION, + version=settings.VERSION, + docs_url="/docs", + redoc_url="/redoc", + openapi_url="/openapi.json", +) + +# Set all CORS enabled origins +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +app.include_router(api_router, prefix=settings.API_V1_STR) + + +@app.get("/", tags=["Root"]) +async def root(): + """ + Root endpoint returning basic information about the API. + """ + return { + "title": settings.PROJECT_NAME, + "description": settings.PROJECT_DESCRIPTION, + "version": settings.VERSION, + "docs_url": "/docs", + "health_check": "/health" + } + + +@app.get("/health", tags=["Health"]) +async def health_check(): + """ + Health check endpoint to verify service status. + """ + return {"status": "healthy"} + + +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, + ) + app.openapi_schema = openapi_schema + return app.openapi_schema + + +app.openapi = custom_openapi + + +@app.on_event("startup") +def startup_event(): + """ + Initialize the database with initial data on startup. + """ + init_db() + + +if __name__ == "__main__": + uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..61111ec --- /dev/null +++ b/migrations/README @@ -0,0 +1,14 @@ +Generic single-database configuration with SQLite. + +This is a generic migration management setup for SQLAlchemy using Alembic. +Changes to models in app/models/ should be reflected in migrations by running: + +``` +alembic revision --autogenerate -m "description of changes" +``` + +To apply migrations to the database, run: + +``` +alembic upgrade head +``` \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..bc596f7 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,90 @@ +from logging.config import fileConfig + +from alembic import context +from sqlalchemy import engine_from_config, pool + +# Add the parent directory to the Python path +import sys +from pathlib import Path + +sys.path.append(str(Path(__file__).parent.parent)) + +# Import the SQLAlchemy Base +from app.db.base import Base # noqa + +# 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. +fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +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(): + """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"}, + render_as_batch=True, # Key configuration for SQLite + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """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: + # Check if we're using SQLite + 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() \ No newline at end of file diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..1e4564e --- /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(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} \ No newline at end of file diff --git a/migrations/versions/initial_migration.py b/migrations/versions/initial_migration.py new file mode 100644 index 0000000..b914d8b --- /dev/null +++ b/migrations/versions/initial_migration.py @@ -0,0 +1,154 @@ +"""initial migration + +Revision ID: 001 +Revises: +Create Date: 2023-11-08 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '001' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('contact', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(length=100), nullable=False), + sa.Column('email', sa.String(length=100), nullable=False), + sa.Column('phone', sa.String(length=20), nullable=True), + sa.Column('subject', sa.String(length=200), nullable=True), + sa.Column('message', sa.Text(), nullable=False), + sa.Column('is_read', sa.Boolean(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_contact_email'), 'contact', ['email'], unique=False) + op.create_index(op.f('ix_contact_id'), 'contact', ['id'], unique=False) + + op.create_table('project', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(length=100), nullable=False), + sa.Column('slug', sa.String(length=100), nullable=False), + sa.Column('description', sa.Text(), nullable=False), + sa.Column('client', sa.String(length=100), nullable=True), + sa.Column('completion_date', sa.DateTime(), nullable=True), + sa.Column('featured_image', sa.String(length=255), nullable=True), + sa.Column('is_featured', sa.Boolean(), nullable=True), + sa.Column('is_active', sa.Boolean(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_project_client'), 'project', ['client'], unique=False) + op.create_index(op.f('ix_project_id'), 'project', ['id'], unique=False) + op.create_index(op.f('ix_project_slug'), 'project', ['slug'], unique=True) + op.create_index(op.f('ix_project_title'), 'project', ['title'], unique=False) + + op.create_table('service', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(length=100), nullable=False), + sa.Column('slug', sa.String(length=100), nullable=False), + sa.Column('description', sa.Text(), nullable=False), + sa.Column('icon', sa.String(length=255), nullable=True), + sa.Column('image_path', sa.String(length=255), nullable=True), + sa.Column('is_active', sa.Boolean(), nullable=True), + sa.Column('order', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_service_id'), 'service', ['id'], unique=False) + op.create_index(op.f('ix_service_slug'), 'service', ['slug'], unique=True) + op.create_index(op.f('ix_service_title'), 'service', ['title'], unique=False) + + op.create_table('settings', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('site_name', sa.String(length=100), nullable=False), + sa.Column('site_description', sa.Text(), nullable=True), + sa.Column('contact_email', sa.String(length=100), nullable=False), + sa.Column('contact_phone', sa.String(length=20), nullable=True), + sa.Column('address', sa.Text(), nullable=True), + sa.Column('facebook', sa.String(length=255), nullable=True), + sa.Column('twitter', sa.String(length=255), nullable=True), + sa.Column('linkedin', sa.String(length=255), nullable=True), + sa.Column('instagram', sa.String(length=255), nullable=True), + sa.Column('logo_path', sa.String(length=255), nullable=True), + sa.Column('favicon_path', sa.String(length=255), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_settings_id'), 'settings', ['id'], unique=False) + + op.create_table('team_member', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(length=100), nullable=False), + sa.Column('position', sa.String(length=100), nullable=False), + sa.Column('bio', sa.Text(), nullable=True), + sa.Column('photo', sa.String(length=255), nullable=True), + sa.Column('email', sa.String(length=100), nullable=True), + sa.Column('linkedin', sa.String(length=255), nullable=True), + sa.Column('twitter', sa.String(length=255), nullable=True), + sa.Column('is_active', sa.Boolean(), nullable=True), + sa.Column('order', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_team_member_id'), 'team_member', ['id'], unique=False) + op.create_index(op.f('ix_team_member_name'), 'team_member', ['name'], unique=False) + + op.create_table('user', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('email', sa.String(), nullable=False), + sa.Column('full_name', sa.String(), nullable=True), + sa.Column('hashed_password', sa.String(), nullable=False), + sa.Column('is_active', sa.Boolean(), nullable=True), + sa.Column('is_superuser', sa.Boolean(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True) + op.create_index(op.f('ix_user_full_name'), 'user', ['full_name'], unique=False) + op.create_index(op.f('ix_user_id'), 'user', ['id'], unique=False) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_user_id'), table_name='user') + op.drop_index(op.f('ix_user_full_name'), table_name='user') + op.drop_index(op.f('ix_user_email'), table_name='user') + op.drop_table('user') + + op.drop_index(op.f('ix_team_member_name'), table_name='team_member') + op.drop_index(op.f('ix_team_member_id'), table_name='team_member') + op.drop_table('team_member') + + op.drop_index(op.f('ix_settings_id'), table_name='settings') + op.drop_table('settings') + + op.drop_index(op.f('ix_service_title'), table_name='service') + op.drop_index(op.f('ix_service_slug'), table_name='service') + op.drop_index(op.f('ix_service_id'), table_name='service') + op.drop_table('service') + + op.drop_index(op.f('ix_project_title'), table_name='project') + op.drop_index(op.f('ix_project_slug'), table_name='project') + op.drop_index(op.f('ix_project_id'), table_name='project') + op.drop_index(op.f('ix_project_client'), table_name='project') + op.drop_table('project') + + op.drop_index(op.f('ix_contact_id'), table_name='contact') + op.drop_index(op.f('ix_contact_email'), table_name='contact') + op.drop_table('contact') + # ### end Alembic commands ### \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..bd97032 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,15 @@ +fastapi==0.104.0 +uvicorn==0.23.2 +sqlalchemy==2.0.22 +alembic==1.12.0 +pydantic==2.4.2 +pydantic-settings==2.0.3 +python-jose==3.3.0 +passlib==1.7.4 +bcrypt==4.0.1 +python-multipart==0.0.6 +email-validator==2.0.0 +httpx==0.25.0 +ruff==0.0.292 +python-dotenv==1.0.0 +aiofiles==23.2.1 \ No newline at end of file