Search in sources :

Example 11 with RoleService

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

the class DefaultUserMapper method mapUser.

@Override
public User mapUser(OAuth2UserRequest userRequest, OAuth2User oAuth2User) {
    if (log.isDebugEnabled()) {
        log.debug("Syncing OAuth2 user {} to Mango user", oAuth2User);
    }
    ClientRegistration clientRegistration = userRequest.getClientRegistration();
    StandardClaimAccessor accessor = toAccessor(oAuth2User);
    String registrationId = clientRegistration.getRegistrationId();
    EnvironmentPropertyMapper userMapping = mapperFactory.forRegistrationId(registrationId, "userMapping.");
    Optional<String> issuerOptional = userMapping.map("issuer.fixed");
    if (!issuerOptional.isPresent()) {
        issuerOptional = userMapping.map("issuer", accessor::getClaimAsString);
    }
    String issuer = issuerOptional.orElseThrow(() -> new IllegalStateException("Issuer is required"));
    String subject = userMapping.map("subject", accessor::getClaimAsString).orElseThrow(() -> new IllegalStateException("Subject is required"));
    LinkedAccount linkedAccount = new OAuth2LinkedAccount(issuer, subject);
    User user = usersService.getUserForLinkedAccount(linkedAccount).orElseGet(() -> {
        // only synchronize the username when creating the user
        String usernamePrefix = userMapping.map("username.prefix").orElse("");
        String usernameSuffix = userMapping.map("username.suffix").orElse("");
        String username = userMapping.map("username", accessor::getClaimAsString).map(un -> usernamePrefix + un + usernameSuffix).orElse(// user will get a random XID for a username if claim is missing
        null);
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(LOCKED_PASSWORD);
        // in case role sync is not turned on
        newUser.setRoles(Collections.singleton(PermissionHolder.USER_ROLE));
        return newUser;
    });
    String emailPrefix = userMapping.map("email.prefix").orElse("");
    String emailSuffix = userMapping.map("email.suffix").orElse("");
    String email = userMapping.map("email", accessor::getClaimAsString).map(e -> emailPrefix + e + emailSuffix).orElse(// validation will fail if email is not set
    null);
    user.setEmail(email);
    userMapping.map("name", accessor::getClaimAsString).ifPresent(user::setName);
    userMapping.map("phone", accessor::getClaimAsString).ifPresent(user::setPhone);
    userMapping.map("locale", accessor::getClaimAsString).ifPresent(user::setLocale);
    userMapping.map("timezone", accessor::getClaimAsString).ifPresent(user::setTimezone);
    if (userMapping.map("oauth2.client.default.userMapping.roles.sync", Boolean.class).orElse(true)) {
        String rolePrefix = userMapping.map("roles.prefix").orElse("");
        String roleSuffix = userMapping.map("roles.suffix").orElse("");
        Set<String> ignoreRoles = Arrays.stream(userMapping.map("roles.ignore", String[].class).orElse(new String[0])).collect(Collectors.toSet());
        Stream<String> oauthRoles = userMapping.map("roles", accessor::getClaimAsStringList).orElseGet(ArrayList::new).stream().filter(r -> !ignoreRoles.contains(r)).map(r -> userMapping.map("roles.map." + r).orElse(rolePrefix + r + roleSuffix));
        Stream<String> addRoles = Arrays.stream(userMapping.map("roles.add", String[].class).orElse(new String[0]));
        Set<Role> roles = Stream.concat(oauthRoles, addRoles).map(roleService::getOrInsert).map(RoleVO::getRole).collect(Collectors.toCollection(HashSet::new));
        // ensure user role is present
        roles.add(PermissionHolder.USER_ROLE);
        user.setRoles(roles);
    }
    if (user.isNew()) {
        usersService.insertUserForLinkedAccount(user, linkedAccount);
    } else {
        usersService.update(user.getId(), user);
    }
    return user;
}
Also used : Arrays(java.util.Arrays) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) Role(com.serotonin.m2m2.vo.role.Role) OAuth2UserRequest(org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) UsersService(com.infiniteautomation.mango.spring.service.UsersService) RoleVO(com.serotonin.m2m2.vo.role.RoleVO) StandardClaimAccessor(org.springframework.security.oauth2.core.oidc.StandardClaimAccessor) Logger(org.slf4j.Logger) LinkedAccount(com.serotonin.m2m2.vo.LinkedAccount) Set(java.util.Set) Collectors(java.util.stream.Collectors) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Component(org.springframework.stereotype.Component) Stream(java.util.stream.Stream) EnvironmentPropertyMapper(com.infiniteautomation.mango.util.EnvironmentPropertyMapper) ConditionalOnProperty(com.infiniteautomation.mango.spring.ConditionalOnProperty) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) Optional(java.util.Optional) LOCKED_PASSWORD(com.serotonin.m2m2.db.dao.UserDao.LOCKED_PASSWORD) OAuth2LinkedAccount(com.serotonin.m2m2.vo.OAuth2LinkedAccount) Collections(java.util.Collections) User(com.serotonin.m2m2.vo.User) RoleService(com.infiniteautomation.mango.spring.service.RoleService) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) User(com.serotonin.m2m2.vo.User) LinkedAccount(com.serotonin.m2m2.vo.LinkedAccount) OAuth2LinkedAccount(com.serotonin.m2m2.vo.OAuth2LinkedAccount) OAuth2LinkedAccount(com.serotonin.m2m2.vo.OAuth2LinkedAccount) Role(com.serotonin.m2m2.vo.role.Role) StandardClaimAccessor(org.springframework.security.oauth2.core.oidc.StandardClaimAccessor) EnvironmentPropertyMapper(com.infiniteautomation.mango.util.EnvironmentPropertyMapper) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration)

