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);
}
});
}
}
}
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;
}
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;
}
}
}
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());
}
}
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;
}
Aggregations