init
This commit is contained in:
0
app/auth/__init__.py
Normal file
0
app/auth/__init__.py
Normal file
49
app/auth/dependencies.py
Normal file
49
app/auth/dependencies.py
Normal file
@@ -0,0 +1,49 @@
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from app.connection import get_session
|
||||
from app.models.user import User
|
||||
from app.auth.utils import decode_access_token
|
||||
|
||||
security = HTTPBearer()
|
||||
|
||||
|
||||
def get_current_user(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
session: Session = Depends(get_session),
|
||||
) -> User:
|
||||
"""Извлекает текущего пользователя из JWT-токена."""
|
||||
payload = decode_access_token(credentials.credentials)
|
||||
if payload is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Невалидный токен",
|
||||
)
|
||||
|
||||
user_id: int | None = payload.get("sub")
|
||||
if user_id is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Невалидный токен",
|
||||
)
|
||||
|
||||
user = session.get(User, int(user_id))
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Пользователь не найден",
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
def get_current_organizer(
|
||||
current_user: User = Depends(get_current_user),
|
||||
) -> User:
|
||||
"""Проверяет, что текущий пользователь — организатор."""
|
||||
if not current_user.is_organizer:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Доступно только организаторам",
|
||||
)
|
||||
return current_user
|
||||
44
app/auth/router.py
Normal file
44
app/auth/router.py
Normal file
@@ -0,0 +1,44 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from app.connection import get_session
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserCreate, UserRead, Token, LoginRequest
|
||||
from app.auth.utils import hash_password, verify_password, create_access_token
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["Auth"])
|
||||
|
||||
|
||||
@router.post("/register", response_model=UserRead, status_code=status.HTTP_201_CREATED)
|
||||
def register(data: UserCreate, session: Session = Depends(get_session)) -> User:
|
||||
existing = session.exec(select(User).where(User.email == data.email)).first()
|
||||
if existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Пользователь с таким email уже существует",
|
||||
)
|
||||
|
||||
user = User(
|
||||
name=data.name,
|
||||
email=data.email,
|
||||
phone=data.phone,
|
||||
hashed_password=hash_password(data.password),
|
||||
is_organizer=data.is_organizer,
|
||||
)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
session.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
@router.post("/login", response_model=Token)
|
||||
def login(data: LoginRequest, session: Session = Depends(get_session)) -> dict:
|
||||
user = session.exec(select(User).where(User.email == data.email)).first()
|
||||
if not user or not verify_password(data.password, user.hashed_password):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Неверный email или пароль",
|
||||
)
|
||||
|
||||
access_token = create_access_token({"sub": str(user.id)})
|
||||
return {"access_token": access_token, "token_type": "bearer"}
|
||||
29
app/auth/utils.py
Normal file
29
app/auth/utils.py
Normal file
@@ -0,0 +1,29 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import bcrypt
|
||||
import jwt
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
return bcrypt.checkpw(plain_password.encode(), hashed_password.encode())
|
||||
|
||||
|
||||
def create_access_token(data: dict) -> str:
|
||||
to_encode = data.copy()
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
|
||||
to_encode.update({"exp": expire})
|
||||
return jwt.encode(to_encode, settings.secret_key, algorithm=settings.algorithm)
|
||||
|
||||
|
||||
def decode_access_token(token: str) -> dict | None:
|
||||
"""Декодирует JWT-токен. Возвращает payload или None при ошибке."""
|
||||
try:
|
||||
return jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
|
||||
except jwt.PyJWTError:
|
||||
return None
|
||||
Reference in New Issue
Block a user