web sttarting
This commit is contained in:
@@ -1,10 +1,10 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from pydantic import BaseModel, field_validator
|
||||
from typing import Optional
|
||||
import uuid
|
||||
|
||||
from bd import Settings
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from bd import make_engine
|
||||
|
||||
from bd.tables.users import User
|
||||
from route.auth_utils import hash_password, verify_password, create_access_token
|
||||
@@ -12,10 +12,9 @@ from route.auth_utils import hash_password, verify_password, create_access_token
|
||||
router = APIRouter(tags=["auth"], prefix="/auth")
|
||||
|
||||
|
||||
def _get_session():
|
||||
settings = Settings()
|
||||
engine = create_engine(settings.DATABASE_URL_syncpg, future=True)
|
||||
return sessionmaker(bind=engine, future=True)
|
||||
def get_session():
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
return sessionmaker(bind=make_engine(), future=True)
|
||||
|
||||
|
||||
class RegisterIn(BaseModel):
|
||||
@@ -23,6 +22,8 @@ class RegisterIn(BaseModel):
|
||||
password: str
|
||||
first_name: str
|
||||
last_name: str
|
||||
group_id: Optional[str] = None
|
||||
organization_id: Optional[str] = None
|
||||
|
||||
@field_validator("password")
|
||||
@classmethod
|
||||
@@ -42,7 +43,7 @@ class RegisterIn(BaseModel):
|
||||
|
||||
@router.post("/register", status_code=201)
|
||||
def register(payload: RegisterIn):
|
||||
Session = _get_session()
|
||||
Session = get_session()
|
||||
with Session() as session:
|
||||
existing = session.query(User).filter(User.username == payload.username).first()
|
||||
if existing:
|
||||
@@ -52,6 +53,8 @@ def register(payload: RegisterIn):
|
||||
last_name=payload.last_name.strip(),
|
||||
username=payload.username,
|
||||
hashed_password=hash_password(payload.password),
|
||||
group_id=uuid.UUID(payload.group_id) if payload.group_id else None,
|
||||
organization_id=uuid.UUID(payload.organization_id) if payload.organization_id else None,
|
||||
)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
@@ -61,7 +64,7 @@ def register(payload: RegisterIn):
|
||||
|
||||
@router.post("/login")
|
||||
def login(form: OAuth2PasswordRequestForm = Depends()):
|
||||
Session = _get_session()
|
||||
Session = get_session()
|
||||
with Session() as session:
|
||||
user = session.query(User).filter(User.username == form.username).first()
|
||||
if not user or not verify_password(form.password, user.hashed_password):
|
||||
|
||||
@@ -9,9 +9,7 @@ from fastapi.security import OAuth2PasswordBearer
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
|
||||
from bd import Settings
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from bd import make_engine
|
||||
|
||||
SECRET_KEY: str = os.getenv("SECRET_KEY", "")
|
||||
if not SECRET_KEY:
|
||||
@@ -46,10 +44,9 @@ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -
|
||||
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
||||
|
||||
|
||||
def _get_session():
|
||||
settings = Settings()
|
||||
engine = create_engine(settings.DATABASE_URL_syncpg, future=True)
|
||||
return sessionmaker(bind=engine, future=True)
|
||||
def get_session():
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
return sessionmaker(bind=make_engine(), future=True)
|
||||
|
||||
|
||||
def get_current_user(token: str = Depends(oauth2_scheme)):
|
||||
@@ -74,7 +71,7 @@ def get_current_user(token: str = Depends(oauth2_scheme)):
|
||||
except Exception:
|
||||
raise credentials_exc
|
||||
|
||||
Session = _get_session()
|
||||
Session = get_session()
|
||||
with Session() as session:
|
||||
user = session.get(User, uid)
|
||||
if user is None:
|
||||
|
||||
@@ -3,13 +3,11 @@ from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
import uuid
|
||||
|
||||
from bd import Settings
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from bd import make_engine
|
||||
|
||||
from bd.tables.choice import Choice
|
||||
from bd.tables.question import Question
|
||||
from route.auth_utils import get_current_user
|
||||
from route.auth_utils import require_admin_key
|
||||
|
||||
router = APIRouter(tags=["choices"], prefix="/choices")
|
||||
|
||||
@@ -26,13 +24,12 @@ class ChoiceUpdate(BaseModel):
|
||||
|
||||
|
||||
def get_session():
|
||||
settings = Settings()
|
||||
engine = create_engine(settings.DATABASE_URL_syncpg, future=True)
|
||||
return sessionmaker(bind=engine, future=True)
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
return sessionmaker(bind=make_engine(), future=True)
|
||||
|
||||
|
||||
@router.post("/", status_code=201)
|
||||
def create_choice(payload: ChoiceCreate, _: object = Depends(get_current_user)):
|
||||
@router.post("/", status_code=201, dependencies=[Depends(require_admin_key)])
|
||||
def create_choice(payload: ChoiceCreate):
|
||||
Session = get_session()
|
||||
try:
|
||||
qid = uuid.UUID(payload.question_id)
|
||||
@@ -49,8 +46,8 @@ def create_choice(payload: ChoiceCreate, _: object = Depends(get_current_user)):
|
||||
return {"id": str(ch.id)}
|
||||
|
||||
|
||||
@router.put("/{choice_id}")
|
||||
def update_choice(choice_id: str, payload: ChoiceUpdate, _: object = Depends(get_current_user)):
|
||||
@router.put("/{choice_id}", dependencies=[Depends(require_admin_key)])
|
||||
def update_choice(choice_id: str, payload: ChoiceUpdate):
|
||||
Session = get_session()
|
||||
try:
|
||||
cid = uuid.UUID(choice_id)
|
||||
@@ -70,8 +67,8 @@ def update_choice(choice_id: str, payload: ChoiceUpdate, _: object = Depends(get
|
||||
return {"id": str(ch.id)}
|
||||
|
||||
|
||||
@router.delete("/{choice_id}", status_code=204)
|
||||
def delete_choice(choice_id: str, _: object = Depends(get_current_user)):
|
||||
@router.delete("/{choice_id}", status_code=204, dependencies=[Depends(require_admin_key)])
|
||||
def delete_choice(choice_id: str):
|
||||
Session = get_session()
|
||||
try:
|
||||
cid = uuid.UUID(choice_id)
|
||||
|
||||
@@ -3,49 +3,43 @@ from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
import uuid
|
||||
|
||||
from bd import Settings
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from bd import make_engine
|
||||
|
||||
from bd.tables.group import Group
|
||||
from bd.tables.users import User
|
||||
from route.auth_utils import get_current_user
|
||||
from route.auth_utils import require_admin_key
|
||||
|
||||
router = APIRouter(tags=["groups"], prefix="/groups")
|
||||
|
||||
|
||||
class GroupCreate(BaseModel):
|
||||
name_group: str
|
||||
user_id: str
|
||||
|
||||
|
||||
class GroupUpdate(BaseModel):
|
||||
name_group: Optional[str]
|
||||
user_id: Optional[str]
|
||||
name_group: Optional[str] = None
|
||||
|
||||
|
||||
def get_session():
|
||||
settings = Settings()
|
||||
engine = create_engine(settings.DATABASE_URL_syncpg, future=True)
|
||||
return sessionmaker(bind=engine, future=True)
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
return sessionmaker(bind=make_engine(), future=True)
|
||||
|
||||
|
||||
@router.post("/", status_code=201)
|
||||
def create_group(payload: GroupCreate, _: object = Depends(get_current_user)):
|
||||
def _group_dict(grp: Group) -> dict:
|
||||
return {"id": str(grp.id), "name_group": grp.name_group}
|
||||
|
||||
|
||||
@router.post("/", status_code=201, dependencies=[Depends(require_admin_key)])
|
||||
def create_group(payload: GroupCreate):
|
||||
Session = get_session()
|
||||
try:
|
||||
uid = uuid.UUID(payload.user_id)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="Invalid user_id UUID")
|
||||
with Session() as session:
|
||||
user = session.get(User, uid)
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
grp = Group(name_group=payload.name_group, user_id=uid)
|
||||
existing = session.query(Group).filter(Group.name_group == payload.name_group).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Group name already exists")
|
||||
grp = Group(name_group=payload.name_group)
|
||||
session.add(grp)
|
||||
session.commit()
|
||||
session.refresh(grp)
|
||||
return {"id": str(grp.id), "name_group": grp.name_group, "user_id": str(grp.user_id)}
|
||||
return _group_dict(grp)
|
||||
|
||||
|
||||
@router.get("/")
|
||||
@@ -53,7 +47,7 @@ def list_groups():
|
||||
Session = get_session()
|
||||
with Session() as session:
|
||||
rows = session.query(Group).all()
|
||||
return [{"id": str(g.id), "name_group": g.name_group, "user_id": str(g.user_id)} for g in rows]
|
||||
return [_group_dict(g) for g in rows]
|
||||
|
||||
|
||||
@router.get("/{group_id}")
|
||||
@@ -67,11 +61,11 @@ def get_group(group_id: str):
|
||||
grp = session.get(Group, gid)
|
||||
if not grp:
|
||||
raise HTTPException(status_code=404, detail="Group not found")
|
||||
return {"id": str(grp.id), "name_group": grp.name_group, "user_id": str(grp.user_id)}
|
||||
return _group_dict(grp)
|
||||
|
||||
|
||||
@router.put("/{group_id}")
|
||||
def update_group(group_id: str, payload: GroupUpdate, _: object = Depends(get_current_user)):
|
||||
@router.put("/{group_id}", dependencies=[Depends(require_admin_key)])
|
||||
def update_group(group_id: str, payload: GroupUpdate):
|
||||
Session = get_session()
|
||||
try:
|
||||
gid = uuid.UUID(group_id)
|
||||
@@ -83,23 +77,14 @@ def update_group(group_id: str, payload: GroupUpdate, _: object = Depends(get_cu
|
||||
raise HTTPException(status_code=404, detail="Group not found")
|
||||
if payload.name_group is not None:
|
||||
grp.name_group = payload.name_group
|
||||
if payload.user_id is not None:
|
||||
try:
|
||||
new_uid = uuid.UUID(payload.user_id)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="Invalid user_id UUID")
|
||||
user = session.get(User, new_uid)
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
grp.user_id = new_uid
|
||||
session.add(grp)
|
||||
session.commit()
|
||||
session.refresh(grp)
|
||||
return {"id": str(grp.id), "name_group": grp.name_group, "user_id": str(grp.user_id)}
|
||||
return _group_dict(grp)
|
||||
|
||||
|
||||
@router.delete("/{group_id}", status_code=204)
|
||||
def delete_group(group_id: str, _: object = Depends(get_current_user)):
|
||||
@router.delete("/{group_id}", status_code=204, dependencies=[Depends(require_admin_key)])
|
||||
def delete_group(group_id: str):
|
||||
Session = get_session()
|
||||
try:
|
||||
gid = uuid.UUID(group_id)
|
||||
|
||||
@@ -2,9 +2,7 @@ from fastapi import APIRouter, HTTPException
|
||||
from typing import Optional
|
||||
import uuid
|
||||
|
||||
from bd import Settings
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from bd import make_engine
|
||||
|
||||
from bd.tables.poll import Poll
|
||||
from bd.tables.question import Question
|
||||
@@ -60,9 +58,8 @@ PAIRS = [
|
||||
|
||||
|
||||
def get_session():
|
||||
settings = Settings()
|
||||
engine = create_engine(settings.DATABASE_URL_syncpg, future=True)
|
||||
return sessionmaker(bind=engine, future=True)
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
return sessionmaker(bind=make_engine(), future=True)
|
||||
|
||||
|
||||
@router.post("/holland", status_code=201)
|
||||
@@ -83,3 +80,11 @@ def create_holland_poll(author_id: Optional[str] = None):
|
||||
session.commit()
|
||||
session.refresh(poll)
|
||||
return {"id": str(poll.id), "questions": len(poll.questions)}
|
||||
|
||||
|
||||
@router.get("/holland")
|
||||
def list_holland_polls():
|
||||
Session = get_session()
|
||||
with Session() as session:
|
||||
rows = session.query(Poll).filter(Poll.title.like("%Голланда%")).all()
|
||||
return [{"id": str(p.id), "title": p.title, "description": p.description} for p in rows]
|
||||
|
||||
@@ -4,8 +4,8 @@ import importlib
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
from bd import Settings
|
||||
from sqlalchemy import create_engine, text
|
||||
from bd import Settings, make_engine
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from pydantic import BaseModel
|
||||
|
||||
@@ -48,9 +48,7 @@ async def create_tables():
|
||||
|
||||
Endpoint вызывается по нажатию кнопки в UI (POST).
|
||||
"""
|
||||
settings = Settings()
|
||||
db_url = settings.DATABASE_URL_syncpg
|
||||
engine = create_engine(db_url, future=True)
|
||||
engine = make_engine()
|
||||
|
||||
metadatas = collect_metadatas()
|
||||
if not metadatas:
|
||||
@@ -75,8 +73,7 @@ async def create_tables():
|
||||
@router.post("/db/migrate-users", dependencies=[Depends(require_admin_key)])
|
||||
async def migrate_users():
|
||||
"""Добавляет колонки username и hashed_password в таблицу users, если они ещё не существуют."""
|
||||
settings = Settings()
|
||||
engine = create_engine(settings.DATABASE_URL_syncpg, future=True)
|
||||
engine = make_engine()
|
||||
try:
|
||||
with engine.connect() as conn:
|
||||
conn.execute(text("""
|
||||
@@ -94,6 +91,30 @@ class ClearDBIn(BaseModel):
|
||||
confirm: bool
|
||||
|
||||
|
||||
@router.post("/db/migrate", dependencies=[Depends(require_admin_key)])
|
||||
async def migrate_tables():
|
||||
"""Приводит схему БД в соответствие с моделями: убирает устаревшие колонки, добавляет новые."""
|
||||
engine = make_engine()
|
||||
migrations = [
|
||||
# Убираем старый FK и колонку group.user_id (если остался от прежней схемы)
|
||||
'ALTER TABLE "group" DROP COLUMN IF EXISTS user_id',
|
||||
# Делаем organization.group_id необязательным
|
||||
"ALTER TABLE organization ALTER COLUMN group_id DROP NOT NULL",
|
||||
# Добавляем новые колонки в users
|
||||
'ALTER TABLE users ADD COLUMN IF NOT EXISTS group_id UUID REFERENCES "group"(id) ON DELETE SET NULL',
|
||||
"ALTER TABLE users ADD COLUMN IF NOT EXISTS organization_id UUID REFERENCES organization(id) ON DELETE SET NULL",
|
||||
]
|
||||
applied = []
|
||||
try:
|
||||
with engine.begin() as conn:
|
||||
for sql in migrations:
|
||||
conn.execute(text(sql))
|
||||
applied.append(sql)
|
||||
return {"status": "ok", "applied": applied}
|
||||
except SQLAlchemyError as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/db/clear", dependencies=[Depends(require_admin_key)])
|
||||
async def clear_tables(payload: ClearDBIn):
|
||||
"""Полная очистка всех таблиц, описанных в `bd.tables`.
|
||||
@@ -103,9 +124,7 @@ async def clear_tables(payload: ClearDBIn):
|
||||
if not payload.confirm:
|
||||
raise HTTPException(status_code=400, detail="Confirmation required")
|
||||
|
||||
settings = Settings()
|
||||
db_url = settings.DATABASE_URL_syncpg
|
||||
engine = create_engine(db_url, future=True)
|
||||
engine = make_engine()
|
||||
|
||||
metadatas = collect_metadatas()
|
||||
if not metadatas:
|
||||
@@ -120,8 +139,9 @@ async def clear_tables(payload: ClearDBIn):
|
||||
unique.append(md)
|
||||
|
||||
try:
|
||||
for md in unique:
|
||||
md.drop_all(bind=engine)
|
||||
return {"status": "ok", "detail": f"Dropped {len(unique)} metadata groups"}
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("DROP SCHEMA public CASCADE"))
|
||||
conn.execute(text("CREATE SCHEMA public"))
|
||||
return {"status": "ok", "detail": "All tables dropped via DROP SCHEMA CASCADE"}
|
||||
except SQLAlchemyError as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@@ -3,49 +3,48 @@ from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
import uuid
|
||||
|
||||
from bd import Settings
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from bd import make_engine
|
||||
|
||||
from bd.tables.organization import Organization
|
||||
from bd.tables.group import Group
|
||||
from route.auth_utils import get_current_user
|
||||
from route.auth_utils import require_admin_key
|
||||
|
||||
router = APIRouter(tags=["organizations"], prefix="/organizations")
|
||||
|
||||
|
||||
class OrganizationCreate(BaseModel):
|
||||
name_organization: str
|
||||
group_id: str
|
||||
|
||||
|
||||
class OrganizationUpdate(BaseModel):
|
||||
name_organization: Optional[str]
|
||||
group_id: Optional[str]
|
||||
name_organization: Optional[str] = None
|
||||
|
||||
|
||||
|
||||
def get_session():
|
||||
settings = Settings()
|
||||
engine = create_engine(settings.DATABASE_URL_syncpg, future=True)
|
||||
return sessionmaker(bind=engine, future=True)
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
return sessionmaker(bind=make_engine(), future=True)
|
||||
|
||||
|
||||
@router.post("/", status_code=201)
|
||||
def create_organization(payload: OrganizationCreate, _: object = Depends(get_current_user)):
|
||||
def _org_dict(org: Organization) -> dict:
|
||||
return {
|
||||
"id": str(org.id),
|
||||
"name_organization": org.name_organization,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/", status_code=201, dependencies=[Depends(require_admin_key)])
|
||||
def create_organization(payload: OrganizationCreate):
|
||||
Session = get_session()
|
||||
try:
|
||||
gid = uuid.UUID(payload.group_id)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="Invalid group_id UUID")
|
||||
with Session() as session:
|
||||
grp = session.get(Group, gid)
|
||||
if not grp:
|
||||
raise HTTPException(status_code=404, detail="Group not found")
|
||||
org = Organization(name_organization=payload.name_organization, group_id=gid)
|
||||
existing = session.query(Organization).filter(
|
||||
Organization.name_organization == payload.name_organization
|
||||
).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Organization name already exists")
|
||||
org = Organization(name_organization=payload.name_organization)
|
||||
session.add(org)
|
||||
session.commit()
|
||||
session.refresh(org)
|
||||
return {"id": str(org.id), "name_organization": org.name_organization, "group_id": str(org.group_id)}
|
||||
return _org_dict(org)
|
||||
|
||||
|
||||
@router.get("/")
|
||||
@@ -53,7 +52,7 @@ def list_organizations():
|
||||
Session = get_session()
|
||||
with Session() as session:
|
||||
rows = session.query(Organization).all()
|
||||
return [{"id": str(o.id), "name_organization": o.name_organization, "group_id": str(o.group_id)} for o in rows]
|
||||
return [_org_dict(o) for o in rows]
|
||||
|
||||
|
||||
@router.get("/{org_id}")
|
||||
@@ -67,11 +66,11 @@ def get_organization(org_id: str):
|
||||
org = session.get(Organization, oid)
|
||||
if not org:
|
||||
raise HTTPException(status_code=404, detail="Organization not found")
|
||||
return {"id": str(org.id), "name_organization": org.name_organization, "group_id": str(org.group_id)}
|
||||
return _org_dict(org)
|
||||
|
||||
|
||||
@router.put("/{org_id}")
|
||||
def update_organization(org_id: str, payload: OrganizationUpdate, _: object = Depends(get_current_user)):
|
||||
@router.put("/{org_id}", dependencies=[Depends(require_admin_key)])
|
||||
def update_organization(org_id: str, payload: OrganizationUpdate):
|
||||
Session = get_session()
|
||||
try:
|
||||
oid = uuid.UUID(org_id)
|
||||
@@ -83,23 +82,14 @@ def update_organization(org_id: str, payload: OrganizationUpdate, _: object = De
|
||||
raise HTTPException(status_code=404, detail="Organization not found")
|
||||
if payload.name_organization is not None:
|
||||
org.name_organization = payload.name_organization
|
||||
if payload.group_id is not None:
|
||||
try:
|
||||
new_gid = uuid.UUID(payload.group_id)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="Invalid group_id UUID")
|
||||
grp = session.get(Group, new_gid)
|
||||
if not grp:
|
||||
raise HTTPException(status_code=404, detail="Group not found")
|
||||
org.group_id = new_gid
|
||||
session.add(org)
|
||||
session.commit()
|
||||
session.refresh(org)
|
||||
return {"id": str(org.id), "name_organization": org.name_organization, "group_id": str(org.group_id)}
|
||||
return _org_dict(org)
|
||||
|
||||
|
||||
@router.delete("/{org_id}", status_code=204)
|
||||
def delete_organization(org_id: str, _: object = Depends(get_current_user)):
|
||||
@router.delete("/{org_id}", status_code=204, dependencies=[Depends(require_admin_key)])
|
||||
def delete_organization(org_id: str):
|
||||
Session = get_session()
|
||||
try:
|
||||
oid = uuid.UUID(org_id)
|
||||
|
||||
@@ -3,14 +3,12 @@ from pydantic import BaseModel
|
||||
from typing import List, Optional
|
||||
import uuid
|
||||
|
||||
from bd import Settings
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from bd import make_engine
|
||||
|
||||
from bd.tables.poll import Poll
|
||||
from bd.tables.question import Question
|
||||
from bd.tables.choice import Choice
|
||||
from route.auth_utils import get_current_user
|
||||
from route.auth_utils import require_admin_key
|
||||
|
||||
router = APIRouter(tags=["polls"], prefix="/polls")
|
||||
|
||||
@@ -34,13 +32,12 @@ class PollIn(BaseModel):
|
||||
|
||||
|
||||
def get_session():
|
||||
settings = Settings()
|
||||
engine = create_engine(settings.DATABASE_URL_syncpg, future=True)
|
||||
return sessionmaker(bind=engine, future=True)
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
return sessionmaker(bind=make_engine(), future=True)
|
||||
|
||||
|
||||
@router.post("/", status_code=201)
|
||||
def create_poll(payload: PollIn, _: object = Depends(get_current_user)):
|
||||
@router.post("/", status_code=201, dependencies=[Depends(require_admin_key)])
|
||||
def create_poll(payload: PollIn):
|
||||
Session = get_session()
|
||||
with Session() as session:
|
||||
poll = Poll(title=payload.title, description=payload.description)
|
||||
|
||||
@@ -3,13 +3,11 @@ from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
import uuid
|
||||
|
||||
from bd import Settings
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from bd import make_engine
|
||||
|
||||
from bd.tables.question import Question
|
||||
from bd.tables.poll import Poll
|
||||
from route.auth_utils import get_current_user
|
||||
from route.auth_utils import require_admin_key
|
||||
|
||||
router = APIRouter(tags=["questions"], prefix="/questions")
|
||||
|
||||
@@ -28,13 +26,12 @@ class QuestionUpdate(BaseModel):
|
||||
|
||||
|
||||
def get_session():
|
||||
settings = Settings()
|
||||
engine = create_engine(settings.DATABASE_URL_syncpg, future=True)
|
||||
return sessionmaker(bind=engine, future=True)
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
return sessionmaker(bind=make_engine(), future=True)
|
||||
|
||||
|
||||
@router.post("/", status_code=201)
|
||||
def create_question(payload: QuestionCreate, _: object = Depends(get_current_user)):
|
||||
@router.post("/", status_code=201, dependencies=[Depends(require_admin_key)])
|
||||
def create_question(payload: QuestionCreate):
|
||||
Session = get_session()
|
||||
try:
|
||||
pid = uuid.UUID(payload.poll_id)
|
||||
@@ -51,8 +48,8 @@ def create_question(payload: QuestionCreate, _: object = Depends(get_current_use
|
||||
return {"id": str(q.id)}
|
||||
|
||||
|
||||
@router.put("/{question_id}")
|
||||
def update_question(question_id: str, payload: QuestionUpdate, _: object = Depends(get_current_user)):
|
||||
@router.put("/{question_id}", dependencies=[Depends(require_admin_key)])
|
||||
def update_question(question_id: str, payload: QuestionUpdate):
|
||||
Session = get_session()
|
||||
try:
|
||||
qid = uuid.UUID(question_id)
|
||||
@@ -74,8 +71,8 @@ def update_question(question_id: str, payload: QuestionUpdate, _: object = Depen
|
||||
return {"id": str(q.id)}
|
||||
|
||||
|
||||
@router.delete("/{question_id}", status_code=204)
|
||||
def delete_question(question_id: str, _: object = Depends(get_current_user)):
|
||||
@router.delete("/{question_id}", status_code=204, dependencies=[Depends(require_admin_key)])
|
||||
def delete_question(question_id: str):
|
||||
Session = get_session()
|
||||
try:
|
||||
qid = uuid.UUID(question_id)
|
||||
|
||||
@@ -3,9 +3,7 @@ from pydantic import BaseModel
|
||||
from typing import List, Optional
|
||||
import uuid
|
||||
|
||||
from bd import Settings
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from bd import make_engine
|
||||
|
||||
from bd.tables.poll import Poll
|
||||
from bd.tables.question import Question
|
||||
@@ -26,9 +24,8 @@ class ResponseIn(BaseModel):
|
||||
|
||||
|
||||
def get_session():
|
||||
settings = Settings()
|
||||
engine = create_engine(settings.DATABASE_URL_syncpg, future=True)
|
||||
return sessionmaker(bind=engine, future=True)
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
return sessionmaker(bind=make_engine(), future=True)
|
||||
|
||||
|
||||
@router.post("/{poll_id}/responses", status_code=201)
|
||||
@@ -71,6 +68,17 @@ def submit_response(poll_id: str, payload: ResponseIn):
|
||||
return {"id": str(resp.id)}
|
||||
|
||||
|
||||
@router.get("/responses/")
|
||||
def list_all_responses():
|
||||
Session = get_session()
|
||||
with Session() as session:
|
||||
rows = session.query(Response).all()
|
||||
return [
|
||||
{"id": str(r.id), "poll_id": str(r.poll_id), "user_id": str(r.user_id) if r.user_id else None, "submitted_at": r.submitted_at.isoformat()}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
@router.get("/{poll_id}/responses")
|
||||
def list_responses(poll_id: str):
|
||||
Session = get_session()
|
||||
|
||||
@@ -3,9 +3,7 @@ from pydantic import BaseModel, field_validator
|
||||
from typing import Optional
|
||||
import uuid
|
||||
|
||||
from bd import Settings
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from bd import make_engine
|
||||
|
||||
from bd.tables.users import User
|
||||
from route.auth_utils import get_current_user, require_admin_key, hash_password
|
||||
@@ -18,6 +16,8 @@ class UserCreate(BaseModel):
|
||||
password: str
|
||||
first_name: str
|
||||
last_name: str
|
||||
group_id: Optional[str] = None
|
||||
organization_id: Optional[str] = None
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
@@ -38,12 +38,24 @@ class UserCreate(BaseModel):
|
||||
class UserUpdate(BaseModel):
|
||||
first_name: Optional[str] = None
|
||||
last_name: Optional[str] = None
|
||||
group_id: Optional[str] = None
|
||||
organization_id: Optional[str] = None
|
||||
|
||||
|
||||
def get_session():
|
||||
settings = Settings()
|
||||
engine = create_engine(settings.DATABASE_URL_syncpg, future=True)
|
||||
return sessionmaker(bind=engine, future=True)
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
return sessionmaker(bind=make_engine(), future=True)
|
||||
|
||||
|
||||
def _user_dict(user: User) -> dict:
|
||||
return {
|
||||
"id": str(user.id),
|
||||
"username": user.username,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"group_id": str(user.group_id) if user.group_id else None,
|
||||
"organization_id": str(user.organization_id) if user.organization_id else None,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/", status_code=201, dependencies=[Depends(require_admin_key)])
|
||||
@@ -58,11 +70,13 @@ def create_user(payload: UserCreate):
|
||||
last_name=payload.last_name.strip(),
|
||||
username=payload.username,
|
||||
hashed_password=hash_password(payload.password),
|
||||
group_id=uuid.UUID(payload.group_id) if payload.group_id else None,
|
||||
organization_id=uuid.UUID(payload.organization_id) if payload.organization_id else None,
|
||||
)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
session.refresh(user)
|
||||
return {"id": str(user.id), "username": user.username}
|
||||
return _user_dict(user)
|
||||
|
||||
|
||||
@router.put("/{user_id}")
|
||||
@@ -82,10 +96,14 @@ def update_user(user_id: str, payload: UserUpdate, current_user: User = Depends(
|
||||
user.first_name = payload.first_name
|
||||
if payload.last_name is not None:
|
||||
user.last_name = payload.last_name
|
||||
if payload.group_id is not None:
|
||||
user.group_id = uuid.UUID(payload.group_id)
|
||||
if payload.organization_id is not None:
|
||||
user.organization_id = uuid.UUID(payload.organization_id)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
session.refresh(user)
|
||||
return {"id": str(user.id), "first_name": user.first_name, "last_name": user.last_name}
|
||||
return _user_dict(user)
|
||||
|
||||
|
||||
@router.delete("/{user_id}", status_code=204)
|
||||
@@ -108,7 +126,15 @@ def delete_user(user_id: str, current_user: User = Depends(get_current_user)):
|
||||
|
||||
@router.get("/me")
|
||||
def get_me(current_user: User = Depends(get_current_user)):
|
||||
return {"id": str(current_user.id), "username": current_user.username, "first_name": current_user.first_name, "last_name": current_user.last_name}
|
||||
return _user_dict(current_user)
|
||||
|
||||
|
||||
@router.get("/", dependencies=[Depends(require_admin_key)])
|
||||
def list_users():
|
||||
Session = get_session()
|
||||
with Session() as session:
|
||||
rows = session.query(User).all()
|
||||
return [_user_dict(u) for u in rows]
|
||||
|
||||
|
||||
@router.get("/{user_id}")
|
||||
@@ -122,4 +148,4 @@ def get_user(user_id: str, current_user: User = Depends(get_current_user)):
|
||||
user = session.get(User, uid)
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return {"id": str(user.id), "first_name": user.first_name, "last_name": user.last_name}
|
||||
return _user_dict(user)
|
||||
|
||||
Reference in New Issue
Block a user