add user? new page? new web
This commit is contained in:
74
route/auth.py
Normal file
74
route/auth.py
Normal file
@@ -0,0 +1,74 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from pydantic import BaseModel, field_validator
|
||||
|
||||
from bd import Settings
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from bd.tables.users import User
|
||||
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)
|
||||
|
||||
|
||||
class RegisterIn(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
first_name: str
|
||||
last_name: str
|
||||
|
||||
@field_validator("password")
|
||||
@classmethod
|
||||
def password_strength(cls, v: str) -> str:
|
||||
if len(v) < 8:
|
||||
raise ValueError("Password must be at least 8 characters")
|
||||
return v
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def username_clean(cls, v: str) -> str:
|
||||
v = v.strip()
|
||||
if len(v) < 3:
|
||||
raise ValueError("Username must be at least 3 characters")
|
||||
return v
|
||||
|
||||
|
||||
@router.post("/register", status_code=201)
|
||||
def register(payload: RegisterIn):
|
||||
Session = _get_session()
|
||||
with Session() as session:
|
||||
existing = session.query(User).filter(User.username == payload.username).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Username already taken")
|
||||
user = User(
|
||||
first_name=payload.first_name.strip(),
|
||||
last_name=payload.last_name.strip(),
|
||||
username=payload.username,
|
||||
hashed_password=hash_password(payload.password),
|
||||
)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
session.refresh(user)
|
||||
return {"id": str(user.id), "username": user.username}
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
def login(form: OAuth2PasswordRequestForm = Depends()):
|
||||
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):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect username or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
token = create_access_token({"sub": str(user.id)})
|
||||
return {"access_token": token, "token_type": "bearer"}
|
||||
99
route/auth_utils.py
Normal file
99
route/auth_utils.py
Normal file
@@ -0,0 +1,99 @@
|
||||
import hashlib
|
||||
import os
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends, Header, HTTPException, status
|
||||
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
|
||||
|
||||
SECRET_KEY: str = os.getenv("SECRET_KEY", "")
|
||||
if not SECRET_KEY:
|
||||
import secrets
|
||||
SECRET_KEY = secrets.token_hex(32)
|
||||
print("WARNING: SECRET_KEY not set in environment. Using a random key — tokens will be invalidated on restart!")
|
||||
|
||||
ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "60"))
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
|
||||
|
||||
|
||||
def _prehash(password: str) -> str:
|
||||
"""SHA-256 пред-хеш чтобы обойти 72-байтовый лимит bcrypt."""
|
||||
return hashlib.sha256(password.encode()).hexdigest()
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return pwd_context.hash(_prehash(password))
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
return pwd_context.verify(_prehash(plain), hashed)
|
||||
|
||||
|
||||
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
|
||||
to_encode = data.copy()
|
||||
expire = datetime.now(timezone.utc) + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
|
||||
to_encode["exp"] = expire
|
||||
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_current_user(token: str = Depends(oauth2_scheme)):
|
||||
"""FastAPI dependency: валидирует Bearer-токен и возвращает объект User."""
|
||||
credentials_exc = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
try:
|
||||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||
user_id: str = payload.get("sub")
|
||||
if user_id is None:
|
||||
raise credentials_exc
|
||||
except JWTError:
|
||||
raise credentials_exc
|
||||
|
||||
from bd.tables.users import User
|
||||
|
||||
try:
|
||||
uid = uuid.UUID(user_id)
|
||||
except Exception:
|
||||
raise credentials_exc
|
||||
|
||||
Session = _get_session()
|
||||
with Session() as session:
|
||||
user = session.get(User, uid)
|
||||
if user is None:
|
||||
raise credentials_exc
|
||||
# detach from session so object can be used outside
|
||||
session.expunge(user)
|
||||
return user
|
||||
|
||||
|
||||
def require_admin_key(x_admin_key: Optional[str] = Header(default=None)):
|
||||
"""FastAPI dependency: проверяет секретный ключ администратора (заголовок X-Admin-Key)."""
|
||||
admin_key = os.getenv("ADMIN_KEY", "")
|
||||
if not admin_key:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Admin access is disabled: ADMIN_KEY not configured",
|
||||
)
|
||||
if x_admin_key != admin_key:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Invalid admin key",
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
import uuid
|
||||
@@ -9,6 +9,7 @@ from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from bd.tables.choice import Choice
|
||||
from bd.tables.question import Question
|
||||
from route.auth_utils import get_current_user
|
||||
|
||||
router = APIRouter(tags=["choices"], prefix="/choices")
|
||||
|
||||
@@ -31,7 +32,7 @@ def get_session():
|
||||
|
||||
|
||||
@router.post("/", status_code=201)
|
||||
def create_choice(payload: ChoiceCreate):
|
||||
def create_choice(payload: ChoiceCreate, _: object = Depends(get_current_user)):
|
||||
Session = get_session()
|
||||
try:
|
||||
qid = uuid.UUID(payload.question_id)
|
||||
@@ -49,7 +50,7 @@ def create_choice(payload: ChoiceCreate):
|
||||
|
||||
|
||||
@router.put("/{choice_id}")
|
||||
def update_choice(choice_id: str, payload: ChoiceUpdate):
|
||||
def update_choice(choice_id: str, payload: ChoiceUpdate, _: object = Depends(get_current_user)):
|
||||
Session = get_session()
|
||||
try:
|
||||
cid = uuid.UUID(choice_id)
|
||||
@@ -70,7 +71,7 @@ def update_choice(choice_id: str, payload: ChoiceUpdate):
|
||||
|
||||
|
||||
@router.delete("/{choice_id}", status_code=204)
|
||||
def delete_choice(choice_id: str):
|
||||
def delete_choice(choice_id: str, _: object = Depends(get_current_user)):
|
||||
Session = get_session()
|
||||
try:
|
||||
cid = uuid.UUID(choice_id)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
import uuid
|
||||
@@ -9,6 +9,7 @@ from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from bd.tables.group import Group
|
||||
from bd.tables.users import User
|
||||
from route.auth_utils import get_current_user
|
||||
|
||||
router = APIRouter(tags=["groups"], prefix="/groups")
|
||||
|
||||
@@ -30,7 +31,7 @@ def get_session():
|
||||
|
||||
|
||||
@router.post("/", status_code=201)
|
||||
def create_group(payload: GroupCreate):
|
||||
def create_group(payload: GroupCreate, _: object = Depends(get_current_user)):
|
||||
Session = get_session()
|
||||
try:
|
||||
uid = uuid.UUID(payload.user_id)
|
||||
@@ -70,7 +71,7 @@ def get_group(group_id: str):
|
||||
|
||||
|
||||
@router.put("/{group_id}")
|
||||
def update_group(group_id: str, payload: GroupUpdate):
|
||||
def update_group(group_id: str, payload: GroupUpdate, _: object = Depends(get_current_user)):
|
||||
Session = get_session()
|
||||
try:
|
||||
gid = uuid.UUID(group_id)
|
||||
@@ -98,7 +99,7 @@ def update_group(group_id: str, payload: GroupUpdate):
|
||||
|
||||
|
||||
@router.delete("/{group_id}", status_code=204)
|
||||
def delete_group(group_id: str):
|
||||
def delete_group(group_id: str, _: object = Depends(get_current_user)):
|
||||
Session = get_session()
|
||||
try:
|
||||
gid = uuid.UUID(group_id)
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
import pkgutil
|
||||
import importlib
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
from bd import Settings
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from pydantic import BaseModel
|
||||
|
||||
from route.auth_utils import require_admin_key
|
||||
|
||||
router = APIRouter(tags=["db"])
|
||||
|
||||
|
||||
@@ -40,7 +42,7 @@ def collect_metadatas():
|
||||
return metadatas
|
||||
|
||||
|
||||
@router.post("/db/create-tables")
|
||||
@router.post("/db/create-tables", dependencies=[Depends(require_admin_key)])
|
||||
async def create_tables():
|
||||
"""Создаёт все таблицы, описанные в модулях `db.tables`.
|
||||
|
||||
@@ -70,11 +72,29 @@ async def create_tables():
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@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)
|
||||
try:
|
||||
with engine.connect() as conn:
|
||||
conn.execute(text("""
|
||||
ALTER TABLE users
|
||||
ADD COLUMN IF NOT EXISTS username VARCHAR(150),
|
||||
ADD COLUMN IF NOT EXISTS hashed_password VARCHAR(256)
|
||||
"""))
|
||||
conn.commit()
|
||||
return {"status": "ok", "detail": "Columns username and hashed_password ensured in users table"}
|
||||
except SQLAlchemyError as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
class ClearDBIn(BaseModel):
|
||||
confirm: bool
|
||||
|
||||
|
||||
@router.post("/db/clear")
|
||||
@router.post("/db/clear", dependencies=[Depends(require_admin_key)])
|
||||
async def clear_tables(payload: ClearDBIn):
|
||||
"""Полная очистка всех таблиц, описанных в `bd.tables`.
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
import uuid
|
||||
@@ -9,6 +9,7 @@ from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from bd.tables.organization import Organization
|
||||
from bd.tables.group import Group
|
||||
from route.auth_utils import get_current_user
|
||||
|
||||
router = APIRouter(tags=["organizations"], prefix="/organizations")
|
||||
|
||||
@@ -30,7 +31,7 @@ def get_session():
|
||||
|
||||
|
||||
@router.post("/", status_code=201)
|
||||
def create_organization(payload: OrganizationCreate):
|
||||
def create_organization(payload: OrganizationCreate, _: object = Depends(get_current_user)):
|
||||
Session = get_session()
|
||||
try:
|
||||
gid = uuid.UUID(payload.group_id)
|
||||
@@ -70,7 +71,7 @@ def get_organization(org_id: str):
|
||||
|
||||
|
||||
@router.put("/{org_id}")
|
||||
def update_organization(org_id: str, payload: OrganizationUpdate):
|
||||
def update_organization(org_id: str, payload: OrganizationUpdate, _: object = Depends(get_current_user)):
|
||||
Session = get_session()
|
||||
try:
|
||||
oid = uuid.UUID(org_id)
|
||||
@@ -98,7 +99,7 @@ def update_organization(org_id: str, payload: OrganizationUpdate):
|
||||
|
||||
|
||||
@router.delete("/{org_id}", status_code=204)
|
||||
def delete_organization(org_id: str):
|
||||
def delete_organization(org_id: str, _: object = Depends(get_current_user)):
|
||||
Session = get_session()
|
||||
try:
|
||||
oid = uuid.UUID(org_id)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Optional
|
||||
import uuid
|
||||
@@ -10,6 +10,7 @@ from sqlalchemy.orm import sessionmaker
|
||||
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
|
||||
|
||||
router = APIRouter(tags=["polls"], prefix="/polls")
|
||||
|
||||
@@ -39,7 +40,7 @@ def get_session():
|
||||
|
||||
|
||||
@router.post("/", status_code=201)
|
||||
def create_poll(payload: PollIn):
|
||||
def create_poll(payload: PollIn, _: object = Depends(get_current_user)):
|
||||
Session = get_session()
|
||||
with Session() as session:
|
||||
poll = Poll(title=payload.title, description=payload.description)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
import uuid
|
||||
@@ -9,6 +9,7 @@ from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from bd.tables.question import Question
|
||||
from bd.tables.poll import Poll
|
||||
from route.auth_utils import get_current_user
|
||||
|
||||
router = APIRouter(tags=["questions"], prefix="/questions")
|
||||
|
||||
@@ -33,7 +34,7 @@ def get_session():
|
||||
|
||||
|
||||
@router.post("/", status_code=201)
|
||||
def create_question(payload: QuestionCreate):
|
||||
def create_question(payload: QuestionCreate, _: object = Depends(get_current_user)):
|
||||
Session = get_session()
|
||||
try:
|
||||
pid = uuid.UUID(payload.poll_id)
|
||||
@@ -51,7 +52,7 @@ def create_question(payload: QuestionCreate):
|
||||
|
||||
|
||||
@router.put("/{question_id}")
|
||||
def update_question(question_id: str, payload: QuestionUpdate):
|
||||
def update_question(question_id: str, payload: QuestionUpdate, _: object = Depends(get_current_user)):
|
||||
Session = get_session()
|
||||
try:
|
||||
qid = uuid.UUID(question_id)
|
||||
@@ -74,7 +75,7 @@ def update_question(question_id: str, payload: QuestionUpdate):
|
||||
|
||||
|
||||
@router.delete("/{question_id}", status_code=204)
|
||||
def delete_question(question_id: str):
|
||||
def delete_question(question_id: str, _: object = Depends(get_current_user)):
|
||||
Session = get_session()
|
||||
try:
|
||||
qid = uuid.UUID(question_id)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, field_validator
|
||||
from typing import Optional
|
||||
import uuid
|
||||
|
||||
@@ -8,18 +8,36 @@ from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from bd.tables.users import User
|
||||
from route.auth_utils import get_current_user, require_admin_key, hash_password
|
||||
|
||||
router = APIRouter(tags=["users"], prefix="/users")
|
||||
|
||||
|
||||
class UserCreate(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
first_name: str
|
||||
last_name: str
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def username_clean(cls, v: str) -> str:
|
||||
v = v.strip()
|
||||
if len(v) < 3:
|
||||
raise ValueError("Username must be at least 3 characters")
|
||||
return v
|
||||
|
||||
@field_validator("password")
|
||||
@classmethod
|
||||
def password_strength(cls, v: str) -> str:
|
||||
if len(v) < 8:
|
||||
raise ValueError("Password must be at least 8 characters")
|
||||
return v
|
||||
|
||||
|
||||
class UserUpdate(BaseModel):
|
||||
first_name: Optional[str]
|
||||
last_name: Optional[str]
|
||||
first_name: Optional[str] = None
|
||||
last_name: Optional[str] = None
|
||||
|
||||
|
||||
def get_session():
|
||||
@@ -28,24 +46,34 @@ def get_session():
|
||||
return sessionmaker(bind=engine, future=True)
|
||||
|
||||
|
||||
@router.post("/", status_code=201)
|
||||
@router.post("/", status_code=201, dependencies=[Depends(require_admin_key)])
|
||||
def create_user(payload: UserCreate):
|
||||
Session = get_session()
|
||||
with Session() as session:
|
||||
user = User(first_name=payload.first_name, last_name=payload.last_name)
|
||||
existing = session.query(User).filter(User.username == payload.username).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Username already taken")
|
||||
user = User(
|
||||
first_name=payload.first_name.strip(),
|
||||
last_name=payload.last_name.strip(),
|
||||
username=payload.username,
|
||||
hashed_password=hash_password(payload.password),
|
||||
)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
session.refresh(user)
|
||||
return {"id": str(user.id), "first_name": user.first_name, "last_name": user.last_name}
|
||||
return {"id": str(user.id), "username": user.username}
|
||||
|
||||
|
||||
@router.put("/{user_id}")
|
||||
def update_user(user_id: str, payload: UserUpdate):
|
||||
def update_user(user_id: str, payload: UserUpdate, current_user: User = Depends(get_current_user)):
|
||||
Session = get_session()
|
||||
try:
|
||||
uid = uuid.UUID(user_id)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="Invalid UUID")
|
||||
if uid != current_user.id:
|
||||
raise HTTPException(status_code=403, detail="You can only update your own profile")
|
||||
with Session() as session:
|
||||
user = session.get(User, uid)
|
||||
if not user:
|
||||
@@ -61,12 +89,14 @@ def update_user(user_id: str, payload: UserUpdate):
|
||||
|
||||
|
||||
@router.delete("/{user_id}", status_code=204)
|
||||
def delete_user(user_id: str):
|
||||
def delete_user(user_id: str, current_user: User = Depends(get_current_user)):
|
||||
Session = get_session()
|
||||
try:
|
||||
uid = uuid.UUID(user_id)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="Invalid UUID")
|
||||
if uid != current_user.id:
|
||||
raise HTTPException(status_code=403, detail="You can only delete your own account")
|
||||
with Session() as session:
|
||||
user = session.get(User, uid)
|
||||
if not user:
|
||||
@@ -76,16 +106,13 @@ def delete_user(user_id: str):
|
||||
return {}
|
||||
|
||||
|
||||
@router.get("/")
|
||||
def list_users():
|
||||
Session = get_session()
|
||||
with Session() as session:
|
||||
rows = session.query(User).all()
|
||||
return [{"id": str(u.id), "first_name": u.first_name, "last_name": u.last_name} for u in rows]
|
||||
@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}
|
||||
|
||||
|
||||
@router.get("/{user_id}")
|
||||
def get_user(user_id: str):
|
||||
def get_user(user_id: str, current_user: User = Depends(get_current_user)):
|
||||
Session = get_session()
|
||||
try:
|
||||
uid = uuid.UUID(user_id)
|
||||
|
||||
Reference in New Issue
Block a user