@router.post("/register")
async def register(user: UserCreate, background_tasks: BackgroundTasks):
existing_user = await find_one_user({"email": user.email})
if existing_user:
raise HTTPException(status_code=400, detail="Email already registered")
hashed_password = bcrypt.hashpw(user.password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
confirmation_token = str(uuid.uuid4())
new_user = {
"username": user.username,
"email": user.email,
"hashed_password": hashed_password,
"is_active": False,
"confirmation_token": confirmation_token
}
await write_new_user(new_user)
background_tasks.add_task(send_confirmation_email, user.email, confirmation_token, config.BASE_URL)
print(f"{confirmation_token=}")
return {"message": "Registration successful. Please check your email to confirm your account."}
@router.post("/login")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
db_user = await find_one_user({"username": form_data.username})
if not db_user:
raise HTTPException(status_code=401, detail="Invalid username or password")
if not bcrypt.checkpw(form_data.password.encode('utf-8'), db_user["hashed_password"].encode('utf-8')):
raise HTTPException(status_code=401, detail="Invalid username or password")
if not db_user["is_active"]:
raise HTTPException(status_code=400, detail="Email not confirmed")
access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": db_user["username"]}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}