Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,46 @@ apps/ia/.env
node_modules/
apps/web/node_modules/
apps/web/.next/
.next/

# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# FastAPI
.env
.venv
venv/
ENV/
env/
.pytest_cache/

# Database
*.db
*.sqlite3
alembic/versions/

# IDE
.vscode/
.idea/
*.swp
*.swo
22 changes: 22 additions & 0 deletions apps/ia/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Application Configuration
APP_NAME=La Vida Luca API
DEBUG=true

# Security
SECRET_KEY=your-secret-key-change-in-production-please-use-a-secure-random-key
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

# CORS
ALLOWED_ORIGINS=["http://localhost:3000", "https://la-vida-luca.vercel.app"]
ALLOWED_HOSTS=["localhost", "127.0.0.1", "*.render.com"]

# Database
DATABASE_URL=postgresql://user:password@localhost/lavidaluca
ASYNC_DATABASE_URL=postgresql+asyncpg://user:password@localhost/lavidaluca
DATABASE_POOL_SIZE=5
DATABASE_MAX_OVERFLOW=10

# Rate Limiting
RATE_LIMIT_REQUESTS=100
RATE_LIMIT_WINDOW=60
101 changes: 101 additions & 0 deletions apps/ia/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# La Vida Luca - FastAPI Backend

API backend pour la plateforme La Vida Luca - Formation des jeunes en MFR, développement d'une agriculture nouvelle et insertion sociale.

## Fonctionnalités

### Sécurité et Middleware
- ✅ Gestion d'erreurs centralisée
- ✅ Configuration CORS
- ✅ Middleware de sécurité (TrustedHost)
- ✅ Rate limiting
- ✅ Authentification JWT
- ✅ Validation des tokens

### API Endpoints
- ✅ Authentification (register, login, refresh token)
- ✅ Gestion des activités
- ✅ Protection par JWT
- ✅ Documentation automatique (Swagger/OpenAPI)

### Base de données
- ✅ Modèles SQLAlchemy optimisés
- ✅ Configuration Alembic pour les migrations
- ✅ Pooling de connexions
- ✅ Support PostgreSQL avec asyncpg

### Tests
- ✅ Configuration pytest
- ✅ Tests unitaires (auth, middleware)
- ✅ Tests d'intégration (API endpoints)
- ✅ Couverture de code configurée

## Installation

1. Installer les dépendances:
```bash
pip install -r requirements.txt
```

2. Configurer les variables d'environnement:
```bash
cp .env.example .env
# Éditer .env avec vos paramètres
```

3. Initialiser la base de données:
```bash
alembic init
alembic revision --autogenerate -m "Initial migration"
alembic upgrade head
```

## Utilisation

### Développement
```bash
python main.py
```

### Production
```bash
uvicorn main:app --host 0.0.0.0 --port 8000
```

### Tests
```bash
# Tests unitaires
pytest tests/test_auth.py -v

# Tests d'intégration
pytest tests/test_integration.py -v

# Tous les tests avec couverture
pytest --cov=app
```

## Documentation API

Une fois l'application lancée:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc

## Configuration

Voir `.env.example` pour les variables d'environnement disponibles:
- Configuration de base de données
- Clés de sécurité JWT
- Paramètres CORS
- Limites de taux

## Architecture

```
app/
├── auth/ # Service d'authentification JWT
├── api/endpoints/ # Endpoints API
├── core/ # Configuration
├── db/ # Configuration base de données
├── middleware/ # Middleware personnalisés
└── models/ # Modèles SQLAlchemy
```
98 changes: 98 additions & 0 deletions apps/ia/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts
script_location = alembic

# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s

# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .

# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =

# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version 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

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

sqlalchemy.url = postgresql://user:password@localhost/lavidaluca


[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
82 changes: 82 additions & 0 deletions apps/ia/alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
from app.models.models import Base
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 get_url():
from app.core.config import settings
return settings.DATABASE_URL

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 = get_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.

"""
configuration = config.get_section(config.config_ini_section)
configuration["sqlalchemy.url"] = get_url()
connectable = engine_from_config(
configuration,
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)

with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)

with context.begin_transaction():
context.run_migrations()


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
24 changes: 24 additions & 0 deletions apps/ia/alembic/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}

"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}

# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}


def upgrade() -> None:
${upgrades if upgrades else "pass"}


def downgrade() -> None:
${downgrades if downgrades else "pass"}
Empty file added apps/ia/app/__init__.py
Empty file.
Empty file added apps/ia/app/api/__init__.py
Empty file.
Empty file.
Loading