Search in sources :

Example 6 with Authorization

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);
}
Also used : PagedResourcesAssembler(org.springframework.data.web.PagedResourcesAssembler) PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) DependentTaskTrigger(eu.bcvsolutions.idm.core.scheduler.api.dto.DependentTaskTrigger) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) SimpleTaskTrigger(eu.bcvsolutions.idm.core.scheduler.api.dto.SimpleTaskTrigger) Autowired(org.springframework.beans.factory.annotation.Autowired) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ApiParam(io.swagger.annotations.ApiParam) StringUtils(org.apache.commons.lang3.StringUtils) Valid(javax.validation.Valid) RequestBody(org.springframework.web.bind.annotation.RequestBody) CoreGroupPermission(eu.bcvsolutions.idm.core.model.domain.CoreGroupPermission) ApiOperation(io.swagger.annotations.ApiOperation) DataFilter(eu.bcvsolutions.idm.core.api.dto.filter.DataFilter) LookupService(eu.bcvsolutions.idm.core.api.service.LookupService) SwaggerConfig(eu.bcvsolutions.idm.core.api.config.swagger.SwaggerConfig) Pageable(org.springframework.data.domain.Pageable) Sort(org.springframework.data.domain.Sort) AuthorizationScope(io.swagger.annotations.AuthorizationScope) Task(eu.bcvsolutions.idm.core.scheduler.api.dto.Task) Api(io.swagger.annotations.Api) ConditionalOnProperty(org.springframework.boot.autoconfigure.condition.ConditionalOnProperty) ApiImplicitParam(io.swagger.annotations.ApiImplicitParam) MultiValueMap(org.springframework.util.MultiValueMap) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) SchedulerManager(eu.bcvsolutions.idm.core.scheduler.api.service.SchedulerManager) Page(org.springframework.data.domain.Page) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) ParameterConverter(eu.bcvsolutions.idm.core.api.utils.ParameterConverter) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) BaseController(eu.bcvsolutions.idm.core.api.rest.BaseController) AbstractTaskTrigger(eu.bcvsolutions.idm.core.scheduler.api.dto.AbstractTaskTrigger) CronTaskTrigger(eu.bcvsolutions.idm.core.scheduler.api.dto.CronTaskTrigger) PageableDefault(org.springframework.data.web.PageableDefault) Resources(org.springframework.hateoas.Resources) ResponseEntity(org.springframework.http.ResponseEntity) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) PageImpl(org.springframework.data.domain.PageImpl) Authorization(io.swagger.annotations.Authorization) PageImpl(org.springframework.data.domain.PageImpl) Task(eu.bcvsolutions.idm.core.scheduler.api.dto.Task) Sort(org.springframework.data.domain.Sort) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 7 with Authorization

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;
}
Also used : Userinfoplus(com.google.api.services.oauth2.model.Userinfoplus) WorkbenchConfig(org.pmiops.workbench.config.WorkbenchConfig) ForbiddenException(org.pmiops.workbench.exceptions.ForbiddenException) User(org.pmiops.workbench.db.model.User) HttpResponseException(com.google.api.client.http.HttpResponseException) UserAuthentication(org.pmiops.workbench.auth.UserAuthentication) HandlerMethod(org.springframework.web.method.HandlerMethod) Authorization(io.swagger.annotations.Authorization) ApiOperation(io.swagger.annotations.ApiOperation) ApiException(org.pmiops.workbench.firecloud.ApiException)