Example 12 with RoleService

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

the class MangoTestBase method createRole.

/**
 * Create a role with inherited roles (
 */
protected RoleVO createRole(String xid, String name, Role... inherited) {
    RoleService service = Common.getBean(RoleService.class);
    RoleVO role = new RoleVO(Common.NEW_ID, xid, name, new HashSet<>(Arrays.asList(inherited)));
    return service.insert(role);
}
Also used : RoleVO(com.serotonin.m2m2.vo.role.RoleVO) RoleService(com.infiniteautomation.mango.spring.service.RoleService)

Example 13 with RoleService

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

the class AbstractRoleBasedTest method setupRoles.

protected void setupRoles() {
    roleService = Common.getBean(RoleService.class);
    // Add some roles
    RoleVO temp = new RoleVO(Common.NEW_ID, "read-role", "Role to allow reading.");
    roleService.insert(temp);
    readRole = new Role(temp);
    temp = new RoleVO(Common.NEW_ID, "edit-role", "Role to allow editing.");
    roleService.insert(temp);
    editRole = new Role(temp);
    temp = new RoleVO(Common.NEW_ID, "set-role", "Role to allow setting.");
    roleService.insert(temp);
    setRole = new Role(temp);
    temp = new RoleVO(Common.NEW_ID, "delete-role", "Role to allow deleting.");
    roleService.insert(temp);
    deleteRole = new Role(temp);
    readUser = createUser("readUser", "readUser", "password", "readUser@example.com", readRole);
    editUser = createUser("editUser", "editUser", "password", "editUser@example.com", editRole);
    setUser = createUser("setUser", "setUser", "password", "setUser@example.com", setRole);
    deleteUser = createUser("deleteUser", "deleteUser", "password", "deleteUser@example.com", deleteRole);
    allUser = createUser("allUser", "allUser", "password", "allUser@example.com", readRole, editRole, setRole, deleteRole);
}
Also used : Role(com.serotonin.m2m2.vo.role.Role) RoleVO(com.serotonin.m2m2.vo.role.RoleVO) RoleService(com.infiniteautomation.mango.spring.service.RoleService)

