Search in sources :

Example 11 with PermissionService

use of com.infiniteautomation.mango.spring.service.PermissionService in project ma-core-public by infiniteautomation.

the class UserEventMulticasterTest method testMulticastEventsForUsersWithPermissions.

@Test
public void testMulticastEventsForUsersWithPermissions() {
    PermissionService service = Common.getBean(PermissionService.class);
    int dataPointId = 1;
    int eventCount = 100;
    int userCount = 5 * 6;
    // Add them out of order so the tree is jumbled with permissions hither and yon
    List<User> users = new ArrayList<>();
    int added = 0;
    for (int i = 0; i < (userCount / 6); i++) {
        users.add(createUser("User" + added, "user" + added, "password", "user" + added + "@yourMangoDomain.com", PermissionHolder.SUPERADMIN_ROLE));
        added++;
    }
    for (int i = 0; i < (userCount / 6); i++) {
        users.add(createUser("User" + added, "user" + added, "password", "user" + added + "@yourMangoDomain.com", mockRole.getRole()));
        added++;
    }
    for (int i = 0; i < (userCount / 6); i++) {
        users.add(createUser("User" + added, "user" + added, "password", "user" + added + "@yourMangoDomain.com"));
        added++;
    }
    for (int i = 0; i < (userCount / 6); i++) {
        users.add(createUser("User" + added, "user" + added, "password", "user" + added + "@yourMangoDomain.com", PermissionHolder.SUPERADMIN_ROLE));
        added++;
    }
    for (int i = 0; i < (userCount / 6); i++) {
        users.add(createUser("User" + added, "user" + added, "password", "user" + added + "@yourMangoDomain.com", mockRole.getRole()));
        added++;
    }
    for (int i = 0; i < (userCount / 6); i++) {
        users.add(createUser("User" + added, "user" + added, "password", "user" + added + "@yourMangoDomain.com"));
        added++;
    }
    List<Integer> idsToNotify = new ArrayList<>();
    List<MockUserEventListener> listeners = new ArrayList<>();
    UserEventListener multicaster = null;
    MockEventType mockEventType = new MockEventType(DuplicateHandling.ALLOW, null, 0, dataPointId, this.mockRole.getRole());
    for (User u : users) {
        MockUserEventListener l = new MockUserEventListener(u);
        if (// This work is normally done by the event manager handling the raiseEvent calls
        mockEventType.hasPermission(u, service))
            // through an EventNotifyWorkItem
            idsToNotify.add(u.getId());
        listeners.add(l);
        multicaster = UserEventMulticaster.add(multicaster, l);
    }
    List<EventInstance> events = new ArrayList<>();
    long time = 0;
    for (int i = 0; i < eventCount; i++) {
        EventInstance event = createMockEventInstance(i, dataPointId, time);
        events.add(event);
        event.setIdsToNotify(idsToNotify);
        multicaster.raised(event);
        time += 1;
    }
    // Ack
    for (EventInstance e : events) multicaster.acknowledged(e);
    // Rtn
    for (EventInstance e : events) multicaster.returnToNormal(e);
    // Confirm those with correct permissions permissions saw all raised
    for (MockUserEventListener l : listeners) {
        if (!(service.hasPermission(l.getUser(), MangoPermission.requireAnyRole(mockRole.getRole())) || service.hasAdminRole(l.getUser()))) {
            assertEquals(0, l.getRaised().size());
        } else {
            assertEquals(eventCount, l.getRaised().size());
        }
    }
    // Confirm those with permissions saw all acked
    for (MockUserEventListener l : listeners) {
        if (!(service.hasPermission(l.getUser(), MangoPermission.requireAnyRole(mockRole.getRole())) || service.hasAdminRole(l.getUser()))) {
            assertEquals(0, l.getAcknowledged().size());
        } else {
            assertEquals(eventCount, l.getAcknowledged().size());
        }
    }
    // Confirm those with permissions saw all rtned
    for (MockUserEventListener l : listeners) {
        if (!(service.hasPermission(l.getUser(), MangoPermission.requireAnyRole(mockRole.getRole())) || service.hasAdminRole(l.getUser()))) {
            assertEquals(0, l.getReturned().size());
        } else {
            assertEquals(eventCount, l.getReturned().size());
        }
    }
}
Also used : User(com.serotonin.m2m2.vo.User) ArrayList(java.util.ArrayList) MockEventType(com.serotonin.m2m2.rt.event.type.MockEventType) PermissionService(com.infiniteautomation.mango.spring.service.PermissionService) Test(org.junit.Test)