Example 8 with Authorization

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);
    }
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) IcRemoteServerException(eu.bcvsolutions.idm.ic.exception.IcRemoteServerException) Autowired(org.springframework.beans.factory.annotation.Autowired) Enabled(eu.bcvsolutions.idm.core.security.api.domain.Enabled) ApiParam(io.swagger.annotations.ApiParam) SysConnectorServerDto(eu.bcvsolutions.idm.acc.dto.SysConnectorServerDto) IcInvalidCredentialException(eu.bcvsolutions.idm.ic.exception.IcInvalidCredentialException) Valid(javax.validation.Valid) ApiOperation(io.swagger.annotations.ApiOperation) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) Map(java.util.Map) SysRemoteServerService(eu.bcvsolutions.idm.acc.service.api.SysRemoteServerService) Pageable(org.springframework.data.domain.Pageable) AuthorizationScope(io.swagger.annotations.AuthorizationScope) IcCantConnectException(eu.bcvsolutions.idm.ic.exception.IcCantConnectException) IcConfigurationFacade(eu.bcvsolutions.idm.ic.service.api.IcConfigurationFacade) EntityNotFoundException(eu.bcvsolutions.idm.core.api.exception.EntityNotFoundException) ImmutableMap(com.google.common.collect.ImmutableMap) MediaType(org.springframework.http.MediaType) Set(java.util.Set) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) List(java.util.List) ConnectorManager(eu.bcvsolutions.idm.acc.service.api.ConnectorManager) IcConnectorInfo(eu.bcvsolutions.idm.ic.api.IcConnectorInfo) SysRemoteServerFilter(eu.bcvsolutions.idm.acc.dto.filter.SysRemoteServerFilter) AccResultCode(eu.bcvsolutions.idm.acc.domain.AccResultCode) ResultModels(eu.bcvsolutions.idm.core.api.dto.ResultModels) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) HashMap(java.util.HashMap) CollectionUtils(org.apache.commons.collections4.CollectionUtils) RequestBody(org.springframework.web.bind.annotation.RequestBody) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) AbstractReadWriteDtoController(eu.bcvsolutions.idm.core.api.rest.AbstractReadWriteDtoController) SwaggerConfig(eu.bcvsolutions.idm.core.api.config.swagger.SwaggerConfig) AccGroupPermission(eu.bcvsolutions.idm.acc.domain.AccGroupPermission) IcConfigurationService(eu.bcvsolutions.idm.ic.service.api.IcConfigurationService) ConnectorTypeDto(eu.bcvsolutions.idm.acc.dto.ConnectorTypeDto) Api(io.swagger.annotations.Api) AccModuleDescriptor(eu.bcvsolutions.idm.acc.AccModuleDescriptor) IcServerNotFoundException(eu.bcvsolutions.idm.ic.exception.IcServerNotFoundException) MultiValueMap(org.springframework.util.MultiValueMap) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) HttpStatus(org.springframework.http.HttpStatus) IdmBulkActionDto(eu.bcvsolutions.idm.core.api.bulk.action.dto.IdmBulkActionDto) BaseController(eu.bcvsolutions.idm.core.api.rest.BaseController) BaseDtoController(eu.bcvsolutions.idm.core.api.rest.BaseDtoController) PageableDefault(org.springframework.data.web.PageableDefault) Resources(org.springframework.hateoas.Resources) ResponseEntity(org.springframework.http.ResponseEntity) Comparator(java.util.Comparator) Authorization(io.swagger.annotations.Authorization) IcServerNotFoundException(eu.bcvsolutions.idm.ic.exception.IcServerNotFoundException) IcInvalidCredentialException(eu.bcvsolutions.idm.ic.exception.IcInvalidCredentialException) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) EntityNotFoundException(eu.bcvsolutions.idm.core.api.exception.EntityNotFoundException) ConnectorTypeDto(eu.bcvsolutions.idm.acc.dto.ConnectorTypeDto) IcConnectorInfo(eu.bcvsolutions.idm.ic.api.IcConnectorInfo) IcConfigurationService(eu.bcvsolutions.idm.ic.service.api.IcConfigurationService) IcCantConnectException(eu.bcvsolutions.idm.ic.exception.IcCantConnectException) IcRemoteServerException(eu.bcvsolutions.idm.ic.exception.IcRemoteServerException) Resources(org.springframework.hateoas.Resources) SysConnectorServerDto(eu.bcvsolutions.idm.acc.dto.SysConnectorServerDto) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 9 with Authorization

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;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ModelConverters(io.swagger.converter.ModelConverters) Scheme(io.swagger.models.Scheme) AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) ArrayList(java.util.ArrayList) ApiOperation(io.swagger.annotations.ApiOperation) Operation(io.swagger.models.Operation) ApiResponse(io.swagger.annotations.ApiResponse) LinkedHashMap(java.util.LinkedHashMap) Authorization(io.swagger.annotations.Authorization) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Path(io.swagger.models.Path) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) Method(java.lang.reflect.Method) HttpMethod(javax.ws.rs.HttpMethod) AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) JavaType(com.fasterxml.jackson.databind.JavaType) Produces(javax.ws.rs.Produces) FormParameter(io.swagger.models.parameters.FormParameter) PathParameter(io.swagger.models.parameters.PathParameter) Parameter(io.swagger.models.parameters.Parameter) QueryParameter(io.swagger.models.parameters.QueryParameter) HeaderParameter(io.swagger.models.parameters.HeaderParameter) AnnotatedParameter(com.fasterxml.jackson.databind.introspect.AnnotatedParameter) Tag(io.swagger.models.Tag) Api(io.swagger.annotations.Api) AuthorizationScope(io.swagger.annotations.AuthorizationScope) SecurityRequirement(io.swagger.models.SecurityRequirement)

