Étape 7 : authentification par lien magique + JWT + rôles
- app/auth/ : jetons (lien magique aléatoire haché SHA-256, JWT HS256), dépendances get_current_account / current_account_in_edition / require_roles + require_coordinator / require_staff, et ensure_can_write_position/_shift - Endpoints app/api/auth.py : POST .../auth/magic-link (202 constant, pas de divulgation), POST .../auth/verify (JWT, jeton à usage unique), GET /auth/me - Envoi d'email stubé : le lien est journalisé (logger app.auth, identifiants seulement, aucune donnée nominative) - app/api/accounts.py : CRUD des comptes réservé à la COORDINATION - Rôles appliqués sur toute l'API : COORDINATION accès complet ; RÉFÉRENT lecture globale + écriture sur ses seuls postes/créneaux/affectations ; BÉNÉVOLE sa fiche et ses affectations, aucune écriture - imports.py aligné sur la dépendance get_edition (404 avant 403) - Secret JWT porté à >= 32 octets (config, .env.example, docker-compose) - seed : crée un compte VOLUNTEER pour chaque bénévole avec email (104 comptes) - conftest : fixtures make_account / coordinator / as_account / raw_client ; la suite existante s'exécute en COORDINATION - 13 tests d'authentification + de rôles ; 119 tests au total ; alembic check toujours vert (Account / MagicLinkToken déjà dans la migration 0001) Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017uUsRg7XzopkCPWimwg9ZM
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
c9dda65361
commit
ced922f785
@@ -0,0 +1,78 @@
|
||||
"""Gestion des comptes par la coordination (créer un référent, un bénévole
|
||||
connecté…)."""
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response, status
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from app.api._common import owned_or_404
|
||||
from app.api.deps import get_edition
|
||||
from app.api.schemas import AccountCreate, AccountRead
|
||||
from app.auth.deps import require_coordinator
|
||||
from app.db import get_session
|
||||
from app.models import Account, Edition, Volunteer
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/editions/{edition_id}/accounts", tags=["accounts"]
|
||||
)
|
||||
|
||||
|
||||
@router.post("", response_model=AccountRead, status_code=status.HTTP_201_CREATED)
|
||||
def create_account(
|
||||
payload: AccountCreate,
|
||||
edition: Edition = Depends(get_edition),
|
||||
_guard: Account = Depends(require_coordinator),
|
||||
session: Session = Depends(get_session),
|
||||
) -> Account:
|
||||
if payload.volunteer_id is not None:
|
||||
volunteer = session.get(Volunteer, payload.volunteer_id)
|
||||
if volunteer is None or volunteer.edition_id != edition.id:
|
||||
raise HTTPException(
|
||||
status_code=422, detail={"code": "account.volunteer_wrong_edition"}
|
||||
)
|
||||
account = Account(
|
||||
edition_id=edition.id,
|
||||
email=payload.email.strip(),
|
||||
role=payload.role,
|
||||
volunteer_id=payload.volunteer_id,
|
||||
)
|
||||
session.add(account)
|
||||
try:
|
||||
session.commit()
|
||||
except IntegrityError as exc:
|
||||
session.rollback()
|
||||
raise HTTPException(
|
||||
status_code=409, detail={"code": "account.duplicate"}
|
||||
) from exc
|
||||
session.refresh(account)
|
||||
return account
|
||||
|
||||
|
||||
@router.get("", response_model=list[AccountRead])
|
||||
def list_accounts(
|
||||
edition: Edition = Depends(get_edition),
|
||||
_guard: Account = Depends(require_coordinator),
|
||||
session: Session = Depends(get_session),
|
||||
) -> list[Account]:
|
||||
return list(
|
||||
session.exec(
|
||||
select(Account)
|
||||
.where(Account.edition_id == edition.id)
|
||||
.order_by(Account.email)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/{account_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_account(
|
||||
account_id: uuid.UUID,
|
||||
edition: Edition = Depends(get_edition),
|
||||
_guard: Account = Depends(require_coordinator),
|
||||
session: Session = Depends(get_session),
|
||||
) -> Response:
|
||||
account = owned_or_404(session.get(Account, account_id), edition.id)
|
||||
session.delete(account)
|
||||
session.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -17,11 +17,18 @@ from app.api.schemas import (
|
||||
AssignmentValidateResult,
|
||||
AssignmentWriteResult,
|
||||
)
|
||||
from app.auth.deps import (
|
||||
current_account_in_edition,
|
||||
ensure_can_write_shift,
|
||||
require_staff,
|
||||
)
|
||||
from app.db import get_session
|
||||
from app.models import (
|
||||
ACTIVE_ASSIGNMENT_STATUSES,
|
||||
Account,
|
||||
Assignment,
|
||||
Edition,
|
||||
Role,
|
||||
Shift,
|
||||
Volunteer,
|
||||
)
|
||||
@@ -50,12 +57,25 @@ def _pair_or_422(
|
||||
return volunteer, shift
|
||||
|
||||
|
||||
def _forbidden() -> HTTPException:
|
||||
return HTTPException(status_code=403, detail={"code": "error.forbidden"})
|
||||
|
||||
|
||||
def _ensure_can_read(account: Account, volunteer_id: uuid.UUID) -> None:
|
||||
if account.role in (Role.COORDINATOR, Role.LEAD):
|
||||
return
|
||||
if account.volunteer_id == volunteer_id:
|
||||
return
|
||||
raise _forbidden()
|
||||
|
||||
|
||||
@router.post(
|
||||
"/validate", response_model=AssignmentValidateResult, tags=["assignments"]
|
||||
)
|
||||
def validate_assignment(
|
||||
payload: AssignmentValidateRequest,
|
||||
edition: Edition = Depends(get_edition),
|
||||
_guard: Account = Depends(require_staff),
|
||||
session: Session = Depends(get_session),
|
||||
) -> AssignmentValidateResult:
|
||||
volunteer, shift = _pair_or_422(
|
||||
@@ -77,11 +97,13 @@ def validate_assignment(
|
||||
def create_assignment(
|
||||
payload: AssignmentCreate,
|
||||
edition: Edition = Depends(get_edition),
|
||||
account: Account = Depends(current_account_in_edition),
|
||||
session: Session = Depends(get_session),
|
||||
) -> AssignmentWriteResult:
|
||||
volunteer, shift = _pair_or_422(
|
||||
session, edition.id, payload.volunteer_id, payload.shift_id
|
||||
)
|
||||
ensure_can_write_shift(account, session, shift)
|
||||
existing = session.exec(
|
||||
select(Assignment)
|
||||
.where(Assignment.volunteer_id == volunteer.id)
|
||||
@@ -132,8 +154,14 @@ def list_assignments(
|
||||
volunteer_id: uuid.UUID | None = None,
|
||||
shift_id: uuid.UUID | None = None,
|
||||
edition: Edition = Depends(get_edition),
|
||||
account: Account = Depends(current_account_in_edition),
|
||||
session: Session = Depends(get_session),
|
||||
) -> list[Assignment]:
|
||||
if account.role is Role.VOLUNTEER:
|
||||
# Un bénévole ne voit que ses propres affectations.
|
||||
if volunteer_id not in (None, account.volunteer_id):
|
||||
raise _forbidden()
|
||||
volunteer_id = account.volunteer_id
|
||||
stmt = select(Assignment).where(Assignment.edition_id == edition.id)
|
||||
if volunteer_id is not None:
|
||||
stmt = stmt.where(Assignment.volunteer_id == volunteer_id)
|
||||
@@ -146,9 +174,14 @@ def list_assignments(
|
||||
def get_assignment(
|
||||
assignment_id: uuid.UUID,
|
||||
edition: Edition = Depends(get_edition),
|
||||
account: Account = Depends(current_account_in_edition),
|
||||
session: Session = Depends(get_session),
|
||||
) -> Assignment:
|
||||
return owned_or_404(session.get(Assignment, assignment_id), edition.id)
|
||||
assignment = owned_or_404(
|
||||
session.get(Assignment, assignment_id), edition.id
|
||||
)
|
||||
_ensure_can_read(account, assignment.volunteer_id)
|
||||
return assignment
|
||||
|
||||
|
||||
@router.patch("/{assignment_id}", response_model=AssignmentWriteResult)
|
||||
@@ -156,11 +189,15 @@ def update_assignment(
|
||||
assignment_id: uuid.UUID,
|
||||
payload: AssignmentUpdate,
|
||||
edition: Edition = Depends(get_edition),
|
||||
account: Account = Depends(current_account_in_edition),
|
||||
session: Session = Depends(get_session),
|
||||
) -> AssignmentWriteResult:
|
||||
assignment = owned_or_404(
|
||||
session.get(Assignment, assignment_id), edition.id
|
||||
)
|
||||
ensure_can_write_shift(
|
||||
account, session, session.get(Shift, assignment.shift_id)
|
||||
)
|
||||
changes = payload.model_dump(exclude_unset=True)
|
||||
for field, value in changes.items():
|
||||
setattr(assignment, field, value)
|
||||
@@ -197,11 +234,15 @@ def update_assignment(
|
||||
def delete_assignment(
|
||||
assignment_id: uuid.UUID,
|
||||
edition: Edition = Depends(get_edition),
|
||||
account: Account = Depends(current_account_in_edition),
|
||||
session: Session = Depends(get_session),
|
||||
) -> Response:
|
||||
assignment = owned_or_404(
|
||||
session.get(Assignment, assignment_id), edition.id
|
||||
)
|
||||
ensure_can_write_shift(
|
||||
account, session, session.get(Shift, assignment.shift_id)
|
||||
)
|
||||
session.delete(assignment)
|
||||
session.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Endpoints d'authentification : lien magique, vérification, profil courant."""
|
||||
|
||||
import datetime as dt
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy import func
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from app.api.schemas import (
|
||||
AccountRead,
|
||||
MagicLinkRequest,
|
||||
TokenResponse,
|
||||
VerifyRequest,
|
||||
)
|
||||
from app.auth.deps import get_current_account
|
||||
from app.auth.tokens import create_access_token, hash_token, new_raw_token
|
||||
from app.config import get_settings
|
||||
from app.db import get_session
|
||||
from app.models import Account, MagicLinkToken, local_now
|
||||
|
||||
router = APIRouter(tags=["auth"])
|
||||
logger = logging.getLogger("app.auth")
|
||||
|
||||
|
||||
@router.post(
|
||||
"/editions/{edition_id}/auth/magic-link",
|
||||
status_code=status.HTTP_202_ACCEPTED,
|
||||
)
|
||||
def request_magic_link(
|
||||
edition_id: uuid.UUID,
|
||||
payload: MagicLinkRequest,
|
||||
session: Session = Depends(get_session),
|
||||
) -> dict[str, str]:
|
||||
"""Émet un lien magique si un compte correspond. Réponse identique dans
|
||||
tous les cas (pas de divulgation de l'existence d'un compte)."""
|
||||
account = session.exec(
|
||||
select(Account)
|
||||
.where(Account.edition_id == edition_id)
|
||||
.where(func.lower(Account.email) == payload.email.strip().lower())
|
||||
).first()
|
||||
if account is not None:
|
||||
raw = new_raw_token()
|
||||
token = MagicLinkToken(
|
||||
account_id=account.id,
|
||||
token_hash=hash_token(raw),
|
||||
expires_at=local_now()
|
||||
+ dt.timedelta(minutes=get_settings().magic_link_ttl_minutes),
|
||||
)
|
||||
session.add(token)
|
||||
session.commit()
|
||||
# STUB : en production, ce lien part par email. Ici on le journalise
|
||||
# (identifiants uniquement, aucune donnée nominative).
|
||||
logger.info(
|
||||
"STUB lien magique — compte=%s édition=%s expire=%s jeton=%s",
|
||||
account.id,
|
||||
edition_id,
|
||||
token.expires_at.isoformat(),
|
||||
raw,
|
||||
)
|
||||
return {"status": "accepted"}
|
||||
|
||||
|
||||
@router.post("/editions/{edition_id}/auth/verify", response_model=TokenResponse)
|
||||
def verify_magic_link(
|
||||
edition_id: uuid.UUID,
|
||||
payload: VerifyRequest,
|
||||
session: Session = Depends(get_session),
|
||||
) -> TokenResponse:
|
||||
token = session.exec(
|
||||
select(MagicLinkToken).where(
|
||||
MagicLinkToken.token_hash == hash_token(payload.token.strip())
|
||||
)
|
||||
).first()
|
||||
if (
|
||||
token is None
|
||||
or token.used_at is not None
|
||||
or token.expires_at < local_now()
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail={"code": "auth.invalid_token"},
|
||||
)
|
||||
account = session.get(Account, token.account_id)
|
||||
if account is None or account.edition_id != edition_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail={"code": "auth.invalid_token"},
|
||||
)
|
||||
token.used_at = local_now()
|
||||
session.commit()
|
||||
session.refresh(account)
|
||||
return TokenResponse(
|
||||
access_token=create_access_token(account),
|
||||
token_type="bearer",
|
||||
account=AccountRead.model_validate(account),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/auth/me", response_model=AccountRead)
|
||||
def read_me(account: Account = Depends(get_current_account)) -> Account:
|
||||
return account
|
||||
@@ -1,12 +1,13 @@
|
||||
"""Endpoints d'import : analyse puis exécution."""
|
||||
|
||||
import datetime as dt
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
|
||||
from pydantic import ValidationError
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from app.api.deps import get_edition
|
||||
from app.auth.deps import require_coordinator
|
||||
from app.db import get_session
|
||||
from app.importing.parser import ImportParseError, parse_upload
|
||||
from app.importing.schemas import (
|
||||
@@ -17,7 +18,7 @@ from app.importing.schemas import (
|
||||
PreviewRow,
|
||||
)
|
||||
from app.importing.service import run_import, suggest_mapping, validate_mapping
|
||||
from app.models import DayPart, Edition
|
||||
from app.models import Account, DayPart, Edition
|
||||
|
||||
router = APIRouter(prefix="/editions/{edition_id}/import", tags=["import"])
|
||||
|
||||
@@ -25,13 +26,6 @@ _PREVIEW_ROWS = 5
|
||||
_MAX_BYTES = 5 * 1024 * 1024
|
||||
|
||||
|
||||
def _get_edition(edition_id: uuid.UUID, session: Session) -> Edition:
|
||||
edition = session.get(Edition, edition_id)
|
||||
if edition is None:
|
||||
raise HTTPException(status_code=404, detail={"code": "error.not_found"})
|
||||
return edition
|
||||
|
||||
|
||||
async def _read_upload(file: UploadFile) -> bytes:
|
||||
content = await file.read()
|
||||
if not content:
|
||||
@@ -68,11 +62,11 @@ def _day_parts(session: Session, edition: Edition) -> list[DayPart]:
|
||||
|
||||
@router.post("/analyze", response_model=AnalyzeResponse)
|
||||
async def analyze(
|
||||
edition_id: uuid.UUID,
|
||||
file: UploadFile = File(...),
|
||||
edition: Edition = Depends(get_edition),
|
||||
_guard: Account = Depends(require_coordinator),
|
||||
session: Session = Depends(get_session),
|
||||
) -> AnalyzeResponse:
|
||||
edition = _get_edition(edition_id, session)
|
||||
content = await _read_upload(file)
|
||||
try:
|
||||
table = parse_upload(file.filename or "", content)
|
||||
@@ -109,12 +103,12 @@ async def analyze(
|
||||
|
||||
@router.post("/execute", response_model=ImportReport)
|
||||
async def execute(
|
||||
edition_id: uuid.UUID,
|
||||
file: UploadFile = File(...),
|
||||
mapping: str = Form(...),
|
||||
edition: Edition = Depends(get_edition),
|
||||
_guard: Account = Depends(require_coordinator),
|
||||
session: Session = Depends(get_session),
|
||||
) -> ImportReport:
|
||||
edition = _get_edition(edition_id, session)
|
||||
content = await _read_upload(file)
|
||||
|
||||
try:
|
||||
|
||||
@@ -6,8 +6,16 @@ from sqlmodel import Session, select
|
||||
|
||||
from app.api.deps import get_edition
|
||||
from app.api.schemas import MatrixPosition, MatrixResponse, MatrixShift
|
||||
from app.auth.deps import require_staff
|
||||
from app.db import get_session
|
||||
from app.models import Assignment, AssignmentStatus, Edition, Position, Shift
|
||||
from app.models import (
|
||||
Account,
|
||||
Assignment,
|
||||
AssignmentStatus,
|
||||
Edition,
|
||||
Position,
|
||||
Shift,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/editions/{edition_id}/matrix", tags=["matrix"])
|
||||
|
||||
@@ -15,6 +23,7 @@ router = APIRouter(prefix="/editions/{edition_id}/matrix", tags=["matrix"])
|
||||
@router.get("", response_model=MatrixResponse)
|
||||
def get_matrix(
|
||||
edition: Edition = Depends(get_edition),
|
||||
_guard: Account = Depends(require_staff),
|
||||
session: Session = Depends(get_session),
|
||||
) -> MatrixResponse:
|
||||
positions = list(
|
||||
|
||||
@@ -8,8 +8,14 @@ from sqlmodel import Session, select
|
||||
from app.api._common import owned_or_404
|
||||
from app.api.deps import get_edition
|
||||
from app.api.schemas import PositionCreate, PositionRead, PositionUpdate
|
||||
from app.auth.deps import (
|
||||
current_account_in_edition,
|
||||
ensure_can_write_position,
|
||||
require_coordinator,
|
||||
require_staff,
|
||||
)
|
||||
from app.db import get_session
|
||||
from app.models import Edition, Position
|
||||
from app.models import Account, Edition, Position
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/editions/{edition_id}/positions", tags=["positions"]
|
||||
@@ -20,6 +26,7 @@ router = APIRouter(
|
||||
def create_position(
|
||||
payload: PositionCreate,
|
||||
edition: Edition = Depends(get_edition),
|
||||
_guard: Account = Depends(require_coordinator),
|
||||
session: Session = Depends(get_session),
|
||||
) -> Position:
|
||||
position = Position(edition_id=edition.id, **payload.model_dump())
|
||||
@@ -32,6 +39,7 @@ def create_position(
|
||||
@router.get("", response_model=list[PositionRead])
|
||||
def list_positions(
|
||||
edition: Edition = Depends(get_edition),
|
||||
_guard: Account = Depends(require_staff),
|
||||
session: Session = Depends(get_session),
|
||||
) -> list[Position]:
|
||||
return list(
|
||||
@@ -47,6 +55,7 @@ def list_positions(
|
||||
def get_position(
|
||||
position_id: uuid.UUID,
|
||||
edition: Edition = Depends(get_edition),
|
||||
_guard: Account = Depends(require_staff),
|
||||
session: Session = Depends(get_session),
|
||||
) -> Position:
|
||||
return owned_or_404(session.get(Position, position_id), edition.id)
|
||||
@@ -57,9 +66,11 @@ def update_position(
|
||||
position_id: uuid.UUID,
|
||||
payload: PositionUpdate,
|
||||
edition: Edition = Depends(get_edition),
|
||||
account: Account = Depends(current_account_in_edition),
|
||||
session: Session = Depends(get_session),
|
||||
) -> Position:
|
||||
position = owned_or_404(session.get(Position, position_id), edition.id)
|
||||
ensure_can_write_position(account, position)
|
||||
for field, value in payload.model_dump(exclude_unset=True).items():
|
||||
setattr(position, field, value)
|
||||
session.commit()
|
||||
@@ -71,6 +82,7 @@ def update_position(
|
||||
def delete_position(
|
||||
position_id: uuid.UUID,
|
||||
edition: Edition = Depends(get_edition),
|
||||
_guard: Account = Depends(require_coordinator),
|
||||
session: Session = Depends(get_session),
|
||||
) -> Response:
|
||||
position = owned_or_404(session.get(Position, position_id), edition.id)
|
||||
|
||||
@@ -9,6 +9,7 @@ from app.models import (
|
||||
AssignmentSource,
|
||||
AssignmentStatus,
|
||||
PositionCategory,
|
||||
Role,
|
||||
TshirtSize,
|
||||
)
|
||||
from app.validation import Violation
|
||||
@@ -190,3 +191,36 @@ class MatrixPosition(ApiModel):
|
||||
class MatrixResponse(ApiModel):
|
||||
edition_id: uuid.UUID
|
||||
positions: list[MatrixPosition]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Authentification et comptes #
|
||||
# --------------------------------------------------------------------------- #
|
||||
class MagicLinkRequest(ApiModel):
|
||||
email: str
|
||||
|
||||
|
||||
class VerifyRequest(ApiModel):
|
||||
token: str
|
||||
|
||||
|
||||
class AccountRead(ApiModel):
|
||||
id: uuid.UUID
|
||||
edition_id: uuid.UUID
|
||||
email: str
|
||||
role: Role
|
||||
volunteer_id: uuid.UUID | None
|
||||
created_at: dt.datetime
|
||||
updated_at: dt.datetime
|
||||
|
||||
|
||||
class TokenResponse(ApiModel):
|
||||
access_token: str
|
||||
token_type: str
|
||||
account: AccountRead
|
||||
|
||||
|
||||
class AccountCreate(ApiModel):
|
||||
email: str
|
||||
role: Role
|
||||
volunteer_id: uuid.UUID | None = None
|
||||
|
||||
@@ -8,8 +8,21 @@ from sqlmodel import Session, select
|
||||
from app.api._common import owned_or_404, replace_links, resolve_skills
|
||||
from app.api.deps import get_edition
|
||||
from app.api.schemas import ShiftCreate, ShiftRead, ShiftUpdate
|
||||
from app.auth.deps import (
|
||||
current_account_in_edition,
|
||||
ensure_can_write_position,
|
||||
ensure_can_write_shift,
|
||||
require_staff,
|
||||
)
|
||||
from app.db import get_session
|
||||
from app.models import Edition, Position, Shift, ShiftRequiredSkill, Skill
|
||||
from app.models import (
|
||||
Account,
|
||||
Edition,
|
||||
Position,
|
||||
Shift,
|
||||
ShiftRequiredSkill,
|
||||
Skill,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/editions/{edition_id}/shifts", tags=["shifts"])
|
||||
|
||||
@@ -65,10 +78,12 @@ def _require_position(
|
||||
def create_shift(
|
||||
payload: ShiftCreate,
|
||||
edition: Edition = Depends(get_edition),
|
||||
account: Account = Depends(current_account_in_edition),
|
||||
session: Session = Depends(get_session),
|
||||
) -> ShiftRead:
|
||||
_check_range(payload.starts_at, payload.ends_at)
|
||||
_require_position(session, payload.position_id, edition.id)
|
||||
position = _require_position(session, payload.position_id, edition.id)
|
||||
ensure_can_write_position(account, position)
|
||||
shift = Shift(
|
||||
edition_id=edition.id,
|
||||
**payload.model_dump(exclude={"required_skill_codes"}),
|
||||
@@ -85,6 +100,7 @@ def create_shift(
|
||||
def list_shifts(
|
||||
position_id: uuid.UUID | None = None,
|
||||
edition: Edition = Depends(get_edition),
|
||||
_guard: Account = Depends(require_staff),
|
||||
session: Session = Depends(get_session),
|
||||
) -> list[ShiftRead]:
|
||||
stmt = (
|
||||
@@ -101,6 +117,7 @@ def list_shifts(
|
||||
def get_shift(
|
||||
shift_id: uuid.UUID,
|
||||
edition: Edition = Depends(get_edition),
|
||||
_guard: Account = Depends(require_staff),
|
||||
session: Session = Depends(get_session),
|
||||
) -> ShiftRead:
|
||||
shift = owned_or_404(session.get(Shift, shift_id), edition.id)
|
||||
@@ -112,13 +129,16 @@ def update_shift(
|
||||
shift_id: uuid.UUID,
|
||||
payload: ShiftUpdate,
|
||||
edition: Edition = Depends(get_edition),
|
||||
account: Account = Depends(current_account_in_edition),
|
||||
session: Session = Depends(get_session),
|
||||
) -> ShiftRead:
|
||||
shift = owned_or_404(session.get(Shift, shift_id), edition.id)
|
||||
ensure_can_write_shift(account, session, shift)
|
||||
changes = payload.model_dump(exclude_unset=True)
|
||||
skill_codes = changes.pop("required_skill_codes", None)
|
||||
if "position_id" in changes:
|
||||
_require_position(session, changes["position_id"], edition.id)
|
||||
target = _require_position(session, changes["position_id"], edition.id)
|
||||
ensure_can_write_position(account, target)
|
||||
for field, value in changes.items():
|
||||
setattr(shift, field, value)
|
||||
_check_range(shift.starts_at, shift.ends_at)
|
||||
@@ -133,9 +153,11 @@ def update_shift(
|
||||
def delete_shift(
|
||||
shift_id: uuid.UUID,
|
||||
edition: Edition = Depends(get_edition),
|
||||
account: Account = Depends(current_account_in_edition),
|
||||
session: Session = Depends(get_session),
|
||||
) -> Response:
|
||||
shift = owned_or_404(session.get(Shift, shift_id), edition.id)
|
||||
ensure_can_write_shift(account, session, shift)
|
||||
session.delete(shift)
|
||||
session.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
@@ -9,14 +9,27 @@ from sqlmodel import Session, select
|
||||
from app.api._common import owned_or_404, replace_links, resolve_skills
|
||||
from app.api.deps import get_edition
|
||||
from app.api.schemas import VolunteerCreate, VolunteerRead, VolunteerUpdate
|
||||
from app.auth.deps import (
|
||||
current_account_in_edition,
|
||||
require_coordinator,
|
||||
require_staff,
|
||||
)
|
||||
from app.db import get_session
|
||||
from app.models import Edition, Skill, Volunteer, VolunteerSkill
|
||||
from app.models import Account, Edition, Role, Skill, Volunteer, VolunteerSkill
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/editions/{edition_id}/volunteers", tags=["volunteers"]
|
||||
)
|
||||
|
||||
|
||||
def _ensure_can_read(account: Account, volunteer_id: uuid.UUID) -> None:
|
||||
if account.role in (Role.COORDINATOR, Role.LEAD):
|
||||
return
|
||||
if account.volunteer_id == volunteer_id:
|
||||
return
|
||||
raise HTTPException(status_code=403, detail={"code": "error.forbidden"})
|
||||
|
||||
|
||||
def _skill_codes(session: Session, volunteer_id: uuid.UUID) -> list[str]:
|
||||
return sorted(
|
||||
session.exec(
|
||||
@@ -53,6 +66,7 @@ def _set_skills(
|
||||
def create_volunteer(
|
||||
payload: VolunteerCreate,
|
||||
edition: Edition = Depends(get_edition),
|
||||
_guard: Account = Depends(require_coordinator),
|
||||
session: Session = Depends(get_session),
|
||||
) -> VolunteerRead:
|
||||
volunteer = Volunteer(
|
||||
@@ -76,6 +90,7 @@ def create_volunteer(
|
||||
@router.get("", response_model=list[VolunteerRead])
|
||||
def list_volunteers(
|
||||
edition: Edition = Depends(get_edition),
|
||||
_guard: Account = Depends(require_staff),
|
||||
session: Session = Depends(get_session),
|
||||
) -> list[VolunteerRead]:
|
||||
volunteers = session.exec(
|
||||
@@ -90,8 +105,10 @@ def list_volunteers(
|
||||
def get_volunteer(
|
||||
volunteer_id: uuid.UUID,
|
||||
edition: Edition = Depends(get_edition),
|
||||
account: Account = Depends(current_account_in_edition),
|
||||
session: Session = Depends(get_session),
|
||||
) -> VolunteerRead:
|
||||
_ensure_can_read(account, volunteer_id)
|
||||
volunteer = owned_or_404(session.get(Volunteer, volunteer_id), edition.id)
|
||||
return _read(session, volunteer)
|
||||
|
||||
@@ -101,6 +118,7 @@ def update_volunteer(
|
||||
volunteer_id: uuid.UUID,
|
||||
payload: VolunteerUpdate,
|
||||
edition: Edition = Depends(get_edition),
|
||||
_guard: Account = Depends(require_coordinator),
|
||||
session: Session = Depends(get_session),
|
||||
) -> VolunteerRead:
|
||||
volunteer = owned_or_404(session.get(Volunteer, volunteer_id), edition.id)
|
||||
@@ -126,6 +144,7 @@ def update_volunteer(
|
||||
def delete_volunteer(
|
||||
volunteer_id: uuid.UUID,
|
||||
edition: Edition = Depends(get_edition),
|
||||
_guard: Account = Depends(require_coordinator),
|
||||
session: Session = Depends(get_session),
|
||||
) -> Response:
|
||||
volunteer = owned_or_404(session.get(Volunteer, volunteer_id), edition.id)
|
||||
|
||||
Reference in New Issue
Block a user