Example 12 with PermissionService

use of com.infiniteautomation.mango.spring.service.PermissionService in project ma-core-public by infiniteautomation.

the class RoleDao method joinPermissions.

@Override
public <R extends Record> SelectJoinStep<R> joinPermissions(SelectJoinStep<R> select, PermissionHolder user) {
    PermissionService permissionService = permissionServiceSupplier.get();
    Set<Role> heldRoles = permissionService.getAllInheritedRoles(user);
    if (heldRoles.contains(PermissionHolder.SUPERADMIN_ROLE)) {
        return select;
    }
    List<String> xids = heldRoles.stream().map(Role::getXid).collect(Collectors.toList());
    return select.innerJoin(DSL.selectOne()).on(table.xid.in(xids));
}
Also used : PermissionService(com.infiniteautomation.mango.spring.service.PermissionService) Role(com.serotonin.m2m2.vo.role.Role)

Example 13 with PermissionService

use of com.infiniteautomation.mango.spring.service.PermissionService in project ma-core-public by infiniteautomation.

the class RoleDao method createSubSelectMap.

@Override
protected Map<String, RQLSubSelectCondition> createSubSelectMap() {
    Map<String, RQLSubSelectCondition> subselects = super.createSubSelectMap();
    subselects.put("inherited", (operation, node) -> {
        if (operation != RQLOperation.CONTAINS) {
            throw new RQLVisitException(String.format("Unsupported node type '%s' for field '%s'", node.getName(), node.getArgument(0)));
        }
        PermissionService permissionService = permissionServiceSupplier.get();
        Set<Integer> roleIds = extractArrayArguments(node, o -> o == null ? null : o.toString()).stream().filter(Objects::nonNull).map(permissionService::getRole).filter(Objects::nonNull).map(Role::getId).collect(Collectors.toSet());
        SelectConditionStep<Record1<Integer>> afterWhere;
        if (!roleIds.isEmpty()) {
            SelectJoinStep<Record1<Integer>> select = create.select(RoleInheritance.ROLE_INHERITANCE.roleId).from(RoleInheritance.ROLE_INHERITANCE);
            afterWhere = select.where(RoleInheritance.ROLE_INHERITANCE.inheritedRoleId.in(roleIds));
        } else {
            // Find all roles with no inherited roles
            SelectJoinStep<Record1<Integer>> select = create.select(getIdField()).from(table);
            SelectOnConditionStep<Record1<Integer>> afterJoin = select.leftJoin(RoleInheritance.ROLE_INHERITANCE).on(RoleInheritance.ROLE_INHERITANCE.roleId.eq(getIdField()));
            afterWhere = afterJoin.where(RoleInheritance.ROLE_INHERITANCE.roleId.isNull());
        }
        return table.id.in(afterWhere.asField());
    });
    subselects.put("inheritedBy", (operation, node) -> {
        if (operation != RQLOperation.CONTAINS) {
            throw new RQLVisitException(String.format("Unsupported node type '%s' for field '%s'", node.getName(), node.getArgument(0)));
        }
        PermissionService permissionService = permissionServiceSupplier.get();
        Set<Integer> roleIds = extractArrayArguments(node, o -> o == null ? null : o.toString()).stream().filter(Objects::nonNull).map(permissionService::getRole).filter(Objects::nonNull).map(Role::getId).collect(Collectors.toSet());
        SelectConditionStep<Record1<Integer>> afterWhere;
        if (!roleIds.isEmpty()) {
            // Find all roles inherited by this role
            SelectJoinStep<Record1<Integer>> select = create.select(RoleInheritance.ROLE_INHERITANCE.inheritedRoleId).from(RoleInheritance.ROLE_INHERITANCE);
            afterWhere = select.where(RoleInheritance.ROLE_INHERITANCE.roleId.in(roleIds));
        } else {
            // Find all roles with that are not inherited by any role
            SelectJoinStep<Record1<Integer>> select = create.select(getIdField()).from(table);
            SelectOnConditionStep<Record1<Integer>> afterJoin = select.leftJoin(RoleInheritance.ROLE_INHERITANCE).on(RoleInheritance.ROLE_INHERITANCE.inheritedRoleId.eq(getIdField()));
            afterWhere = afterJoin.where(RoleInheritance.ROLE_INHERITANCE.inheritedRoleId.isNull());
        }
        return table.id.in(afterWhere.asField());
    });
    return subselects;
}
Also used : PermissionService(com.infiniteautomation.mango.spring.service.PermissionService) RQLVisitException(com.infiniteautomation.mango.db.query.RQLToCondition.RQLVisitException) Objects(java.util.Objects) RQLSubSelectCondition(com.infiniteautomation.mango.db.query.RQLSubSelectCondition) Record1(org.jooq.Record1)