Example 10 with Authorization

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();
    });
}
Also used : PathParam(javax.ws.rs.PathParam) Revision(org.apache.nifi.web.Revision) Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) ApiParam(io.swagger.annotations.ApiParam) AccessDeniedException(org.apache.nifi.authorization.AccessDeniedException) ApiResponses(io.swagger.annotations.ApiResponses) HttpMethod(javax.ws.rs.HttpMethod) ApiOperation(io.swagger.annotations.ApiOperation) SnippetEntity(org.apache.nifi.web.api.entity.SnippetEntity) HttpServletRequest(javax.servlet.http.HttpServletRequest) MediaType(javax.ws.rs.core.MediaType) Consumes(javax.ws.rs.Consumes) Api(io.swagger.annotations.Api) URI(java.net.URI) DELETE(javax.ws.rs.DELETE) NiFiServiceFacade(org.apache.nifi.web.NiFiServiceFacade) POST(javax.ws.rs.POST) Context(javax.ws.rs.core.Context) Authorizable(org.apache.nifi.authorization.resource.Authorizable) AuthorizableLookup(org.apache.nifi.authorization.AuthorizableLookup) RequestAction(org.apache.nifi.authorization.RequestAction) Set(java.util.Set) SnippetAuthorizable(org.apache.nifi.authorization.SnippetAuthorizable) Collectors(java.util.stream.Collectors) Consumer(java.util.function.Consumer) ComponentEntity(org.apache.nifi.web.api.entity.ComponentEntity) Authorizer(org.apache.nifi.authorization.Authorizer) Response(javax.ws.rs.core.Response) ApiResponse(io.swagger.annotations.ApiResponse) NiFiUserUtils(org.apache.nifi.authorization.user.NiFiUserUtils) PUT(javax.ws.rs.PUT) SnippetDTO(org.apache.nifi.web.api.dto.SnippetDTO) Authorization(io.swagger.annotations.Authorization) Revision(org.apache.nifi.web.Revision) SnippetAuthorizable(org.apache.nifi.authorization.SnippetAuthorizable) ComponentEntity(org.apache.nifi.web.api.entity.ComponentEntity) SnippetEntity(org.apache.nifi.web.api.entity.SnippetEntity) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

Authorization (io.swagger.annotations.Authorization)18 ApiOperation (io.swagger.annotations.ApiOperation)16 Api (io.swagger.annotations.Api)14 ApiParam (io.swagger.annotations.ApiParam)13 Collectors (java.util.stream.Collectors)13 ApiResponse (io.swagger.annotations.ApiResponse)12 ApiResponses (io.swagger.annotations.ApiResponses)12 Set (java.util.Set)12 Consumes (javax.ws.rs.Consumes)12 Produces (javax.ws.rs.Produces)12 HttpMethod (javax.ws.rs.HttpMethod)11 Map (java.util.Map)10 HttpServletRequest (javax.servlet.http.HttpServletRequest)10 PUT (javax.ws.rs.PUT)10 Path (javax.ws.rs.Path)10 PathParam (javax.ws.rs.PathParam)10 MediaType (javax.ws.rs.core.MediaType)10 Response (javax.ws.rs.core.Response)10 Authorizer (org.apache.nifi.authorization.Authorizer)10 RequestAction (org.apache.nifi.authorization.RequestAction)10