Example 14 with RoleService

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

the class LazyFieldJsonTest method testLazyPermissionInObject.

@Test
public void testLazyPermissionInObject() {
    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();
    LazyContainer container = new LazyContainer();
    container.supplyPermission(() -> 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(container);
        writer.setPrettyIndent(0);
        writer.setPrettyOutput(true);
        writer.writeObject(value);
        String json = stringWriter.toString();
        JsonTypeReader typeReader = new JsonTypeReader(json);
        JsonValue read = typeReader.read();
        JsonObject root = read.toJsonObject();
        JsonReader reader = new JsonReader(Common.JSON_CONTEXT, root);
        ImportContext context = new ImportContext(reader, new ProcessResult(), Common.getTranslations());
        LazyContainer readContainer = new LazyContainer();
        context.getReader().readInto(readContainer, root);
        assertEquals(container.getPermission(), readContainer.getPermission());
    } catch (IOException | JsonException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : JsonException(com.serotonin.json.JsonException) JsonValue(com.serotonin.json.type.JsonValue) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) JsonObject(com.serotonin.json.type.JsonObject) IOException(java.io.IOException) JsonWriter(com.serotonin.json.JsonWriter) JsonTypeWriter(com.serotonin.json.type.JsonTypeWriter) PermissionService(com.infiniteautomation.mango.spring.service.PermissionService) Role(com.serotonin.m2m2.vo.role.Role) 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) Test(org.junit.Test)

Example 15 with RoleService

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

the class DataSourceDaoDeadlockDetection method detectDeadlockWithEventHandlerRoleMappingandDataSourceTablesExplicit.

