async def register( request: Request, email: EmailStr = Form(...), password: SecretStr = Form(...), password_confirm: SecretStr = Form(...), ): successful = False reason = None # check if the two passwords are the same if password == password_confirm: # check if the user already exists in the database if ( await User.query.where(User.user_email == email.lower()).gino.first() is not None ): # if so set the corresponding reason reason = "Already registered." else: # if the user is not already in the database, insert their await User.create( user_uuid=uuid.uuid4(), user_email=email.lower(), user_password_hash=ph.hash(password.get_secret_value()), ) # set successful to True after the insert was successful successful = True else: # The passwords are not the same. Set the corresponding reason. reason = "Passwords not equal." # render the response template. See the template file to know what is displayed when return main.templates.TemplateResponse( "register_response.html", { "request": request, "reason": reason, "successful": successful, "email": email.lower(), }, )
async def login( request: Request, email: EmailStr = Form(...), password: SecretStr = Form(...) ): successful = False reason = None token = None # search for a user model in the database. If there's no, return None if ( user := await User.query.where(User.user_email == email.lower()).gino.first() ) is not None: # verify the password hash from the database against the password in the request try: if ph.verify(user.user_password_hash, password.get_secret_value()): # set to True since the password is correct successful = True # check if the password needs a rehash (e.g. because stronger hashing # options are used) # This is only possible on login because the client sends the password. if ph.check_needs_rehash(user.user_password_hash): # update the new password hash in the database await user.update( user_password_hash=ph.hash(password.get_secret_value()) ) # create a session token. Sessions are only validated by their signature token = jwt.encode( { "sub": str(user.user_uuid), "exp": datetime.utcnow() + timedelta(weeks=1), }, key=config.SESSION_SECRET.get_secret_value(), algorithm="HS256", ) except VerifyMismatchError: # the password hashes don't match -> wrong password successful = False reason = "Wrong password."