together_backend/src/router/signup.py

47 lines
1.4 KiB
Python

from typing import Literal
from fastapi import APIRouter, BackgroundTasks
from pydantic import BaseModel
from ..utils.email_code import send_email, verify_code
from ..crud import user_account
from ..utils.password import *
router = APIRouter(tags=['signup'], prefix='/signup', redirect_slashes=False)
class SignUpAccount(BaseModel):
username: str
password: str
email: str
code: str
@router.get('/has_existed')
async def has_account_existed(condition: Literal['username', 'email'], value: str):
(res, _) = await user_account.select_user_by(condition, value)
if res:
return {'code': 10101, 'msg': f'{condition.capitalize()} Has Existed'}
else:
return {'code': 10100, 'msg': f'{condition.capitalize()} Has Not Been Used'}
@router.get('/code/{email}')
async def get_code(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(send_email, email)
return {'code': 10100, 'msg': 'Get verification Code Success'}
@router.post('')
async def sign_up(signup_account: SignUpAccount):
verification_res = verify_code(signup_account.email, signup_account.code)
if not verification_res:
return {'code': 10102, 'msg': 'Code Is Incorrect or Code Is Out of Date'}
hashed_password = get_hashed_password(signup_account.password)
await user_account.insert_user(signup_account.username, hashed_password, signup_account.email)
return {'code': 10100, 'msg': 'Sign up successfully'}