Search in sources :

Example 21 with PermissionService

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

the class DataSourceDaoDeadlockDetection method detectDeadlockFromDataSourceDeleteDataPointInsertAndDelete.

/**
 * See the deadlock when you insert data source, then point,
 *  then delete point (outside of transaction) then delete source
 */
@Test
public void detectDeadlockFromDataSourceDeleteDataPointInsertAndDelete() {
    // Create data source
    // Add data point
    // Delete data source
    // Create data source
    // 25;
    int numThreads = 5;
    // 100;
    int numDataSources = 10;
    PermissionService permissionService = Common.getBean(PermissionService.class);
    DataSourceService dataSourceService = Common.getBean(DataSourceService.class);
    DataPointService dataPointService = Common.getBean(DataPointService.class);
    AtomicInteger successes = new AtomicInteger();
    AtomicInteger failures = new AtomicInteger();
    AtomicInteger running = new AtomicInteger(numThreads);
    MutableObject<Exception> failure = new MutableObject<>(null);
    for (int i = 0; i < numThreads; i++) {
        new Thread() {

            @Override
            public void run() {
                try {
                    for (int i = 0; i < numDataSources; i++) {
                        // Create data source
                        MockDataSourceVO ds = new MockDataSourceVO();
                        ds.setName(Common.generateXid("Mock "));
                        dataSourceService.insert(ds);
                        // Create and save point
                        DataPointVO dp = createMockDataPoint(ds, new MockPointLocatorVO());
                        // Delete point
                        dataPointService.delete(dp.getId());
                        // Delete data source
                        dataSourceService.delete(ds.getId());
                        successes.getAndIncrement();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    failure.setValue(e);
                    failures.getAndIncrement();
                } finally {
                    running.decrementAndGet();
                }
            }
        }.start();
    }
    while (running.get() > 0) {
        try {
            Thread.sleep(100);
        } catch (Exception e) {
        }
    }
    if (failures.get() > 0) {
        fail("Ran " + successes.get() + " queries: " + failure.getValue().getMessage());
    }
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) MockDataSourceVO(com.serotonin.m2m2.vo.dataSource.mock.MockDataSourceVO) MockPointLocatorVO(com.serotonin.m2m2.vo.dataPoint.MockPointLocatorVO) DataSourceService(com.infiniteautomation.mango.spring.service.DataSourceService) PermissionService(com.infiniteautomation.mango.spring.service.PermissionService) DataPointService(com.infiniteautomation.mango.spring.service.DataPointService) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MutableObject(org.apache.commons.lang3.mutable.MutableObject) Test(org.junit.Test)

Example 22 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 23 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 24 with PermissionService

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

the class MaintenanceEventsRestController method exportQuery.

@ApiOperation(value = "Export formatted for Configuration Import by supplying an RQL query", notes = "User must have read permission")
@RequestMapping(method = RequestMethod.GET, value = "/export", produces = MediaTypes.SEROTONIN_JSON_VALUE)
public Map<String, JsonStreamedArray> exportQuery(HttpServletRequest request, @AuthenticationPrincipal PermissionHolder user) {
    ASTNode rql = RQLUtils.parseRQLtoAST(request.getQueryString());
    Map<String, JsonStreamedArray> export = new HashMap<>();
    if (permissionService.hasPermission(user, dataSourcePermissionDefinition.getPermission())) {
        export.put("maintenanceEvents", new StreamedSeroJsonVORqlQuery<>(service, rql, null, null, null));
    } else {
        export.put("maintenanceEvents", new StreamedSeroJsonVORqlQuery<>(service, rql, null, null, null, item -> {
            if (item.getDataPoints().size() > 0) {
                DataPointPermissionsCheckCallback callback = new DataPointPermissionsCheckCallback(user, true, permissionService, dataPointService);
                dao.getPoints(item.getId(), callback);
                if (!callback.hasPermission())
                    return false;
            }
            if (item.getDataSources().size() > 0) {
                DataSourcePermissionsCheckCallback callback = new DataSourcePermissionsCheckCallback(user, true, permissionService);
                dao.getDataSources(item.getId(), callback);
                if (!callback.hasPermission())
                    return false;
            }
            return true;
        }));
    }
    return export;
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) RequestParam(org.springframework.web.bind.annotation.RequestParam) BiFunction(java.util.function.BiFunction) StreamedVORqlQueryWithTotal(com.infiniteautomation.mango.rest.latest.model.StreamedVORqlQueryWithTotal) Autowired(org.springframework.beans.factory.annotation.Autowired) ApiParam(io.swagger.annotations.ApiParam) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder) RestModelMapper(com.infiniteautomation.mango.rest.latest.model.RestModelMapper) PatchVORequestBody(com.infiniteautomation.mango.rest.latest.patch.PatchVORequestBody) MaintenanceEventsService(com.infiniteautomation.mango.spring.service.maintenanceEvents.MaintenanceEventsService) ApiOperation(io.swagger.annotations.ApiOperation) Map(java.util.Map) URI(java.net.URI) DataPointPermissionsCheckCallback(com.infiniteautomation.mango.spring.service.maintenanceEvents.MaintenanceEventsService.DataPointPermissionsCheckCallback) HttpHeaders(org.springframework.http.HttpHeaders) RQLUtils(com.infiniteautomation.mango.util.RQLUtils) Set(java.util.Set) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) EventInstanceService(com.infiniteautomation.mango.spring.service.EventInstanceService) Field(org.jooq.Field) RestController(org.springframework.web.bind.annotation.RestController) EventQueryByMaintenanceEventRql(com.infiniteautomation.mango.rest.latest.model.EventQueryByMaintenanceEventRql) JsonStreamedArray(com.serotonin.json.type.JsonStreamedArray) DataSourcePermissionDefinition(com.serotonin.m2m2.module.definitions.permissions.DataSourcePermissionDefinition) List(java.util.List) DataSourcePermissionsCheckCallback(com.infiniteautomation.mango.spring.service.maintenanceEvents.MaintenanceEventsService.DataSourcePermissionsCheckCallback) StreamedSeroJsonVORqlQuery(com.infiniteautomation.mango.rest.latest.model.StreamedSeroJsonVORqlQuery) ASTNode(net.jazdw.rql.parser.ASTNode) EventTableRqlMappings(com.infiniteautomation.mango.rest.latest.EventsRestController.EventTableRqlMappings) PermissionService(com.infiniteautomation.mango.spring.service.PermissionService) EventQueryByMaintenanceCriteria(com.infiniteautomation.mango.rest.latest.model.EventQueryByMaintenanceCriteria) MaintenanceEventType(com.serotonin.m2m2.maintenanceEvents.MaintenanceEventType) MaintenanceEventModel(com.infiniteautomation.mango.rest.latest.model.MaintenanceEventModel) MaintenanceEventVO(com.serotonin.m2m2.maintenanceEvents.MaintenanceEventVO) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) HashMap(java.util.HashMap) Function(java.util.function.Function) Events(com.infiniteautomation.mango.db.tables.Events) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) RequestBody(org.springframework.web.bind.annotation.RequestBody) HttpServletRequest(javax.servlet.http.HttpServletRequest) StreamedArrayWithTotal(com.infiniteautomation.mango.rest.latest.model.StreamedArrayWithTotal) DataPointService(com.infiniteautomation.mango.spring.service.DataPointService) Api(io.swagger.annotations.Api) MaintenanceEventDao(com.serotonin.m2m2.maintenanceEvents.MaintenanceEventDao) EventInstanceVO(com.serotonin.m2m2.vo.event.EventInstanceVO) EventInstanceModel(com.infiniteautomation.mango.rest.latest.model.event.EventInstanceModel) Consumer(java.util.function.Consumer) HttpStatus(org.springframework.http.HttpStatus) AuthenticationPrincipal(org.springframework.security.core.annotation.AuthenticationPrincipal) MediaTypes(com.serotonin.m2m2.web.MediaTypes) ResponseEntity(org.springframework.http.ResponseEntity) StreamedArray(com.infiniteautomation.mango.rest.latest.model.StreamedArray) HashMap(java.util.HashMap) ASTNode(net.jazdw.rql.parser.ASTNode) DataPointPermissionsCheckCallback(com.infiniteautomation.mango.spring.service.maintenanceEvents.MaintenanceEventsService.DataPointPermissionsCheckCallback) DataSourcePermissionsCheckCallback(com.infiniteautomation.mango.spring.service.maintenanceEvents.MaintenanceEventsService.DataSourcePermissionsCheckCallback) JsonStreamedArray(com.serotonin.json.type.JsonStreamedArray) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 25 with PermissionService

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

