Search in sources :

Example 51 with RoleVO

use of com.serotonin.m2m2.vo.role.RoleVO in project ma-core-public by infiniteautomation.

the class UsersService method handleRoleEvent.

@EventListener
protected void handleRoleEvent(DaoEvent<? extends RoleVO> event) {
    if (event.getType() == DaoEventType.DELETE || event.getType() == DaoEventType.UPDATE) {
        Role originalRole = event.getType() == DaoEventType.UPDATE ? event.getOriginalVo().getRole() : event.getVo().getRole();
        // in the user here
        if (userByUsername != null) {
            userByUsername.asMap().forEach((username, user) -> {
                if (user.getRoles().contains(originalRole)) {
                    Set<Role> updatedRoles = new HashSet<>(user.getRoles());
                    if (event.getType() == DaoEventType.DELETE) {
                        // Remove this role
                        updatedRoles.remove(originalRole);
                    } else if (event.getType() == DaoEventType.UPDATE) {
                        // Replace this role
                        updatedRoles.remove(originalRole);
                        updatedRoles.add(event.getVo().getRole());
                    }
                    user.setRoles(Collections.unmodifiableSet(updatedRoles));
                    // publish the event using the same user for originalVo, we aren't changing the XID
                    // so it shouldn't matter
                    DaoEvent<User> userUpdatedEvent = new DaoEvent<>(this.dao, UPDATE, user, user);
                    this.eventPublisher.publishEvent(userUpdatedEvent);
                }
            });
        }
    }
}
Also used : Role(com.serotonin.m2m2.vo.role.Role) DaoEvent(com.infiniteautomation.mango.spring.events.DaoEvent) User(com.serotonin.m2m2.vo.User) HashSet(java.util.HashSet) EventListener(org.springframework.context.event.EventListener)

Example 52 with RoleVO

use of com.serotonin.m2m2.vo.role.RoleVO in project ma-core-public by infiniteautomation.

the class RoleService method commonValidation.

public ProcessResult commonValidation(RoleVO vo) {
    ProcessResult result = super.validate(vo);
    // Don't allow the use of role 'user' or 'superadmin'
    if (StringUtils.equalsIgnoreCase(vo.getXid(), getSuperadminRole().getXid())) {
        result.addContextualMessage("xid", "roles.cannotAlterSuperadminRole");
    }
    if (StringUtils.equalsIgnoreCase(vo.getXid(), getUserRole().getXid())) {
        result.addContextualMessage("xid", "roles.cannotAlterUserRole");
    }
    if (StringUtils.equalsIgnoreCase(vo.getXid(), getAnonymousRole().getXid())) {
        result.addContextualMessage("xid", "roles.cannotAlterAnonymousRole");
    }
    // Don't allow spaces in the XID
    Matcher matcher = Functions.WHITESPACE_PATTERN.matcher(vo.getXid());
    if (matcher.find()) {
        result.addContextualMessage("xid", "validate.role.noSpaceAllowed");
    }
    // Ensure inherited roles exist and they are not us and there are no loops
    if (vo.getInherited() != null) {
        Set<Role> used = new HashSet<>();
        used.add(vo.getRole());
        for (Role role : vo.getInherited()) {
            if (dao.getXidById(role.getId()) == null) {
                result.addContextualMessage("inherited", "validate.role.notFound", role.getXid());
            }
            if (recursivelyCheckForUsedRoles(role, used)) {
                result.addContextualMessage("inherited", "validate.role.inheritanceLoop", role.getXid());
                break;
            }
        }
    }
    return result;
}
Also used : Role(com.serotonin.m2m2.vo.role.Role) Matcher(java.util.regex.Matcher) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) HashSet(java.util.HashSet)

Example 53 with RoleVO

use of com.serotonin.m2m2.vo.role.RoleVO in project ma-core-public by infiniteautomation.

the class EmailEventHandlerDefinition method handleRoleEvent.

@Override
public void handleRoleEvent(EmailEventHandlerVO vo, DaoEvent<? extends RoleVO> event) {
    // Remove and re-serialize our handler's script roles if it has a role that was deleted
    if (vo.getScriptRoles().getRoles().contains(event.getVo().getRole())) {
        switch(event.getType()) {
            case UPDATE:
                break;
            case DELETE:
                Set<Role> updated = new HashSet<>(vo.getScriptRoles().getRoles());
                updated.remove(event.getVo().getRole());
                Set<Role> allRoles = new HashSet<>();
                for (Role role : updated) {
                    allRoles.addAll(service.getAllInheritedRoles(role));
                }
                ScriptPermissions permission = new ScriptPermissions(allRoles, vo.getScriptRoles().getPermissionHolderName());
                vo.setScriptRoles(permission);
                eventHandlerService.update(vo.getId(), vo);
                break;
            default:
                break;
        }
    }
}
Also used : Role(com.serotonin.m2m2.vo.role.Role) ScriptPermissions(com.infiniteautomation.mango.util.script.ScriptPermissions) HashSet(java.util.HashSet)

