|
| 1 | +import os |
| 2 | +from typing import Annotated |
| 3 | + |
| 4 | +from fastapi import APIRouter, Depends, Request, status |
| 5 | +from sqlmodel.ext.asyncio.session import AsyncSession |
| 6 | + |
| 7 | +from app.routers.authentication import get_current_active_community |
| 8 | +from app.schemas import CommunityPostResponse |
| 9 | +from app.services import auth |
| 10 | +from app.services.database.models import Community as DBCommunity # Precisa? |
| 11 | +from app.services.database.orm.community import create_community |
| 12 | +from app.services.limiter import limiter |
| 13 | + |
| 14 | +# ADMIN_USER = os.getenv("ADMIN_USER") |
| 15 | +# ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD") |
| 16 | + |
| 17 | + |
| 18 | +async def create_admin(session: AsyncSession): |
| 19 | + ADMIN_USER = os.getenv("ADMIN_USER") |
| 20 | + ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD") |
| 21 | + ADMIN_EMAIL = os.getenv("ADMIN_EMAIL") |
| 22 | + password = ADMIN_PASSWORD |
| 23 | + hashed_password = auth.hash_password(password) |
| 24 | + community = DBCommunity( |
| 25 | + username=ADMIN_USER, |
| 26 | + email=ADMIN_EMAIL, |
| 27 | + password=hashed_password, |
| 28 | + role="admin", |
| 29 | + ) |
| 30 | + await create_community(session=session, community=community) |
| 31 | + |
| 32 | + return {"msg": "Admin successfully created"} |
| 33 | + |
| 34 | + |
| 35 | +def setup(): |
| 36 | + router = APIRouter(prefix="/admin", tags=["admin"]) |
| 37 | + |
| 38 | + @router.post( |
| 39 | + "/create_community", |
| 40 | + response_model=CommunityPostResponse, |
| 41 | + status_code=status.HTTP_201_CREATED, |
| 42 | + summary="Create Community endpoint", |
| 43 | + description="Create Community and returns a confirmation message", |
| 44 | + ) |
| 45 | + @limiter.limit("60/minute") |
| 46 | + async def post_create_community( |
| 47 | + request: Request, |
| 48 | + admin_community: Annotated[ |
| 49 | + DBCommunity, Depends(get_current_active_community) |
| 50 | + ], |
| 51 | + community: DBCommunity, |
| 52 | + ): |
| 53 | + """ |
| 54 | + Server Admin endpoint that creates Community and returns a confirmation |
| 55 | + message. |
| 56 | + """ |
| 57 | + admin_role = admin_community.role |
| 58 | + if admin_role != "admin": |
| 59 | + return {"status": "Unauthorized"} |
| 60 | + session: AsyncSession = request.app.db_session_factory |
| 61 | + await create_community(session=session, community=community) |
| 62 | + |
| 63 | + return CommunityPostResponse() |
| 64 | + |
| 65 | + return router |
0 commit comments