Example 14 with PermissionService

use of com.infiniteautomation.mango.spring.service.PermissionService in project ma-core-public by infiniteautomation.

the class LazyFieldJsonTest method testLazyPermissionFromJsonObject.

@Test
public void testLazyPermissionFromJsonObject() {
    RoleService roleService = Common.getBean(RoleService.class);
    PermissionService permissionService = Common.getBean(PermissionService.class);
    Role role1 = roleService.insert(new RoleVO(Common.NEW_ID, "XID-1", "Role 1")).getRole();
    Role role2 = roleService.insert(new RoleVO(Common.NEW_ID, "XID-2", "Role 2")).getRole();
    LazyField<MangoPermission> permission = new LazyField<>(() -> MangoPermission.builder().minterm(role1, role2).build());
    try (StringWriter stringWriter = new StringWriter()) {
        JsonWriter writer = new JsonWriter(Common.JSON_CONTEXT, stringWriter);
        JsonTypeWriter typeWriter = new JsonTypeWriter(Common.JSON_CONTEXT);
        JsonValue value = typeWriter.writeObject(permission);
        writer.setPrettyIndent(0);
        writer.setPrettyOutput(true);
        writer.writeObject(value);
        String json = stringWriter.toString();
        JsonTypeReader typeReader = new JsonTypeReader(json);
        JsonValue read = typeReader.read();
        JsonArray root = read.toJsonArray();
        JsonReader reader = new JsonReader(Common.JSON_CONTEXT, root);
        ImportContext context = new ImportContext(reader, new ProcessResult(), Common.getTranslations());
        LazyField<MangoPermission> readPermission = new LazyField<>();
        TypeDefinition lazyType = new TypeDefinition(LazyField.class, MangoPermission.class);
        context.getReader().readInto(lazyType, readPermission, root);
        assertEquals(permission.get(), readPermission.get());
    } catch (IOException | JsonException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : JsonException(com.serotonin.json.JsonException) LazyField(com.infiniteautomation.mango.util.LazyField) JsonValue(com.serotonin.json.type.JsonValue) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) IOException(java.io.IOException) JsonWriter(com.serotonin.json.JsonWriter) JsonTypeWriter(com.serotonin.json.type.JsonTypeWriter) TypeDefinition(com.serotonin.json.util.TypeDefinition) PermissionService(com.infiniteautomation.mango.spring.service.PermissionService) Role(com.serotonin.m2m2.vo.role.Role) JsonArray(com.serotonin.json.type.JsonArray) ImportContext(com.infiniteautomation.mango.emport.ImportContext) RoleVO(com.serotonin.m2m2.vo.role.RoleVO) RoleService(com.infiniteautomation.mango.spring.service.RoleService) StringWriter(java.io.StringWriter) JsonReader(com.serotonin.json.JsonReader) JsonTypeReader(com.serotonin.json.type.JsonTypeReader) MangoPermission(com.infiniteautomation.mango.permission.MangoPermission) Test(org.junit.Test)

Example 15 with PermissionService

use of com.infiniteautomation.mango.spring.service.PermissionService in project ma-core-public by infiniteautomation.

the class PermissionPersistenceTest method testModifyPermission.

/**
 * Modify a permission and ensure that it is retrieved correctly from the database after
 */
@Test
public void testModifyPermission() {
    PermissionService service = Common.getBean(PermissionService.class);
    // insert some roles
    Set<Role> roles = this.createRoles(2).stream().map(r -> r.getRole()).collect(Collectors.toSet());
    // insert the permission
    MangoPermission permission = service.findOrCreate(MangoPermission.requireAnyRole(roles));
    MangoPermission read = service.get(permission.getId());
    assertEquals(2, read.getRoles().size());
    Iterator<Set<Role>> it = read.getRoles().iterator();
    Role toKeep = it.next().iterator().next();
    MangoPermission keep = service.findOrCreate(MangoPermission.requireAnyRole(toKeep));
    read = service.get(keep.getId());
    assertEquals(1, read.getRoles().size());
}
Also used : PermissionService(com.infiniteautomation.mango.spring.service.PermissionService) Role(com.serotonin.m2m2.vo.role.Role) Role(com.serotonin.m2m2.vo.role.Role) Iterator(java.util.Iterator) Common(com.serotonin.m2m2.Common) DatabaseProxy(com.serotonin.m2m2.db.DatabaseProxy) Assert.assertTrue(org.junit.Assert.assertTrue) Set(java.util.Set) Test(org.junit.Test) RoleDao(com.serotonin.m2m2.db.dao.RoleDao) Collectors(java.util.stream.Collectors) HashSet(java.util.HashSet) List(java.util.List) MangoTestBase(com.serotonin.m2m2.MangoTestBase) DSLContext(org.jooq.DSLContext) Assert.assertEquals(org.junit.Assert.assertEquals) PermissionsMinterms(com.infiniteautomation.mango.db.tables.PermissionsMinterms) PermissionService(com.infiniteautomation.mango.spring.service.PermissionService) Set(java.util.Set) HashSet(java.util.HashSet) Test(org.junit.Test)

Aggregations

PermissionService (com.infiniteautomation.mango.spring.service.PermissionService)47 Test (org.junit.Test)32 Role (com.serotonin.m2m2.vo.role.Role)25 Set (java.util.Set)19 HashSet (java.util.HashSet)17 Common (com.serotonin.m2m2.Common)14 DatabaseProxy (com.serotonin.m2m2.db.DatabaseProxy)14 List (java.util.List)13 MangoTestBase (com.serotonin.m2m2.MangoTestBase)12 Collectors (java.util.stream.Collectors)12 PermissionsMinterms (com.infiniteautomation.mango.db.tables.PermissionsMinterms)10 DataSourceService (com.infiniteautomation.mango.spring.service.DataSourceService)10 RoleDao (com.serotonin.m2m2.db.dao.RoleDao)10 MockDataSourceVO (com.serotonin.m2m2.vo.dataSource.mock.MockDataSourceVO)10 Iterator (java.util.Iterator)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)10 MutableObject (org.apache.commons.lang3.mutable.MutableObject)10 DSLContext (org.jooq.DSLContext)10 Assert.assertEquals (org.junit.Assert.assertEquals)10 Assert.assertTrue (org.junit.Assert.assertTrue)10