use of com.b2international.snowowl.core.identity.User in project snow-owl by b2ihealthcare.
the class CommitInfoSearchRequest method addSecurityFilter.
private void addSecurityFilter(final ExpressionBuilder builder, RepositoryContext context) {
final User user = context.service(User.class);
if (user.isAdministrator() || user.hasPermission(Permission.requireAll(Permission.OPERATION_BROWSE, Permission.ALL))) {
return;
}
final List<Permission> readPermissions = user.getPermissions().stream().filter(p -> Permission.ALL.equals(p.getOperation()) || Permission.OPERATION_BROWSE.equals(p.getOperation())).collect(Collectors.toList());
final Set<String> exactResourceIds = readPermissions.stream().flatMap(p -> p.getResources().stream()).filter(resource -> !resource.endsWith("*")).collect(Collectors.toSet());
final Set<String> resourceIdPrefixes = readPermissions.stream().flatMap(p -> p.getResources().stream()).filter(resource -> isWildCardResource(resource)).map(resource -> resource.substring(0, resource.length() - 1)).collect(Collectors.toSet());
SetView<String> resourceIds = Sets.union(exactResourceIds, resourceIdPrefixes);
ExpressionBuilder branchFilter = Expressions.builder();
ResourceRequests.prepareSearch().filterByIds(resourceIds).setLimit(resourceIds.size()).setFields(ResourceDocument.Fields.ID, ResourceDocument.Fields.BRANCH_PATH, ResourceDocument.Fields.RESOURCE_TYPE).buildAsync().getRequest().execute(context).stream().filter(TerminologyResource.class::isInstance).map(TerminologyResource.class::cast).forEach(r -> {
if (resourceIdPrefixes.contains(r.getId())) {
final String branchPattern = String.format("%s(/[a-zA-Z0-9.~_\\-]{1,%d})?", r.getBranchPath(), DEFAULT_MAXIMUM_BRANCH_NAME_LENGTH);
branchFilter.should(regexp(BRANCH, branchPattern));
}
});
builder.filter(branchFilter.build());
}
use of com.b2international.snowowl.core.identity.User in project snow-owl by b2ihealthcare.
the class RemoteJob method run.
@Override
protected final IStatus run(IProgressMonitor monitor) {
final ObjectMapper mapper = this.context.service(ObjectMapper.class);
final IProgressMonitor trackerMonitor = this.context.service(RemoteJobTracker.class).createMonitor(id, monitor);
try {
// override user when necessary
User user = context.service(User.class);
if (User.isSystem(this.user)) {
user = User.SYSTEM;
} else if (!user.getUsername().equals(this.user)) {
user = UserRequests.prepareGet(this.user).build().execute(this.context);
}
// seed the monitor instance into the current context, so the request can use it for progress reporting
final ServiceProvider context = this.context.inject().bind(IProgressMonitor.class, trackerMonitor).bind(RemoteJob.class, this).bind(User.class, user).build();
final Object response = request.execute(context);
if (response != null) {
final Class<? extends Object> responseType = response.getClass();
if (Primitives.isWrapperType(responseType) || String.class.isAssignableFrom(responseType) || UUID.class.isAssignableFrom(responseType)) {
this.response = toJson(mapper, ImmutableMap.of("value", response));
} else {
this.response = toJson(mapper, response);
}
}
final IStatus status = (IStatus) getProperty(REQUEST_STATUS);
return (status != null) ? status : Statuses.ok();
} catch (OperationCanceledException e) {
return Statuses.cancel();
} catch (Throwable e) {
final ApiError apiError;
if (e instanceof ApiException) {
apiError = ((ApiException) e).toApiError();
} else {
apiError = ApiError.builder(e.getMessage()).status(500).developerMessage("Exception caught while executing request in remote job.").addInfo("exception-class", e.getClass().getSimpleName()).build();
}
this.response = toJson(mapper, apiError);
// XXX: Don't delete remote jobs with errors
autoClean = false;
return Statuses.error(CoreActivator.PLUGIN_ID, "Failed to execute long running request", e);
} finally {
if (autoClean) {
context.service(RemoteJobTracker.class).requestDeletes(Collections.singleton(id));
}
}
}
use of com.b2international.snowowl.core.identity.User in project snow-owl by b2ihealthcare.
the class CommitInfoRequestTest method searchCommitInfoByBranch.
@Test
public void searchCommitInfoByBranch() {
final String oid = UUID.randomUUID().toString();
final String shortName = "Resource6";
final String comment = "Code system for commit info 6";
final String branchName = "Test6";
final String term = "Test Description 6";
createCodeSystem(shortName, oid, comment);
final String branchPath = createBranch(String.format("%s/%s", BRANCH, shortName), branchName);
createDescription(ResourceURI.branch(CodeSystem.RESOURCE_TYPE, shortName, branchName), term, comment);
// Search as admin
assertEquals(1, RepositoryRequests.commitInfos().prepareSearchCommitInfo().filterByBranch(branchPath).build(REPOSITORY_ID).execute(bus).getSync().getTotal());
final Permission userPermission = Permission.requireAll(Permission.OPERATION_BROWSE, String.format("%s*", shortName));
final List<Role> roles = List.of(new Role("Editor", List.of(userPermission)));
final String userName = "User6";
final User user = new User(userName, roles);
final IEventBus authorizedBus = new AuthorizedEventBus(bus, ImmutableMap.of(AuthorizedRequest.AUTHORIZATION_HEADER, Services.service(JWTGenerator.class).generate(user)));
// Search as user with limited permissions
assertEquals(1, RepositoryRequests.commitInfos().prepareSearchCommitInfo().filterByBranch(branchPath).build(REPOSITORY_ID).execute(authorizedBus).getSync().getTotal());
}
use of com.b2international.snowowl.core.identity.User in project snow-owl by b2ihealthcare.
the class AuthorizedRequest method execute.
@Override
public R execute(ServiceProvider context) {
final RequestHeaders requestHeaders = context.service(RequestHeaders.class);
final String authorizationToken = requestHeaders.header(AUTHORIZATION_HEADER);
final IdentityProvider identityProvider = context.service(IdentityProvider.class);
final Collection<Request<?, ?>> requests = getNestedRequests();
final User user;
// if there is no authentication configured
if (IdentityProvider.NOOP == identityProvider) {
// allow execution as SYSTEM user
user = User.SYSTEM;
} else if (Strings.isNullOrEmpty(authorizationToken)) {
// allow login requests in
if (requests.stream().allMatch(req -> req.getClass().isAnnotationPresent(Unprotected.class))) {
user = User.SYSTEM;
} else {
// if there is authentication configured, but no authorization token found prevent execution and throw UnauthorizedException
if (PlatformUtil.isDevVersion()) {
Request<?, ?> request = Iterables.getFirst(requests, null);
System.err.println(request);
}
throw new UnauthorizedException("Missing authorization token");
}
} else {
// verify authorization header value
user = context.service(AuthorizationHeaderVerifier.class).auth(authorizationToken);
if (user == null) {
throw new UnauthorizedException("Incorrect authorization token");
}
}
ServiceProvider userContext = context.inject().bind(User.class, user).bind(IEventBus.class, new AuthorizedEventBus(context.service(IEventBus.class), requestHeaders.headers())).build();
if (!User.SYSTEM.equals(user) && !user.isAdministrator()) {
// authorize user whether it is permitted to execute the request(s) or not
requests.stream().filter(AccessControl.class::isInstance).map(AccessControl.class::cast).flatMap(ac -> {
List<Permission> permissions = ac.getPermissions(userContext, next());
if (permissions.isEmpty()) {
context.log().warn("No permissions required to execute request '{}'.", MonitoredRequest.toJson(context, next(), Map.of()));
}
return permissions.stream();
}).forEach(permissionRequirement -> {
if (!user.hasPermission(permissionRequirement)) {
throw new ForbiddenException("Operation not permitted. '%s' permission is required. User has '%s'.", permissionRequirement.getPermission(), user.getPermissions());
}
});
}
return next(userContext);
}
use of com.b2international.snowowl.core.identity.User in project snow-owl by b2ihealthcare.
the class LdapIdentityProvider method searchUsers.
@Override
public Promise<Users> searchUsers(Collection<String> usernames, int limit) {
final ImmutableList.Builder<User> resultBuilder = ImmutableList.builder();
final String uidProp = conf.getUserIdProperty();
InitialLdapContext context = null;
NamingEnumeration<SearchResult> searchResultEnumeration = null;
try {
context = createLdapContext();
Collection<LdapRole> ldapRoles = getAllLdapRoles(context);
searchResultEnumeration = context.search(conf.getBaseDn(), conf.getUserFilter(), createSearchControls(ATTRIBUTE_DN, uidProp));
for (final SearchResult searchResult : ImmutableList.copyOf(Iterators.forEnumeration(searchResultEnumeration))) {
final Attributes attributes = searchResult.getAttributes();
if (hasAttribute(attributes, uidProp)) {
final String userName = (String) attributes.get(uidProp).get();
final List<Role> userRoles = ldapRoles.stream().filter(role -> role.getUniqueMembers().contains(searchResult.getNameInNamespace())).map(role -> new Role(role.getName(), role.getPermissions())).collect(Collectors.toList());
resultBuilder.add(new User(userName, userRoles));
}
}
final List<User> users = resultBuilder.build().stream().sorted((u1, u2) -> u1.getUsername().compareTo(u2.getUsername())).filter(user -> usernames.isEmpty() || usernames.contains(user.getUsername())).limit(limit).collect(Collectors.toList());
return Promise.immediate(new Users(users, limit, users.size()));
} catch (final NamingException e) {
LOG.error("Couldn't search users/roles due to LDAP communication error: {}", e.getMessage(), e);
throw new SnowowlRuntimeException(e);
} finally {
closeNamingEnumeration(searchResultEnumeration);
closeLdapContext(context);
}
}
Aggregations