def post(cls): """Post method""" user_data = user_schema.load(request.get_json()) if UserModel.find_by_username(user_data.username): return { "message": "A user with that username already exists." }, 400 user_data.password = generate_password_hash(user_data.password) user_data.is_admin = False user_data.is_staff = False try: user_data.save_to_db() user = UserModel.find_by_username(user_data.username) user_profile = UserProfileModel(user_id=user.id) user_profile.save_to_db() expires = datetime.timedelta(days=1) access_token = create_access_token(identity=user.id, fresh=True, expires_delta=expires) except: return {"message": "An error occurred creating the user."}, 500 return ( { "message": "User created successfully.", "access_token": access_token, "username": user.username, "user": user.id, }, 201, )
def post(cls): """Register a user""" claims = get_jwt_claims() if not claims["is_admin"]: return ( { "message": "You don't have permission to perform this action." }, 403, ) user_data = user_schema.load(request.get_json()) if UserModel.find_by_username(user_data.username): return {"message": "A user with that username already exists."}, 400 user_data.password = generate_password_hash(user_data.password) try: user_data.save_to_db() user = UserModel.find_by_username(user_data.username) user_profile = UserProfileModel(user_id=user.id) user_profile.save_to_db() except: return {"message": "An error occurred creating the user."}, 500 return {"message": "User created successfully."}, 201
def test_userprofile_is_saved_in_db(self): """Test if the user profile has been successfully saved in the database after creating a new user""" user = UserModel(username="******", password="******") user.save_to_db() userprofile = UserProfileModel(user_id=user.id) userprofile.save_to_db() found_userprofile = UserProfileModel.find_by_username(user.username) self.assertIsNotNone(found_userprofile)
def create_admin(self): """Create a user model and a user profile model and save them to the database""" with app.app_context(): hashed_pass = generate_password_hash(self.password) user = UserModel( username=self.username, password=hashed_pass, is_admin=True, is_staff=True, ) user.save_to_db() user_profile = UserProfileModel(user_id=user.id) user_profile.save_to_db()
def _create_sample_user( cls, username: str = "testuser", height=185, weight=70, gender="Male", age=25, ) -> "UserModel": """Create a sample user""" user = UserModel(username=username, password=generate_password_hash("testpass")) user.save_to_db() user_profile = UserProfileModel( user_id=user.id, height=height, weight=weight, gender=gender, age=age, ) user_profile.save_to_db() return user