def confirmEmail(userId:str): user = accountModel.UserAccount.objects(id=userId).first() if user: if user.active: responseData = {"message": "account already activated", "detail": { "login": "******", "url": f"{WEBSITE_URL}/{API_BASE_URI}/login", "body": {"email": "string", "password": "******"} }} return KhairoFullMixin.Response(userMessage=responseData, success=False, status_code=status.HTTP_401_UNAUTHORIZED) user.update(active=True) SuccessResponseData = { "user": user.to_json(indent=4), "message": "Account verified successfully", "extra":{ "login":"******", "method":"post", "body":{"email":"string", "password":"******"} } } return KhairoFullMixin.Response(userMessage=SuccessResponseData, status_code=status.HTTP_200_OK, success=True) ErrorResponseData = {"message": "Account does not exist"} return KhairoFullMixin.Response(userMessage=ErrorResponseData, status_code=status.HTTP_401_UNAUTHORIZED, success=False)
async def remove_single_service(serviceId: str, user: dict = Depends(AccountManager.authenticate_user)): """[remove or delete service] Args: serviceId (str): [service id to be removed] Returns: [type]: [objectId of the service deleted ] :param user: :param serviceId: """ if user["admin"]: old_data = Service.get_single_service(serviceId) if old_data: try: os.unlink(old_data.image_path) old_data.delete() return KhairoFullMixin.Response(userMessage={"id": serviceId}, status_code=status.HTTP_200_OK) except OSError as e: return KhairoFullMixin.Response(userMessage={"message": " error deleting service"}, status_code=status.HTTP_404_NOT_FOUND) except Exception as e: return KhairoFullMixin.Response(userMessage={"message": " error deleting service"}, status_code=status.HTTP_404_NOT_FOUND) return KhairoFullMixin.Response(userMessage={"message": " service does not exist"}, status_code=status.HTTP_404_NOT_FOUND) else: return KhairoFullMixin.Response(userMessage={"message": " error validating admin"}, status_code=status.HTTP_401_UNAUTHORIZED)
def passwordReset(userOldData:UserPasswordReset, userId:str): user = accountModel.UserAccount.objects(id=userId, email=userOldData.email) if user: if userOldData.password.strip() == userOldData.confirmPassword.strip(): newPassword = AccountManager.hash_password(password=userOldData.password) if newPassword: user.update(password=newPassword, passwordCode=None) SuccessResponseData = { "user": user.to_json(indent=4), "message": "password change successfully", "extra": { "login": "******", "method": "post", "body": {"email": "string", "password": "******"} } } return KhairoFullMixin.Response(userMessage=SuccessResponseData, status_code=status.HTTP_200_OK, success=True) ErrorResponseData = {"message": "could not change password"} return KhairoFullMixin.Response(userMessage=ErrorResponseData, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, success=False) ErrorResponseData = {"message": "password does not match "} return KhairoFullMixin.Response(userMessage=ErrorResponseData, status_code=status.HTTP_400_BAD_REQUEST, success=False) ErrorResponseData = {"message": "Account does not exist"} return KhairoFullMixin.Response(userMessage=ErrorResponseData, status_code=status.HTTP_401_UNAUTHORIZED, success=False)
async def update_service_option(optionId: str, user: dict = Depends(AccountManager.authenticate_user)): if user["admin"]: old_option = ServiceOption.get_single_option(optionId) if old_option: old_option.delete() return KhairoFullMixin.Response(userMessage={"id": optionId}, status_code=status.HTTP_200_OK) return KhairoFullMixin.Response(userMessage={"message": "error deleting option"}, status_code=status.HTTP_400_BAD_REQUEST) return KhairoFullMixin.Response(userMessage={"message": " error validating admin"}, status_code=status.HTTP_401_UNAUTHORIZED)
async def create_service_category(categoryId: str, user: dict = Depends(AccountManager.authenticate_user)): if user["admin"]: new_Category = Categories.get_single_category(categoryId) if new_Category: new_Category.delete() return KhairoFullMixin.Response(userMessage={"id": categoryId}, status_code=status.HTTP_200_OK) return KhairoFullMixin.Response(userMessage={"message": "category is found"}, status_code=status.HTTP_404_NOT_FOUND) return KhairoFullMixin.Response(userMessage={"message": " error validating admin"}, status_code=status.HTTP_401_UNAUTHORIZED)
async def create_service_option(optionData: OptionInput, user: dict = Depends(AccountManager.authenticate_user)): if user["admin"]: new_option = ServiceOption(**optionData.dict()) new_option.save(clean=True) if new_option: return KhairoFullMixin.Response(userMessage={"option": new_option.to_json()}, status_code=status.HTTP_201_CREATED) return KhairoFullMixin.Response(userMessage={"message": "error creating option"}, status_code=status.HTTP_400_BAD_REQUEST) return KhairoFullMixin.Response(userMessage={"message": " error validating admin"}, status_code=status.HTTP_401_UNAUTHORIZED)
async def create_service_category(category: CategoryInput, user: dict = Depends(AccountManager.authenticate_user)): if user["admin"]: new_Category = Categories(**category.dict()) new_Category.save(clean=True) if new_Category: return KhairoFullMixin.Response(userMessage={"category": new_Category.to_json()}, status_code=status.HTTP_201_CREATED) return KhairoFullMixin.Response(userMessage={"message": "error adding category"}, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) return KhairoFullMixin.Response(userMessage={"message": " error validating admin"}, status_code=status.HTTP_401_UNAUTHORIZED)
async def update_service_option(optionData: OptionUpdateInput, user: dict = Depends(AccountManager.authenticate_user)): if user["admin"]: update_option = ServiceOption.get_single_option(optionId=optionData.id) if update_option: update_option.update(option=optionData.option) update_option.save() return KhairoFullMixin.Response(userMessage={"option": update_option.to_json()}, status_code=status.HTTP_200_OK) return KhairoFullMixin.Response(userMessage={"message": "error creating option"}, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) return KhairoFullMixin.Response(userMessage={"message": " error validating admin"}, status_code=status.HTTP_401_UNAUTHORIZED)
def confirmEmail(userId: str): user = accountModel.UserAccount.objects(id=userId).first() if user: if user.active: responseData = {"message": "account already activated"} return KhairoFullMixin.Response(userMessage=responseData, status_code=status.HTTP_400_BAD_REQUEST) user.update(active=True) SuccessResponseData = {"message": "Account verified successfully"} return KhairoFullMixin.Response(userMessage=SuccessResponseData, status_code=status.HTTP_200_OK) ErrorResponseData = {"message": "Account does not exist"} return KhairoFullMixin.Response(userMessage=ErrorResponseData, status_code=status.HTTP_401_UNAUTHORIZED)
async def get_single_service(serviceId: str): """[get single service] Args: serviceId (str): [the service Id to be returned] Returns: [type]: [match service id if exist] """ service = Service.get_single_service(serviceId) if service: return KhairoFullMixin.Response(userMessage={"service": service.to_json()}, status_code=status.HTTP_200_OK) return KhairoFullMixin.Response(userMessage={"message": "service does not exist user"}, status_code=status.HTTP_400_BAD_REQUEST)
def getPasswordLink(userOldData: GetPasswordResetLink, background: BackgroundTasks): user = accountModel.UserAccount.get_singleUserByEmail(email=userOldData.email) if user: mailData = { "title": "Password reset", "message": f"password reset pass code\n Password reset link: {userOldData.passwordReset_url}/{user.id}" } background.add_task(KhairoFullMixin.mailUser, userEmail=user.email, emailTitle=mailData.get("title"), emailMessage=mailData.get("message")) ResponseData = {"message": "Check your email for password reset link"} return KhairoFullMixin.Response(userMessage=ResponseData, status_code=status.HTTP_200_OK) ErrorResponseData = {"message": "Account does not exist"} return KhairoFullMixin.Response(userMessage=ErrorResponseData, status_code=status.HTTP_401_UNAUTHORIZED)
async def create_service(serviceData: ServiceInput = Depends(ServiceInput.as_form), user: dict = Depends(AccountManager.authenticate_user)): """[creating new service] Args: serviceData (ServiceInput): [name, description, cover_img, price, options, categories] Returns: [type]: [new_service] :param user: :param serviceData: :type cover_img: object """ # file_type = cover_img.content_type[-3:] if user["admin"]: try: random_string = uuid4().hex file_location = f"{STATIC_DIR}/{random_string}{serviceData.cover_image.filename}" new_service = Service( name=serviceData.name, description=serviceData.description, price=serviceData.price, category=serviceData.category, options=serviceData.options.split(','), image_path=file_location, cover_img=f"{WEBSITE_URL}/{STATIC_FILE_NAME}/{random_string}{serviceData.cover_image.filename}" ).save() if new_service: await KhairoFullMixin.upload(fileObject=serviceData.cover_image, file_path=file_location) return KhairoFullMixin.Response( userMessage={"service": new_service.to_json()}, status_code=status.HTTP_201_CREATED) else: new_service.delete() return KhairoFullMixin.Response(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, userMessage={"error": "Error saving service"}) except NotUniqueError: return KhairoFullMixin.Response(userMessage={"message": "service with this name already exist"}, status_code=status.HTTP_400_BAD_REQUEST) return KhairoFullMixin.Response(userMessage={"message": " error validating admin"}, status_code=status.HTTP_401_UNAUTHORIZED)
def loginUserAccount(userIn: UserLoginInput, response: Response): user = accountModel.UserAccount.get_singleUserByEmail(email=userIn.email) if user: if user.active: if AccountManager.check_password(userIn.password, user.password): encode_jwt_access, encode_jwt_refresh = AccountManager.JwtEncoder( user=user.to_json()) if encode_jwt_access and encode_jwt_refresh: response.set_cookie(key="refresh_token", value=encode_jwt_refresh, httponly=True, max_age=172800, expires=172800, domain=WEBSITE_URL, secure=True) plan = accountModel.UserPlan.get_user_plan(userId=user.id) SuccessResponseData = { "user": user.to_json(indent=4), "plan": plan.active_plan.to_json() if plan else None, "message": "logged in successfully", "access_token": encode_jwt_access, "access_token_type": "Bearer", "expires": "2 days" } return KhairoFullMixin.Response(userMessage=SuccessResponseData, status_code=status.HTTP_200_OK) ErrorResponseData = {"message": "Password does not match"} return KhairoFullMixin.Response(userMessage=ErrorResponseData, status_code=status.HTTP_401_UNAUTHORIZED) ErrorResponseData = { "message": "Email was sent to you, please verify your email"} return KhairoFullMixin.Response(userMessage=ErrorResponseData, status_code=status.HTTP_401_UNAUTHORIZED) ErrorResponseData = {"message": "Account does not exist"} return KhairoFullMixin.Response(userMessage=ErrorResponseData, status_code=status.HTTP_401_UNAUTHORIZED)
def passwordReset(userOldData: UserPasswordReset): user = accountModel.UserAccount.objects(id=userOldData.userId).first() if user: if userOldData.password.strip() == userOldData.confirmPassword.strip(): newPassword = AccountManager.hash_password( password=userOldData.password) if newPassword: # user.update(password=newPassword, passwordCode=None) SuccessResponseData ={"message": "password change successfully"}, return KhairoFullMixin.Response(userMessage=SuccessResponseData, status_code=status.HTTP_200_OK) ErrorResponseData = {"message": "could not change password"} return KhairoFullMixin.Response(userMessage=ErrorResponseData, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) ErrorResponseData = {"message": "password does not match "} return KhairoFullMixin.Response(userMessage=ErrorResponseData, status_code=status.HTTP_400_BAD_REQUEST) ErrorResponseData = {"message": "Account does not exist"} return KhairoFullMixin.Response(userMessage=ErrorResponseData, status_code=status.HTTP_401_UNAUTHORIZED)
async def update_single_service(serviceData: ServiceUpdateInput, user: dict = Depends(AccountManager.authenticate_user)): """[updating service] Args: serviceData (ServiceUpdateInput): [any passed data] Returns: [type]: [update_service] :param serviceData: :param user: """ if user["admin"]: update_service = Service.get_single_service(serviceId=serviceData.id) if update_service: update_service.update(**serviceData.dict()) update_service.save(clean=True) if update_service: return KhairoFullMixin.Response(userMessage={"service": update_service.to_json()}, status_code=status.HTTP_200_OK) return KhairoFullMixin.Response(userMessage={"message": "Error updating service"}, status_code=status.HTTP_400_BAD_REQUEST) else: return KhairoFullMixin.Response(userMessage={"message": " error validating admin"}, status_code=status.HTTP_401_UNAUTHORIZED)
def registerUserAccount(user:UserRegisterationInput, background:BackgroundTasks): if accountModel.UserAccount.get_singleUserByEmail(email=user.email): ErrorResponse = {"message": "Account does not exist"} return KhairoFullMixin.Response(userMessage=ErrorResponse, success=False, status_code=status.HTTP_400_BAD_REQUEST) if user.password.strip() == user.confirmPassword.strip(): try: password = AccountManager.hash_password(password=user.password) newUserDetails = { "firstname": user.firstname, "lastname":user.lastname, "email": user.email, "password": password } newUser = accountModel.UserAccount(**newUserDetails).save(clean=True) if newUser: mailData = { "title":"Khairo diet Account verification", "message":f" Welcome to {WEBSITE_NAME}, {newUser.firstname} { newUser.lastname}\n " f"Your account was created successfully please " f"verify your email to continue\n {WEBSITE_URL}{API_BASE_URI}/user/{newUser.id}" } background.add_task(KhairoFullMixin.mailUser, userEmail=newUser.email, emailTitle=mailData.get("title"), emailMessage=mailData.get("message")) SuccessResponseData = { "user": {"firstname":newUser.firstname, "lastname":newUser.lastname}, "message": "Account was created successfully", "confirm email": "A mail was sent to your to confirm your email address" } return KhairoFullMixin.Response(userMessage=SuccessResponseData, success=True, status_code=status.HTTP_201_CREATED) ErrorResponse = {"message": "Error creating account, check your detail and try again"} return KhairoFullMixin.Response(userMessage=ErrorResponse, success=False, status_code=status.HTTP_400_BAD_REQUEST) except errors.ValidationError: ErrorResponse = {"message": "Error creating account, check your detail and try again"} return KhairoFullMixin.Response(userMessage=ErrorResponse, success=False, status_code=status.HTTP_400_BAD_REQUEST) except errors.NotUniqueError: ErrorResponse = {"message": "Account with this email already exist, try again"} return KhairoFullMixin.Response(userMessage=ErrorResponse, success=False, status_code=status.HTTP_400_BAD_REQUEST) ErrorResponse = {"message": "Password do not match, try again"} return KhairoFullMixin.Response(userMessage=ErrorResponse, success=False, status_code=status.HTTP_400_BAD_REQUEST)
async def get_service_option(): all_option = ServiceOption.get_all_option() if all_option: return KhairoFullMixin.Response(userMessage={"option": [option.to_json() for option in all_option]}, status_code=status.HTTP_200_OK) return KhairoFullMixin.Response(userMessage={"message": "no option is found"}, status_code=status.HTTP_401_UNAUTHORIZED)
async def get_all_service(): all_service = Service.get_all_service() if all_service: return KhairoFullMixin.Response(userMessage={"service": [service.to_json() for service in all_service]}, status_code=status.HTTP_200_OK) return KhairoFullMixin.Response(userMessage={"message": "error getting all product"}, status_code=status.HTTP_404_NOT_FOUND)
def getUserAccount(user: dict = Depends(AccountManager.authenticate_user)): plan = accountModel.UserPlan.get_user_plan(userid=user["id"]) return KhairoFullMixin.Response({"user": user, "plan": plan.active_plan.to_json() if plan else None}, status_code=status.HTTP_200_OK)
async def create_service_category(): get_all_category = Categories.get_all_category() if get_all_category: return KhairoFullMixin.Response(userMessage={"category": [category.to_json() for category in get_all_category]}, status_code=status.HTTP_200_OK) return KhairoFullMixin.Response(userMessage={"message": "no category is found"}, status_code=status.HTTP_404_NOT_FOUND)
async def update_service_option(optionId: str): single_option = ServiceOption.get_single_option(optionId) if single_option: return KhairoFullMixin.Response(userMessage={"option": single_option.to_json()}, status_code=status.HTTP_200_OK) return KhairoFullMixin.Response(userMessage={"message": "option does not exist"}, status_code=status.HTTP_404_NOT_FOUND)