the class UserModel method fromVO.

@Override
public void fromVO(User vo) {
    super.fromVO(vo);
    this.username = vo.getUsername();
    this.password = vo.getPassword();
    this.email = vo.getEmail();
    this.phone = vo.getPhone();
    this.disabled = vo.isDisabled();
    this.homeUrl = vo.getHomeUrl();
    this.lastLogin = vo.getLastLogin() == 0 ? null : new Date(vo.getLastLogin());
    this.lastPasswordChange = new Date(vo.getPasswordChangeTimestamp());
    this.receiveAlarmEmails = vo.getReceiveAlarmEmails();
    this.timezone = StringUtils.isBlank(vo.getTimezone()) ? null : vo.getTimezone();
    this.muted = vo.isMuted();
    this.receiveOwnAuditEvents = vo.isReceiveOwnAuditEvents();
    this.roles = new HashSet<>();
    for (Role role : vo.getRoles()) {
        roles.add(role.getXid());
    }
    // TODO move this into the model mapper and use map/unmap anywhere
    // a user model is needed
    PermissionService permissionService = Common.getBean(PermissionService.class);
    this.inheritedRoles = new HashSet<>();
    Set<Role> getAllInheritedRoles = permissionService.getAllInheritedRoles(vo);
    for (Role role : getAllInheritedRoles) {
        this.inheritedRoles.add(role.getXid());
    }
    this.systemPermissions = permissionService.getSystemPermissions(vo);
    this.locale = StringUtils.isBlank(vo.getLocale()) ? null : vo.getLocale();
    this.passwordLocked = vo.isPasswordLocked();
    this.sessionExpirationOverride = vo.isSessionExpirationOverride();
    if (sessionExpirationOverride)
        this.sessionExpirationPeriod = new TimePeriod(vo.getSessionExpirationPeriods(), TimePeriodType.valueOf(vo.getSessionExpirationPeriodType()));
    this.organization = vo.getOrganization();
    this.organizationalRole = vo.getOrganizationalRole();
    this.created = vo.getCreated();
    this.emailVerified = vo.getEmailVerifiedDate();
    this.data = vo.getData();
    this.editPermission = new MangoPermissionModel(vo.getEditPermission());
    this.readPermission = new MangoPermissionModel(vo.getReadPermission());
}
Also used : Role(com.serotonin.m2m2.vo.role.Role) PermissionService(com.infiniteautomation.mango.spring.service.PermissionService) TimePeriod(com.infiniteautomation.mango.rest.latest.model.time.TimePeriod) MangoPermissionModel(com.infiniteautomation.mango.rest.latest.model.permissions.MangoPermissionModel) Date(java.util.Date)

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