Example 54 with RoleVO

use of com.serotonin.m2m2.vo.role.RoleVO in project ma-core-public by infiniteautomation.

the class SystemSettingsImporter method importImpl.

@Override
protected void importImpl() {
    try {
        Map<String, Object> settings = new HashMap<String, Object>();
        // Finish reading it in.
        for (String key : json.keySet()) {
            JsonValue value = json.get(key);
            // Don't import null values or database schemas
            if ((value != null) && (!key.startsWith(SystemSettingsDao.DATABASE_SCHEMA_VERSION))) {
                Object o = value.toNative();
                if (o instanceof String) {
                    PermissionDefinition def = ModuleRegistry.getPermissionDefinition(key);
                    if (def != null) {
                        // Legacy permission import
                        try {
                            Set<String> xids = PermissionService.explodeLegacyPermissionGroups((String) o);
                            Set<Set<Role>> roles = new HashSet<>();
                            for (String xid : xids) {
                                RoleVO role = roleService.get(xid);
                                if (role != null) {
                                    roles.add(Collections.singleton(role.getRole()));
                                } else {
                                    roles.add(Collections.singleton(new Role(Common.NEW_ID, xid)));
                                }
                            }
                            permissionService.update(new MangoPermission(roles), def);
                            addSuccessMessage(false, "emport.permission.prefix", key);
                        } catch (ValidationException e) {
                            setValidationMessages(e.getValidationResult(), "emport.permission.prefix", key);
                            return;
                        }
                    } else {
                        // Could be an export code so try and convert it
                        Integer id = SystemSettingsDao.getInstance().convertToValueFromCode(key, (String) o);
                        if (id != null)
                            settings.put(key, id);
                        else
                            settings.put(key, o);
                    }
                } else {
                    settings.put(key, o);
                }
            }
        }
        // Now validate it. Use a new response object so we can distinguish errors in this vo
        // from
        // other errors.
        ProcessResult voResponse = new ProcessResult();
        SystemSettingsDao.getInstance().validate(settings, voResponse, user);
        if (voResponse.getHasMessages())
            setValidationMessages(voResponse, "emport.systemSettings.prefix", new TranslatableMessage("header.systemSettings").translate(Common.getTranslations()));
        else {
            SystemSettingsDao.getInstance().updateSettings(settings);
            addSuccessMessage(false, "emport.systemSettings.prefix", new TranslatableMessage("header.systemSettings").translate(Common.getTranslations()));
        }
    } catch (Exception e) {
        addFailureMessage("emport.systemSettings.prefix", new TranslatableMessage("header.systemSettings").translate(Common.getTranslations()), e.getMessage());
    }
}
Also used : PermissionDefinition(com.serotonin.m2m2.module.PermissionDefinition) Set(java.util.Set) HashSet(java.util.HashSet) ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) HashMap(java.util.HashMap) JsonValue(com.serotonin.json.type.JsonValue) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) Role(com.serotonin.m2m2.vo.role.Role) RoleVO(com.serotonin.m2m2.vo.role.RoleVO) JsonObject(com.serotonin.json.type.JsonObject) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) MangoPermission(com.infiniteautomation.mango.permission.MangoPermission) HashSet(java.util.HashSet)

Example 55 with RoleVO

use of com.serotonin.m2m2.vo.role.RoleVO 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)

Aggregations

RoleVO (com.serotonin.m2m2.vo.role.RoleVO)58 Test (org.junit.Test)34 Role (com.serotonin.m2m2.vo.role.Role)33 HashSet (java.util.HashSet)17 RoleService (com.infiniteautomation.mango.spring.service.RoleService)14 User (com.serotonin.m2m2.vo.User)11 ArrayList (java.util.ArrayList)11 ExpectValidationException (com.infiniteautomation.mango.rules.ExpectValidationException)8 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)8 PermissionService (com.infiniteautomation.mango.spring.service.PermissionService)7 JsonValue (com.serotonin.json.type.JsonValue)7 RoleDao (com.serotonin.m2m2.db.dao.RoleDao)7 Set (java.util.Set)7 Roles (com.infiniteautomation.mango.db.tables.Roles)6 JsonException (com.serotonin.json.JsonException)6 DSLContext (org.jooq.DSLContext)6 MangoPermission (com.infiniteautomation.mango.permission.MangoPermission)5 JsonObject (com.serotonin.json.type.JsonObject)5 ImportContext (com.infiniteautomation.mango.emport.ImportContext)4 JsonReader (com.serotonin.json.JsonReader)4