def wrapper(*args: List[Any], **kwargs: Dict[str, Any]) -> Any: if self.disabled: a = JWTUser( id=1, impersonator=1, type="users", groups=[ JWTGroup(id="admin", name="admin", role=RoleType.ADMIN) ], ) g.user = a return fn(*args, **kwargs) self.verify() user = JWTUser.from_dict(self.get_identity()) g.user = user if not admin: return fn(*args, **kwargs) if user.is_site_admin(): return fn(*args, **kwargs) else: return "User unauthorized", 403
def test_set_public_mode() -> None: uuid = str(uuid4()) group_admin = JWTGroup(id="admin", name="admin", role=RoleType.ADMIN) repository = Mock() user_service = Mock() service = StorageService( study_service=Mock(), importer_service=Mock(), exporter_service=Mock(), user_service=user_service, repository=repository, event_bus=Mock(), ) repository.get.return_value = Study(id=uuid) with pytest.raises(UserHasNotPermissionError): service.set_public_mode( uuid, PublicMode.FULL, RequestParameters(JWTUser(id=1, impersonator=1, type="users")), ) service.set_public_mode( uuid, PublicMode.FULL, RequestParameters( JWTUser(id=1, impersonator=1, type="users", groups=[group_admin])), ) repository.save.assert_called_once_with( Study(id=uuid, public_mode=PublicMode.FULL))
def test_authenticate(): users = Mock() users.get_by_name.return_value = User(id=0, password=Password("pwd")) users.get.return_value = User(id=0, name="linus") ldap = Mock() ldap.login.return_value = None ldap.get.return_value = None roles = Mock() roles.get_all_by_user.return_value = [ Role(type=RoleType.READER, group=Group(id="group", name="group")) ] exp = JWTUser( id=0, impersonator=0, type="users", groups=[JWTGroup(id="group", name="group", role=RoleType.READER)], ) service = LoginService( user_repo=users, bot_repo=Mock(), group_repo=Mock(), role_repo=roles, ldap=ldap, event_bus=Mock(), ) assert exp == service.authenticate("dupond", "pwd") users.get_by_name.assert_called_once_with("dupond") roles.get_all_by_user.assert_called_once_with(0)
def test_save_metadata() -> None: # Mock repository = Mock() uuid = str(uuid4()) study_service = Mock() study_service.get_study_information.return_value = { "antares": { "caption": "CAPTION", "version": "VERSION", "author": "AUTHOR", "created": 1234, "lastsave": 9876, } } # Input jwt = JWTUser( id=0, impersonator=0, type="users", groups=[JWTGroup(id="my-group", name="group", role=RoleType.ADMIN)], ) user = User(id=0, name="user") group = Group(id="my-group", name="group") # Expected study = RawStudy( id=uuid, name="CAPTION", version="VERSION", author="AUTHOR", created_at=datetime.fromtimestamp(1234), updated_at=datetime.fromtimestamp(9876), content_status=StudyContentStatus.VALID, workspace=DEFAULT_WORKSPACE_NAME, owner=user, groups=[group], ) service = StorageService( study_service=study_service, importer_service=Mock(), exporter_service=Mock(), user_service=Mock(), repository=repository, event_bus=Mock(), ) service._save_study( RawStudy(id=uuid, workspace=DEFAULT_WORKSPACE_NAME), owner=jwt, ) repository.save.assert_called_once_with(study)
def test_is_site_admin(): jwt = JWTUser( id=0, impersonator=0, type="users", groups=[JWTGroup(id="admin", name="admin", role=RoleType.ADMIN)], ) assert jwt.is_site_admin() assert not JWTUser( id=0, impersonator=0, type="users", ).is_site_admin()
def get_jwt(self, user_id: int) -> Optional[JWTUser]: user = self.ldap.get(user_id) or self.users.get(user_id) if user: return JWTUser( id=user.id, impersonator=user.get_impersonator(), type=user.type, groups=[ JWTGroup(id=r.group.id, name=r.group.name, role=r.type) for r in self.roles.get_all_by_user(user_id) ], ) return None
def create_auth_token( app: Flask, expires_delta: Any = timedelta(days=2), type: TokenType = TokenType.ACCESS, ) -> Dict[str, str]: create_token = (create_access_token if type == TokenType.ACCESS else create_refresh_token) with app.app_context(): token = create_token( expires_delta=expires_delta, identity=JWTUser( id=0, impersonator=0, type="users", groups=[ JWTGroup(id="group", name="group", role=RoleType.ADMIN) ], ).to_dict(), ) return {"Authorization": f"Bearer {token}"}
from antarest.common.roles import RoleType from antarest.storage.main import build_storage from antarest.storage.model import Study from antarest.storage.service import StorageService from antarest.common.requests import ( RequestParameters, ) from tests.storage.integration.data.de_details_hourly import de_details_hourly from tests.storage.integration.data.de_fr_values_hourly import ( de_fr_values_hourly, ) from tests.storage.integration.data.input_link import input_link ADMIN = JWTUser( id=1, impersonator=1, type="users", groups=[JWTGroup(id="admin", name="admin", role=RoleType.ADMIN)], ) def assert_url_content(storage_service: StorageService, url: str, expected_output: str) -> None: app = Flask(__name__) build_storage( app, session=Mock(), user_service=Mock(), storage_service=storage_service, config=storage_service.study_service.config, ) client = app.test_client() res = client.get(url)
def test_create_study() -> None: # Mock repository = Mock() # Input user = User(id=0, name="user") group = Group(id="my-group", name="group") expected = RawStudy( id=str(uuid4()), name="new-study", version="VERSION", author="AUTHOR", created_at=datetime.fromtimestamp(1234), updated_at=datetime.fromtimestamp(9876), content_status=StudyContentStatus.VALID, workspace=DEFAULT_WORKSPACE_NAME, owner=user, groups=[group], ) study_service = Mock() study_service.get_default_workspace_path.return_value = Path("") study_service.get_study_information.return_value = { "antares": { "caption": "CAPTION", "version": "VERSION", "author": "AUTHOR", "created": 1234, "lastsave": 9876, } } study_service.create_study.return_value = expected service = StorageService( study_service=study_service, importer_service=Mock(), exporter_service=Mock(), user_service=Mock(), repository=repository, event_bus=Mock(), ) with pytest.raises(UserHasNotPermissionError): service.create_study( "new-study", ["my-group"], RequestParameters(JWTUser(id=0, impersonator=0, type="users")), ) service.create_study( "new-study", ["my-group"], RequestParameters( JWTUser( id=0, impersonator=0, type="users", groups=[ JWTGroup(id="my-group", name="group", role=RoleType.WRITER) ], )), ) study_service.create_study.assert_called() repository.save.assert_called_once_with(expected)
def test_assert_permission() -> None: uuid = str(uuid4()) admin_group = JWTGroup(id="admin", name="admin", role=RoleType.ADMIN) admin = JWTUser(id=1, impersonator=1, type="users", groups=[admin_group]) group = JWTGroup(id="my-group", name="g", role=RoleType.ADMIN) jwt = JWTUser(id=0, impersonator=0, type="users", groups=[group]) group_2 = JWTGroup(id="my-group-2", name="g2", role=RoleType.RUNNER) jwt_2 = JWTUser(id=3, impersonator=3, type="users", groups=[group_2]) good = User(id=0) wrong = User(id=2) repository = Mock() service = StorageService( study_service=Mock(), importer_service=Mock(), exporter_service=Mock(), user_service=Mock(), repository=repository, event_bus=Mock(), ) # wrong owner repository.get.return_value = Study(id=uuid, owner=wrong) study = service._get_study(uuid) with pytest.raises(UserHasNotPermissionError): service._assert_permission(jwt, study, StudyPermissionType.READ) assert not service._assert_permission( jwt, study, StudyPermissionType.READ, raising=False) # good owner study = Study(id=uuid, owner=good) assert service._assert_permission(jwt, study, StudyPermissionType.MANAGE_PERMISSIONS) # wrong group study = Study(id=uuid, owner=wrong, groups=[Group(id="wrong")]) with pytest.raises(UserHasNotPermissionError): service._assert_permission(jwt, study, StudyPermissionType.READ) assert not service._assert_permission( jwt, study, StudyPermissionType.READ, raising=False) # good group study = Study(id=uuid, owner=wrong, groups=[Group(id="my-group")]) assert service._assert_permission(jwt, study, StudyPermissionType.MANAGE_PERMISSIONS) # super admin can do whatever he wants.. study = Study(id=uuid) assert service._assert_permission(admin, study, StudyPermissionType.MANAGE_PERMISSIONS) # when study found in workspace without group study = Study(id=uuid, public_mode=PublicMode.FULL) assert not service._assert_permission( jwt, study, StudyPermissionType.MANAGE_PERMISSIONS, raising=False) assert service._assert_permission(jwt, study, StudyPermissionType.DELETE) assert service._assert_permission(jwt, study, StudyPermissionType.READ) assert service._assert_permission(jwt, study, StudyPermissionType.WRITE) assert service._assert_permission(jwt, study, StudyPermissionType.RUN) # some group roles study = Study(id=uuid, owner=wrong, groups=[Group(id="my-group-2")]) assert not service._assert_permission( jwt_2, study, StudyPermissionType.WRITE, raising=False) assert service._assert_permission(jwt_2, study, StudyPermissionType.READ)
def test_manage_group() -> None: uuid = str(uuid4()) alice = User(id=1) group_a = Group(id="a", name="Group A") group_b = Group(id="b", name="Group B") group_a_admin = JWTGroup(id="a", name="Group A", role=RoleType.ADMIN) repository = Mock() user_service = Mock() service = StorageService( study_service=Mock(), importer_service=Mock(), exporter_service=Mock(), user_service=user_service, repository=repository, event_bus=Mock(), ) repository.get.return_value = Study(id=uuid, owner=alice, groups=[group_a]) with pytest.raises(UserHasNotPermissionError): service.add_group( uuid, "b", RequestParameters(JWTUser(id=2, impersonator=2, type="users")), ) user_service.get_group.return_value = group_b service.add_group( uuid, "b", RequestParameters( JWTUser(id=2, impersonator=2, type="users", groups=[group_a_admin])), ) user_service.get_group.assert_called_once_with( "b", RequestParameters( JWTUser(id=2, impersonator=2, type="users", groups=[group_a_admin])), ) repository.save.assert_called_with( Study(id=uuid, owner=alice, groups=[group_a, group_b])) repository.get.return_value = Study(id=uuid, owner=alice, groups=[group_a, group_b]) service.add_group( uuid, "b", RequestParameters( JWTUser(id=2, impersonator=2, type="users", groups=[group_a_admin])), ) user_service.get_group.assert_called_with( "b", RequestParameters( JWTUser(id=2, impersonator=2, type="users", groups=[group_a_admin])), ) repository.save.assert_called_with( Study(id=uuid, owner=alice, groups=[group_a, group_b])) repository.get.return_value = Study(id=uuid, owner=alice, groups=[group_a, group_b]) service.remove_group( uuid, "a", RequestParameters( JWTUser(id=2, impersonator=2, type="users", groups=[group_a_admin])), ) repository.save.assert_called_with( Study(id=uuid, owner=alice, groups=[group_b]))
def bots_create() -> Any: """ Create Bot --- responses: '200': content: application/json: schema: type: string description: Bot token API description: Successful operation '400': description: Invalid request '401': description: Unauthenticated User '403': description: Unauthorized consumes: - application/json parameters: - in: body name: body required: true description: Bot schema: id: User required: - name - group - role properties: name: type: string description: Bot name isAuthor: type: boolean description: Set Bot impersonator between itself or it owner group: type: string description: group id linked to bot role: type: int description: RoleType used by bot. Should be lower or equals ot owner role type inside same group tags: - Bot """ params = RequestParameters(user=Auth.get_current_user()) create = BotCreateDTO.from_dict(json.loads(request.data)) bot = service.save_bot(create, params) if not bot: return UserHasNotPermissionError() group = service.get_group(create.group, params) if not group: return UserHasNotPermissionError() jwt = JWTUser( id=bot.id, impersonator=bot.get_impersonator(), type=bot.type, groups=[JWTGroup(id=group.id, name=group.name, role=create.role)], ) tokens = generate_tokens(jwt, expire=timedelta(days=368 * 200)) return tokens["access_token"]
UserCreateDTO, UserLdap, RoleCreationDTO, ) from antarest.login.service import ( LoginService, GroupNotFoundError, UserNotFoundError, ) SADMIN = RequestParameters( user=JWTUser( id=0, impersonator=0, type="users", groups=[JWTGroup(id="admin", name="admin", role=RoleType.ADMIN)], ) ) GADMIN = RequestParameters( user=JWTUser( id=1, impersonator=1, type="users", groups=[JWTGroup(id="group", name="group", role=RoleType.ADMIN)], ) ) USER3 = RequestParameters( user=JWTUser( id=3,