generated from pptx704/fastapi-template
53 lines
1.5 KiB
Python
53 lines
1.5 KiB
Python
from fastapi import HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app import schemas
|
|
from app.models import User
|
|
from app.security import create_jwt_token, get_password_hash, verify_password
|
|
|
|
|
|
def register(
|
|
request: schemas.RegistrationRequest, db: Session
|
|
) -> schemas.BaseResponse:
|
|
if db.query(User).filter(User.email == request.email).first():
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Email already registered",
|
|
)
|
|
|
|
if request.password != request.confirm_password:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Passwords do not match",
|
|
)
|
|
|
|
user = User(
|
|
name=request.name,
|
|
email=request.email,
|
|
password_hash=get_password_hash(request.password),
|
|
)
|
|
|
|
db.add(user)
|
|
db.commit()
|
|
|
|
return schemas.BaseResponse(message="Registration successful")
|
|
|
|
|
|
def login(request: schemas.LoginRequest, db: Session):
|
|
user = db.query(User).filter(User.email == request.email).first()
|
|
|
|
if not user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND, detail="User not found"
|
|
)
|
|
|
|
if not verify_password(request.password, user.password_hash):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Incorrect password",
|
|
)
|
|
|
|
token = create_jwt_token({"user_id": str(user.id)})
|
|
|
|
return schemas.LoginResponse(token=token, verified=user.is_verified)
|