Add a create_user method for register data

This commit is contained in:
Peter Vacho 2024-12-25 20:22:00 +01:00
parent 3c2bc1c10e
commit e0b77d7ff2
Signed by: school
GPG key ID: 8CFC3837052871B4

View file

@ -30,6 +30,12 @@ class RegisterData(BaseModel):
password: Annotated[str, StringConstraints(min_length=1, max_length=50)] password: Annotated[str, StringConstraints(min_length=1, max_length=50)]
email: EmailStr email: EmailStr
async def create_user(self) -> User:
"""Create a new user in the database."""
password_hash = create_password_hash(self.password)
user = User(username=self.username, email=self.email, password_hash=password_hash)
return await user.create()
@final @final
class UserData(BaseModel): class UserData(BaseModel):
@ -93,9 +99,7 @@ async def register(reg_data: Annotated[RegisterData, Body()]) -> UserData:
if user is not None: if user is not None:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Username already taken") raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Username already taken")
password_hash = create_password_hash(reg_data.password) user = await reg_data.create_user()
user = User(username=reg_data.username, email=reg_data.email, password_hash=password_hash)
user = await user.insert()
return UserData.from_user(user) return UserData.from_user(user)