use of io.swagger.annotations.Authorization in project CzechIdMng by bcvsolutions.
the class SchedulerController method find.
/**
* Finds scheduled tasks
*
* @return all tasks
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@ResponseBody
@RequestMapping(method = RequestMethod.GET)
@PreAuthorize("hasAuthority('" + CoreGroupPermission.SCHEDULER_READ + "')")
@ApiOperation(value = "Search scheduled tasks", nickname = "searchSchedulerTasks", tags = { SchedulerController.TAG }, authorizations = { @Authorization(value = SwaggerConfig.AUTHENTICATION_BASIC, scopes = { @AuthorizationScope(scope = CoreGroupPermission.SCHEDULER_READ, description = "") }), @Authorization(value = SwaggerConfig.AUTHENTICATION_CIDMST, scopes = { @AuthorizationScope(scope = CoreGroupPermission.SCHEDULER_READ, description = "") }) })
@ApiImplicitParams({ @ApiImplicitParam(name = "page", dataType = "string", paramType = "query", value = "Results page you want to retrieve (0..N)"), @ApiImplicitParam(name = "size", dataType = "string", paramType = "query", value = "Number of records per page."), @ApiImplicitParam(name = "sort", allowMultiple = true, dataType = "string", paramType = "query", value = "Sorting criteria in the format: property(,asc|desc). " + "Default sort order is ascending. " + "Multiple sort criteria are supported.") })
public Resources<Task> find(@RequestParam(required = false) MultiValueMap<String, Object> parameters, @PageableDefault Pageable pageable) {
String text = getParameterConverter().toString(parameters, DataFilter.PARAMETER_TEXT);
List<Task> tasks = schedulerService.getAllTasks().stream().filter(task -> {
// filter - like name or description only
return StringUtils.isEmpty(text) || task.getTaskType().getSimpleName().toLowerCase().contains(text.toLowerCase()) || (task.getDescription() != null && task.getDescription().toLowerCase().contains(text.toLowerCase()));
}).sorted((taskOne, taskTwo) -> {
Sort sort = pageable.getSort();
if (pageable.getSort() == null) {
return 0;
}
int compareAscValue = 0;
boolean asc = true;
// "naive" sort implementation
if (sort.getOrderFor(PROPERTY_TASK_TYPE) != null) {
asc = sort.getOrderFor(PROPERTY_TASK_TYPE).isAscending();
compareAscValue = taskOne.getTaskType().getSimpleName().compareTo(taskTwo.getTaskType().getSimpleName());
}
if (sort.getOrderFor(PROPERTY_DESCRIPTION) != null) {
asc = sort.getOrderFor(PROPERTY_DESCRIPTION).isAscending();
compareAscValue = taskOne.getDescription().compareTo(taskTwo.getDescription());
}
if (sort.getOrderFor(PROPERTY_INSTANCE_ID) != null) {
asc = sort.getOrderFor(PROPERTY_INSTANCE_ID).isAscending();
compareAscValue = taskOne.getInstanceId().compareTo(taskTwo.getInstanceId());
}
return asc ? compareAscValue : compareAscValue * -1;
}).collect(Collectors.toList());
// "naive" pagination
int first = pageable.getPageNumber() * pageable.getPageSize();
int last = pageable.getPageSize() + first;
List<Task> taskPage = tasks.subList(first < tasks.size() ? first : tasks.size() > 0 ? tasks.size() - 1 : 0, last < tasks.size() ? last : tasks.size());
//
return pageToResources(new PageImpl(taskPage, pageable, tasks.size()), Task.class);
}
use of io.swagger.annotations.Authorization in project workbench by all-of-us.
the class AuthInterceptor method preHandle.
/**
* Returns true iff the request is auth'd and should proceed. Publishes authenticated user info
* using Spring's SecurityContext.
* @param handler The Swagger-generated ApiController. It contains our handler as a private
* delegate.
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// OPTIONS methods requests don't need authorization.
if (request.getMethod().equals(HttpMethods.OPTIONS)) {
return true;
}
HandlerMethod method = (HandlerMethod) handler;
boolean isAuthRequired = false;
ApiOperation apiOp = AnnotationUtils.findAnnotation(method.getMethod(), ApiOperation.class);
if (apiOp != null) {
for (Authorization auth : apiOp.authorizations()) {
if (auth.value().equals(authName)) {
isAuthRequired = true;
break;
}
}
}
if (!isAuthRequired) {
return true;
}
String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
log.warning("No bearer token found in request");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
String token = authorizationHeader.substring("Bearer".length()).trim();
Userinfoplus userInfo;
try {
userInfo = userInfoService.getUserInfo(token);
} catch (HttpResponseException e) {
log.log(Level.WARNING, "{0} response getting user info for bearer token {1}: {2}", new Object[] { e.getStatusCode(), token, e.getStatusMessage() });
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
// TODO: check Google group membership to ensure user is in registered user group
String userEmail = userInfo.getEmail();
WorkbenchConfig workbenchConfig = workbenchConfigProvider.get();
if (workbenchConfig.auth.serviceAccountApiUsers.contains(userEmail)) {
// Whitelisted service accounts are able to make API calls, too.
// TODO: stop treating service accounts as normal users, have a separate table for them,
// administrators.
User user = userDao.findUserByEmail(userEmail);
if (user == null) {
user = userService.createServiceAccountUser(userEmail);
}
SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(user, userInfo, token, UserType.SERVICE_ACCOUNT));
log.log(Level.INFO, "{0} service account in use", userInfo.getEmail());
return true;
}
String gsuiteDomainSuffix = "@" + workbenchConfig.googleDirectoryService.gSuiteDomain;
if (!userEmail.endsWith(gsuiteDomainSuffix)) {
try {
// If the email isn't in our GSuite domain, try FireCloud; we could be dealing with a
// pet service account. In both AofU and FireCloud, the pet SA is treated as if it were
// the user it was created for.
userEmail = fireCloudService.getMe().getUserInfo().getUserEmail();
} catch (ApiException e) {
log.log(Level.INFO, "FireCloud lookup for {0} failed, can't access the workbench: {1}", new Object[] { userInfo.getEmail(), e.getMessage() });
response.sendError(e.getCode());
return false;
}
if (!userEmail.endsWith(gsuiteDomainSuffix)) {
log.log(Level.INFO, "User {0} isn't in domain {1}, can't access the workbench", new Object[] { userEmail, gsuiteDomainSuffix });
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return false;
}
}
User user = userDao.findUserByEmail(userEmail);
if (user == null) {
// TODO(danrodney): start populating contact email in Google account, use it here.
user = userService.createUser(userInfo.getGivenName(), userInfo.getFamilyName(), userInfo.getEmail(), null);
} else {
if (user.getDisabled()) {
throw new ForbiddenException(ExceptionUtils.errorResponse(ErrorCode.USER_DISABLED, "This user account has been disabled."));
}
}
SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(user, userInfo, token, UserType.RESEARCHER));
// TODO: setup this in the context, get rid of log statement
log.log(Level.INFO, "{0} logged in", userInfo.getEmail());
if (!hasRequiredAuthority(method, user)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return false;
}
return true;
}
use of io.swagger.annotations.Authorization in project CzechIdMng by bcvsolutions.
the class SysRemoteServerController method getConnectorTypes.
/**
* Returns connector types registered on given remote server.
*
* @return connector types
*/
@ResponseBody
@RequestMapping(method = RequestMethod.GET, value = "/{backendId}/connector-types")
@PreAuthorize("hasAuthority('" + AccGroupPermission.REMOTESERVER_READ + "')")
@ApiOperation(value = "Get supported connector types", nickname = "getConnectorTypes", tags = { SysRemoteServerController.TAG }, authorizations = { @Authorization(value = SwaggerConfig.AUTHENTICATION_BASIC, scopes = { @AuthorizationScope(scope = AccGroupPermission.REMOTESERVER_READ, description = "") }), @Authorization(value = SwaggerConfig.AUTHENTICATION_CIDMST, scopes = { @AuthorizationScope(scope = AccGroupPermission.REMOTESERVER_READ, description = "") }) })
public Resources<ConnectorTypeDto> getConnectorTypes(@ApiParam(value = "Remote server uuid identifier or code.", required = true) @PathVariable @NotNull String backendId) {
SysConnectorServerDto connectorServer = getDto(backendId);
if (connectorServer == null) {
throw new EntityNotFoundException(getService().getEntityClass(), backendId);
}
//
try {
List<IcConnectorInfo> connectorInfos = Lists.newArrayList();
for (IcConfigurationService config : icConfiguration.getIcConfigs().values()) {
connectorServer.setPassword(remoteServerService.getPassword(connectorServer.getId()));
Set<IcConnectorInfo> availableRemoteConnectors = config.getAvailableRemoteConnectors(connectorServer);
if (CollectionUtils.isNotEmpty(availableRemoteConnectors)) {
connectorInfos.addAll(availableRemoteConnectors);
}
}
// Find connector types for existing connectors.
List<ConnectorTypeDto> connectorTypes = connectorManager.getSupportedTypes().stream().filter(connectorType -> {
return connectorInfos.stream().anyMatch(connectorInfo -> connectorType.getConnectorName().equals(connectorInfo.getConnectorKey().getConnectorName()));
}).map(connectorType -> {
// Find connector info and set version to the connectorTypeDto.
IcConnectorInfo info = connectorInfos.stream().filter(connectorInfo -> connectorType.getConnectorName().equals(connectorInfo.getConnectorKey().getConnectorName())).findFirst().orElse(null);
ConnectorTypeDto connectorTypeDto = connectorManager.convertTypeToDto(connectorType);
connectorTypeDto.setLocal(true);
if (info != null) {
connectorTypeDto.setVersion(info.getConnectorKey().getBundleVersion());
connectorTypeDto.setName(info.getConnectorDisplayName());
}
return connectorTypeDto;
}).collect(Collectors.toList());
// Find connectors without extension (specific connector type).
List<ConnectorTypeDto> defaultConnectorTypes = connectorInfos.stream().map(info -> {
ConnectorTypeDto connectorTypeDto = connectorManager.convertIcConnectorInfoToDto(info);
connectorTypeDto.setLocal(true);
return connectorTypeDto;
}).filter(type -> {
return !connectorTypes.stream().anyMatch(supportedType -> supportedType.getConnectorName().equals(type.getConnectorName()) && supportedType.isHideParentConnector());
}).collect(Collectors.toList());
connectorTypes.addAll(defaultConnectorTypes);
return new Resources<>(connectorTypes.stream().sorted(Comparator.comparing(ConnectorTypeDto::getOrder)).collect(Collectors.toList()));
} catch (IcInvalidCredentialException e) {
throw new ResultCodeException(AccResultCode.REMOTE_SERVER_INVALID_CREDENTIAL, ImmutableMap.of("server", e.getHost() + ":" + e.getPort()), e);
} catch (IcServerNotFoundException e) {
throw new ResultCodeException(AccResultCode.REMOTE_SERVER_NOT_FOUND, ImmutableMap.of("server", e.getHost() + ":" + e.getPort()), e);
} catch (IcCantConnectException e) {
throw new ResultCodeException(AccResultCode.REMOTE_SERVER_CANT_CONNECT, ImmutableMap.of("server", e.getHost() + ":" + e.getPort()), e);
} catch (IcRemoteServerException e) {
throw new ResultCodeException(AccResultCode.REMOTE_SERVER_UNEXPECTED_ERROR, ImmutableMap.of("server", e.getHost() + ":" + e.getPort()), e);
}
}
use of io.swagger.annotations.Authorization in project swagger-core by swagger-api.
the class Reader method read.
private Swagger read(Class<?> cls, String parentPath, String parentMethod, boolean isSubresource, String[] parentConsumes, String[] parentProduces, Map<String, Tag> parentTags, List<Parameter> parentParameters, Set<Class<?>> scannedResources) {
Map<String, Tag> tags = new LinkedHashMap<String, Tag>();
List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>();
String[] consumes = new String[0];
String[] produces = new String[0];
final Set<Scheme> globalSchemes = EnumSet.noneOf(Scheme.class);
Api api = ReflectionUtils.getAnnotation(cls, Api.class);
boolean hasPathAnnotation = (ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class) != null);
boolean hasApiAnnotation = (api != null);
boolean isApiHidden = hasApiAnnotation && api.hidden();
// class readable only if annotated with ((@Path and @Api) or isSubresource ) - and @Api not hidden
boolean classReadable = ((hasPathAnnotation && hasApiAnnotation) || isSubresource) && !isApiHidden;
// with scanAllResources true in config and @Api not hidden scan only if it has also @Path annotation or is subresource
boolean scanAll = !isApiHidden && config.isScanAllResources() && (hasPathAnnotation || isSubresource);
// readable if classReadable or scanAll
boolean readable = classReadable || scanAll;
if (!readable) {
return swagger;
}
// api readable only if @Api present; cannot be hidden because checked in classReadable.
boolean apiReadable = hasApiAnnotation;
if (apiReadable) {
// the value will be used as a tag for 2.0 UNLESS a Tags annotation is present
Set<String> tagStrings = extractTags(api);
for (String tagString : tagStrings) {
Tag tag = new Tag().name(tagString);
tags.put(tagString, tag);
}
for (String tagName : tags.keySet()) {
swagger.tag(tags.get(tagName));
}
if (!api.produces().isEmpty()) {
produces = ReaderUtils.splitContentValues(new String[] { api.produces() });
}
if (!api.consumes().isEmpty()) {
consumes = ReaderUtils.splitContentValues(new String[] { api.consumes() });
}
globalSchemes.addAll(parseSchemes(api.protocols()));
for (Authorization auth : api.authorizations()) {
if (auth.value() != null && !auth.value().isEmpty()) {
SecurityRequirement security = new SecurityRequirement();
security.setName(auth.value());
for (AuthorizationScope scope : auth.scopes()) {
if (scope.scope() != null && !scope.scope().isEmpty()) {
security.addScope(scope.scope());
}
}
securities.add(security);
}
}
}
if (readable) {
if (isSubresource) {
if (parentTags != null) {
tags.putAll(parentTags);
}
}
// merge consumes, produces
if (consumes.length == 0 && cls.getAnnotation(Consumes.class) != null) {
consumes = ReaderUtils.splitContentValues(cls.getAnnotation(Consumes.class).value());
}
if (produces.length == 0 && cls.getAnnotation(Produces.class) != null) {
produces = ReaderUtils.splitContentValues(cls.getAnnotation(Produces.class).value());
}
// look for method-level annotated properties
// handle sub-resources by looking at return type
final List<Parameter> globalParameters = new ArrayList<Parameter>();
// look for constructor-level annotated properties
globalParameters.addAll(ReaderUtils.collectConstructorParameters(cls, swagger));
// look for field-level annotated properties
globalParameters.addAll(ReaderUtils.collectFieldParameters(cls, swagger));
// build class/interface level @ApiResponse list
ApiResponses classResponseAnnotation = ReflectionUtils.getAnnotation(cls, ApiResponses.class);
List<ApiResponse> classApiResponses = new ArrayList<ApiResponse>();
if (classResponseAnnotation != null) {
classApiResponses.addAll(Arrays.asList(classResponseAnnotation.value()));
}
// parse the method
final javax.ws.rs.Path apiPath = ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class);
JavaType classType = TypeFactory.defaultInstance().constructType(cls);
BeanDescription bd = new ObjectMapper().getSerializationConfig().introspect(classType);
Method[] methods = cls.getMethods();
for (Method method : methods) {
AnnotatedMethod annotatedMethod = bd.findMethod(method.getName(), method.getParameterTypes());
if (ReflectionUtils.isOverriddenMethod(method, cls)) {
continue;
}
javax.ws.rs.Path methodPath = ReflectionUtils.getAnnotation(method, javax.ws.rs.Path.class);
String operationPath = getPath(apiPath, methodPath, parentPath);
Map<String, String> regexMap = new LinkedHashMap<String, String>();
operationPath = PathUtils.parsePath(operationPath, regexMap);
if (operationPath != null) {
if (isIgnored(operationPath)) {
continue;
}
final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
String httpMethod = extractOperationMethod(apiOperation, method, SwaggerExtensions.chain());
Operation operation = null;
if (apiOperation != null || config.isScanAllResources() || httpMethod != null || methodPath != null) {
operation = parseMethod(cls, method, annotatedMethod, globalParameters, classApiResponses);
}
if (operation == null) {
continue;
}
if (parentParameters != null) {
for (Parameter param : parentParameters) {
operation.parameter(param);
}
}
for (Parameter param : operation.getParameters()) {
if (regexMap.get(param.getName()) != null) {
String pattern = regexMap.get(param.getName());
param.setPattern(pattern);
}
}
if (apiOperation != null) {
for (Scheme scheme : parseSchemes(apiOperation.protocols())) {
operation.scheme(scheme);
}
}
if (operation.getSchemes() == null || operation.getSchemes().isEmpty()) {
for (Scheme scheme : globalSchemes) {
operation.scheme(scheme);
}
}
String[] apiConsumes = consumes;
if (parentConsumes != null) {
Set<String> both = new LinkedHashSet<String>(Arrays.asList(apiConsumes));
both.addAll(new LinkedHashSet<String>(Arrays.asList(parentConsumes)));
if (operation.getConsumes() != null) {
both.addAll(new LinkedHashSet<String>(operation.getConsumes()));
}
apiConsumes = both.toArray(new String[both.size()]);
}
String[] apiProduces = produces;
if (parentProduces != null) {
Set<String> both = new LinkedHashSet<String>(Arrays.asList(apiProduces));
both.addAll(new LinkedHashSet<String>(Arrays.asList(parentProduces)));
if (operation.getProduces() != null) {
both.addAll(new LinkedHashSet<String>(operation.getProduces()));
}
apiProduces = both.toArray(new String[both.size()]);
}
final Class<?> subResource = getSubResourceWithJaxRsSubresourceLocatorSpecs(method);
if (subResource != null && !scannedResources.contains(subResource)) {
scannedResources.add(subResource);
read(subResource, operationPath, httpMethod, true, apiConsumes, apiProduces, tags, operation.getParameters(), scannedResources);
// remove the sub resource so that it can visit it later in another path
// but we have a room for optimization in the future to reuse the scanned result
// by caching the scanned resources in the reader instance to avoid actual scanning
// the the resources again
scannedResources.remove(subResource);
}
// can't continue without a valid http method
httpMethod = (httpMethod == null) ? parentMethod : httpMethod;
if (httpMethod != null) {
if (apiOperation != null) {
for (String tag : apiOperation.tags()) {
if (!"".equals(tag)) {
operation.tag(tag);
swagger.tag(new Tag().name(tag));
}
}
operation.getVendorExtensions().putAll(BaseReaderUtils.parseExtensions(apiOperation.extensions()));
}
if (operation.getConsumes() == null) {
for (String mediaType : apiConsumes) {
operation.consumes(mediaType);
}
}
if (operation.getProduces() == null) {
for (String mediaType : apiProduces) {
operation.produces(mediaType);
}
}
if (operation.getTags() == null) {
for (String tagString : tags.keySet()) {
operation.tag(tagString);
}
}
// Only add global @Api securities if operation doesn't already have more specific securities
if (operation.getSecurity() == null) {
for (SecurityRequirement security : securities) {
operation.security(security);
}
}
Path path = swagger.getPath(operationPath);
if (path == null) {
path = new Path();
swagger.path(operationPath, path);
}
path.set(httpMethod, operation);
readImplicitParameters(method, operation);
readExternalDocs(method, operation);
}
}
}
}
return swagger;
}
use of io.swagger.annotations.Authorization in project nifi by apache.
the class SnippetResource method deleteSnippet.
/**
* Removes the specified snippet.
*
* @param httpServletRequest request
* @param snippetId The id of the snippet to remove.
* @return A entity containing the client id and an updated revision.
*/
@DELETE
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(value = "Deletes the components in a snippet and discards the snippet", response = SnippetEntity.class, authorizations = { @Authorization(value = "Write - /{component-type}/{uuid} - For each component in the Snippet and their descendant components"), @Authorization(value = "Write - Parent Process Group - /process-groups/{uuid}") })
@ApiResponses(value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") })
public Response deleteSnippet(@Context final HttpServletRequest httpServletRequest, @ApiParam(value = "The snippet id.", required = true) @PathParam("id") final String snippetId) {
if (isReplicateRequest()) {
return replicate(HttpMethod.DELETE);
}
final ComponentEntity requestEntity = new ComponentEntity();
requestEntity.setId(snippetId);
// get the revision from this snippet
final Set<Revision> requestRevisions = serviceFacade.getRevisionsFromSnippet(snippetId);
return withWriteLock(serviceFacade, requestEntity, requestRevisions, lookup -> {
// ensure write permission to every component in the snippet excluding referenced services
final SnippetAuthorizable snippet = lookup.getSnippet(snippetId);
authorizeSnippet(snippet, authorizer, lookup, RequestAction.WRITE, true, false);
// ensure write permission to the parent process group
snippet.getParentProcessGroup().authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
}, () -> serviceFacade.verifyDeleteSnippet(snippetId, requestRevisions.stream().map(rev -> rev.getComponentId()).collect(Collectors.toSet())), (revisions, entity) -> {
// delete the specified snippet
final SnippetEntity snippetEntity = serviceFacade.deleteSnippet(revisions, entity.getId());
return generateOkResponse(snippetEntity).build();
});
}
Aggregations