@Test
public void detectDeadlockWithEventHandlerRoleMappingandDataSourceTablesExplicit() {
    // This will create 2x threads for each operating as one of the desired problem scenarios
    int numThreads = 5;
    int numDataSources = 10;
    AtomicInteger running = new AtomicInteger(numThreads * 2);
    PermissionService permissionService = Common.getBean(PermissionService.class);
    // Insert some roles
    int roleCount = 0;
    RoleService roleService = Common.getBean(RoleService.class);
    List<RoleVO> roleVOs = new ArrayList<>();
    Set<Role> roles = new HashSet<>();
    for (int i = 0; i < roleCount; i++) {
        RoleVO role = new RoleVO(Common.NEW_ID, Common.generateXid("ROLE_"), "Role " + i);
        roleVOs.add(role);
        roleService.insert(role);
        roles.add(role.getRole());
    }
    DataSource dataSource = Common.getBean(DatabaseProxy.class).getDataSource();
    JdbcConnectionPool pool = (JdbcConnectionPool) dataSource;
    pool.setMaxConnections(numThreads * 2);
    PlatformTransactionManager transactionManager = Common.getBean(DatabaseProxy.class).getTransactionManager();
    AtomicInteger successes = new AtomicInteger();
    AtomicInteger failures = new AtomicInteger();
    MutableObject<Exception> failure = new MutableObject<>(null);
    for (int i = 0; i < numThreads; i++) {
        // #5 lock eventHandlerMappings and roleMappings and then try to lock dataSources
        // Basically delete a data source
        new Thread() {

            @Override
            public void run() {
                try {
                    for (int i = 0; i < numDataSources; i++) {
                        // Insert an event handler
                        EventHandlerService eventHandlerService = Common.getBean(EventHandlerService.class);
                        ProcessEventHandlerVO eh = new ProcessEventHandlerVO();
                        eh.setDefinition(new ProcessEventHandlerDefinition());
                        eh.setName(Common.generateXid("Handler "));
                        eh.setActiveProcessCommand("ls");
                        eventHandlerService.insert(eh);
                        ExtendedJdbcTemplate ejt = new ExtendedJdbcTemplate(dataSource);
                        // Get event handler
                        AbstractEventHandlerVO myEventHandler = eventHandlerService.get(eh.getXid());
                        // Create data source
                        MockDataSourceVO ds = new MockDataSourceVO();
                        ds.setName(Common.generateXid("Mock "));
                        DataSourceService dataSourceService = Common.getBean(DataSourceService.class);
                        dataSourceService.insert(ds);
                        // Insert a mapping
                        myEventHandler.setEventTypes(Collections.singletonList(new EventTypeMatcher(new DataSourceEventType(ds.getId(), ds.getPollAbortedExceptionEventId()))));
                        eventHandlerService.update(eh.getXid(), myEventHandler);
                        new TransactionTemplate(transactionManager).execute((status) -> {
                            // The order of these statements matters for deadlock, we must always lock groups of tables in the same order
                            ejt.update("DELETE FROM dataSources WHERE id=?", new Object[] { ds.getId() });
                            ejt.update("DELETE FROM eventHandlersMapping WHERE eventTypeName=? AND eventTypeRef1=?", new Object[] { EventTypeNames.DATA_SOURCE, ds.getId() });
                            return null;
                        });
                        successes.getAndIncrement();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    failure.setValue(e);
                    failures.getAndIncrement();
                } finally {
                    running.decrementAndGet();
                }
            }
        }.start();
        // #8 lock dataSources and try to lock roleMappings
        // Basically update a data source
        new Thread() {

            @Override
            public void run() {
                try {
                    for (int i = 0; i < numDataSources; i++) {
                        ExtendedJdbcTemplate ejt = new ExtendedJdbcTemplate(dataSource);
                        // Insert an event handler
                        EventHandlerService eventHandlerService = Common.getBean(EventHandlerService.class);
                        ProcessEventHandlerVO eh = new ProcessEventHandlerVO();
                        eh.setDefinition(new ProcessEventHandlerDefinition());
                        eh.setName(Common.generateXid("Handler "));
                        eh.setActiveProcessCommand("ls");
                        eventHandlerService.insert(eh);
                        // Get event handler
                        AbstractEventHandlerVO myEventHandler = eventHandlerService.get(eh.getXid());
                        // Create data source
                        MockDataSourceVO ds = new MockDataSourceVO();
                        ds.setName(Common.generateXid("Mock "));
                        DataSourceService dataSourceService = Common.getBean(DataSourceService.class);
                        dataSourceService.insert(ds);
                        // Insert a mapping
                        myEventHandler.setEventTypes(Collections.singletonList(new EventTypeMatcher(new DataSourceEventType(ds.getId(), ds.getPollAbortedExceptionEventId()))));
                        eventHandlerService.update(eh.getXid(), myEventHandler);
                        new TransactionTemplate(transactionManager).execute((status) -> {
                            ejt.update("UPDATE dataSources SET xid=? WHERE id=?", new Object[] { ds.getXid() + "1", ds.getId() });
                            return null;
                        });
                        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 : DataSourceService(com.infiniteautomation.mango.spring.service.DataSourceService) Role(com.serotonin.m2m2.vo.role.Role) BeforeClass(org.junit.BeforeClass) EventHandlerService(com.infiniteautomation.mango.spring.service.EventHandlerService) ProcessEventHandlerDefinition(com.serotonin.m2m2.module.definitions.event.handlers.ProcessEventHandlerDefinition) EventTypeNames(com.serotonin.m2m2.rt.event.type.EventType.EventTypeNames) MockDataSourceVO(com.serotonin.m2m2.vo.dataSource.mock.MockDataSourceVO) ProcessEventHandlerVO(com.serotonin.m2m2.vo.event.ProcessEventHandlerVO) LoggerFactory(org.slf4j.LoggerFactory) DataSourceEventType(com.serotonin.m2m2.rt.event.type.DataSourceEventType) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) ArrayList(java.util.ArrayList) ExtendedJdbcTemplate(com.serotonin.db.spring.ExtendedJdbcTemplate) HashSet(java.util.HashSet) EventTypeMatcher(com.serotonin.m2m2.rt.event.type.EventTypeMatcher) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RoleVO(com.serotonin.m2m2.vo.role.RoleVO) DataSource(javax.sql.DataSource) MangoTestBase(com.serotonin.m2m2.MangoTestBase) DataPointService(com.infiniteautomation.mango.spring.service.DataPointService) Assert.fail(org.junit.Assert.fail) MutableObject(org.apache.commons.lang3.mutable.MutableObject) MockPointLocatorVO(com.serotonin.m2m2.vo.dataPoint.MockPointLocatorVO) Logger(org.slf4j.Logger) Common(com.serotonin.m2m2.Common) DatabaseProxy(com.serotonin.m2m2.db.DatabaseProxy) Set(java.util.Set) Test(org.junit.Test) UUID(java.util.UUID) AbstractEventHandlerVO(com.serotonin.m2m2.vo.event.AbstractEventHandlerVO) List(java.util.List) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) Collections(java.util.Collections) PermissionService(com.infiniteautomation.mango.spring.service.PermissionService) RoleService(com.infiniteautomation.mango.spring.service.RoleService) JdbcConnectionPool(org.h2.jdbcx.JdbcConnectionPool) ArrayList(java.util.ArrayList) ExtendedJdbcTemplate(com.serotonin.db.spring.ExtendedJdbcTemplate) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) AbstractEventHandlerVO(com.serotonin.m2m2.vo.event.AbstractEventHandlerVO) PermissionService(com.infiniteautomation.mango.spring.service.PermissionService) EventHandlerService(com.infiniteautomation.mango.spring.service.EventHandlerService) HashSet(java.util.HashSet) MutableObject(org.apache.commons.lang3.mutable.MutableObject) ProcessEventHandlerVO(com.serotonin.m2m2.vo.event.ProcessEventHandlerVO) MockDataSourceVO(com.serotonin.m2m2.vo.dataSource.mock.MockDataSourceVO) EventTypeMatcher(com.serotonin.m2m2.rt.event.type.EventTypeMatcher) DataSourceEventType(com.serotonin.m2m2.rt.event.type.DataSourceEventType) JdbcConnectionPool(org.h2.jdbcx.JdbcConnectionPool) DatabaseProxy(com.serotonin.m2m2.db.DatabaseProxy) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) DataSource(javax.sql.DataSource) DataSourceService(com.infiniteautomation.mango.spring.service.DataSourceService) Role(com.serotonin.m2m2.vo.role.Role) ProcessEventHandlerDefinition(com.serotonin.m2m2.module.definitions.event.handlers.ProcessEventHandlerDefinition) RoleVO(com.serotonin.m2m2.vo.role.RoleVO) RoleService(com.infiniteautomation.mango.spring.service.RoleService) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MutableObject(org.apache.commons.lang3.mutable.MutableObject) Test(org.junit.Test)

Aggregations

RoleService (com.infiniteautomation.mango.spring.service.RoleService)15 RoleVO (com.serotonin.m2m2.vo.role.RoleVO)14 Role (com.serotonin.m2m2.vo.role.Role)11 PermissionService (com.infiniteautomation.mango.spring.service.PermissionService)6 Test (org.junit.Test)6 Collections (java.util.Collections)5 Set (java.util.Set)5 ImportContext (com.infiniteautomation.mango.emport.ImportContext)4 JsonException (com.serotonin.json.JsonException)4 JsonReader (com.serotonin.json.JsonReader)4 JsonWriter (com.serotonin.json.JsonWriter)4 JsonTypeReader (com.serotonin.json.type.JsonTypeReader)4 JsonTypeWriter (com.serotonin.json.type.JsonTypeWriter)4 JsonValue (com.serotonin.json.type.JsonValue)4 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)4 IOException (java.io.IOException)4 StringWriter (java.io.StringWriter)4 ArrayList (java.util.ArrayList)4 HashSet (java.util.HashSet)4 Logger (org.slf4j.Logger)4