class AuthService(object): def __init__(self): self.task_service = TaskService() self.user_manager = UserManager() self.auth_user_login_serializer = AuthUserLoginSerializer() self.auth_user_confirm_reset_password = AuthUserConfirmResetPasswordSerializer( ) def login_user(self, **kwargs) -> str: data = filter_by_keys(kwargs, auth_login_sw_model.keys()) user = self.auth_user_login_serializer.load(data) token = generate_login_token(user) # TODO: Pending to testing whats happen if add a new field in user model when a user is logged flask_security.login_user(user) return token @staticmethod def logout_user(): # TODO: check if the user is logged flask_security.logout_user() def request_reset_password(self, **kwargs): data = filter_by_keys(kwargs, auth_user_reset_password_sw_model.keys()) user = self.auth_user_login_serializer.load(data, partial=True) token = user.get_reset_token() reset_password_url = url_for('auth_reset_password_resource', token=token, _external=True) email_data = { 'email': user.email, 'reset_password_url': reset_password_url, } self.task_service.reset_password_email(**email_data) def check_token_status(self, token): data = filter_by_keys(data={'token': token}, keys=['token']) self.auth_user_confirm_reset_password.load(data, partial=True) def confirm_request_reset_password(self, token: str, password: str) -> str: data = filter_by_keys(data={ 'token': token, 'password': password }, keys=['token', 'password']) user = self.auth_user_confirm_reset_password.load(data) self.user_manager.save(user.id, **{'password': password}) return generate_login_token(user.reload())
class UserService(BaseService): def __init__(self, *args, **kwargs): super(UserService, self).__init__(*args, **kwargs) self.manager = UserManager() self.role_manager = RoleManager() self.user_serializer = UserSerializer() def create(self, user_data): deserialized_data = self.user_serializer.load(user_data) with db_wrapper.database.atomic(): role = self.role_manager.find(deserialized_data['role_id']) user = self.manager.get_last_record() fs_uniquifier = 1 if user is None else user.id + 1 deserialized_data.update({ 'created_by': current_user.id, 'roles': [role], 'fs_uniquifier': fs_uniquifier }) user = user_datastore.create_user(**deserialized_data) return user def find(self, user_id: int, *args): self.user_serializer.load({'id': user_id}, partial=True) return self.manager.find(user_id, *args) def save(self, user_id: int, **kwargs): kwargs['id'] = user_id data = self.user_serializer.load(kwargs, unknown=EXCLUDE) user = self.manager.find(user_id) with db_wrapper.database.atomic(): self.manager.save(user_id, **data) if 'role_id' in data: user_datastore.remove_role_from_user(user, user.roles[0]) role = self.role_manager.find(data['role_id']) user_datastore.add_role_to_user(user, role) return user.reload() def delete(self, user_id: int): self.user_serializer.load({'id': user_id}, partial=True) return self.manager.delete(user_id)