summaryrefslogtreecommitdiff
path: root/app/auth/register.py
blob: f1c3ec3ce8286ea4b1ac6e6dd2610b0f6df57d40 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from app.models.auth import User
from argon2 import PasswordHasher
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select

from app.schemas.auth import RegisterSchema
from app.utils.db import get_db

router = APIRouter()
ph = PasswordHasher()


@router.post("/register")
async def register(user: RegisterSchema, db: AsyncSession = Depends(get_db)):
    result = await db.execute(
        select(User).where(
            (User.username == user.username) | (User.email == user.email)
        )
    )
    existing = result.scalar_one_or_none()
    if existing:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Username or email already exists",
        )

    hashed = ph.hash(user.password)
    new_user = User(username=user.username, email=user.email, password_hash=hashed)
    db.add(new_user)
    await db.commit()
    return {"message": "User registered successfully"}