javax.annotation.security.RolesAllowed Java Examples

The following examples show how to use javax.annotation.security.RolesAllowed. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JsonValuejectionEndpoint.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/verifyInjectedCustomString")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("Tester")
public JsonObject verifyInjectedCustomString(@QueryParam("value") String value) {
    boolean pass = false;
    String msg;
    // iat
    String customValue = customString.getString();
    if(customValue == null || customValue.length() == 0) {
        msg = "customString value is null or empty, FAIL";
    }
    else if(customValue.equals(value)) {
        msg = "customString PASS";
        pass = true;
    }
    else {
        msg = String.format("customString: %s != %s", customValue, value);
    }
    JsonObject result = Json.createObjectBuilder()
        .add("pass", pass)
        .add("msg", msg)
        .build();
    return result;
}
 
Example #2
Source File: AdminResource.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/disableDPM")
@ApiOperation(
    value = "Disables DPM",
    authorizations = @Authorization(value = "basic")
)
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({AuthzRole.ADMIN, AuthzRole.ADMIN_REMOTE})
public Response disableDPM(@Context HttpServletRequest request) throws IOException {
  // check if DPM enabled
  if (!runtimeInfo.isDPMEnabled()) {
    throw new RuntimeException("disableDPM is supported only when DPM is enabled");
  }

   // 1. Get DPM user auth token from request cookie
  SSOPrincipal ssoPrincipal = (SSOPrincipal)request.getUserPrincipal();
  String userAuthToken = ssoPrincipal.getTokenStr();
  String organizationId = ssoPrincipal.getOrganizationId();

  SchAdmin.disableDPM(userAuthToken, organizationId, new SchAdmin.Context(runtimeInfo, config));

  return Response.ok().build();
}
 
Example #3
Source File: SystemManagerImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Override
@RolesAllowed( "System-Management|Update" )
public void setNetworkSettings( final String publicUrl, final String publicSecurePort, final boolean useRhIp )
        throws ConfigurationException
{
    try
    {
        peerManager
                .setPublicUrl( peerManager.getLocalPeer().getId(), publicUrl, Integer.parseInt( publicSecurePort ),
                        useRhIp );
    }
    catch ( Exception e )
    {
        throw new ConfigurationException( e );
    }
}
 
Example #4
Source File: PipelineStoreResource.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Path("/detachedstage")
@POST
@ApiOperation(value = "Validates given detached stage and performs any necessary upgrade.",
  response = DetachedStageConfigurationJson.class,
  authorizations = @Authorization(value = "basic")
)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({
    AuthzRole.CREATOR, AuthzRole.ADMIN, AuthzRole.CREATOR_REMOTE, AuthzRole.ADMIN_REMOTE
})
public Response validateDetachedStage(
    @ApiParam(name="stage", required = true) DetachedStageConfigurationJson detachedStage
) {
  DetachedStageConfiguration stageConf = detachedStage.getDetachedStageConfiguration();
  DetachedStageValidator validator = new DetachedStageValidator(stageLibrary, stageConf);
  return Response.ok().entity(new DetachedStageConfigurationJson(validator.validate())).build();
}
 
Example #5
Source File: OntologyRest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Returns annotation property IRIs in the ontology identified by the provided IDs.
 *
 * @param context     the context of the request.
 * @param recordIdStr the String representing the record Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:".
 * @param branchIdStr the String representing the Branch Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the
 *                    master Branch.
 * @param commitIdStr the String representing the Commit Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the head
 *                    Commit. The provided commitId must be on the Branch identified by the provided branchId;
 *                    otherwise, nothing will be returned.
 * @return annotation properties in the ontology identified by the provided IDs.
 */
@GET
@Path("{recordId}/annotations")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Gets the annotations in the identified ontology.")
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response getAnnotationsInOntology(@Context ContainerRequestContext context,
                                         @PathParam("recordId") String recordIdStr,
                                         @QueryParam("branchId") String branchIdStr,
                                         @QueryParam("commitId") String commitIdStr) {
    try {
        ObjectNode result = doWithOntology(context, recordIdStr, branchIdStr, commitIdStr,
                this::getAnnotationIRIObject, true);
        return Response.ok(result.toString()).build();
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example #6
Source File: AccountServiceBean.java    From development with Apache License 2.0 6 votes vote down vote up
@Override
@RolesAllowed({ "SERVICE_MANAGER", "RESELLER_MANAGER", "BROKER_MANAGER" })
public List<VOOrganization> getMyCustomersOptimization() {
    List<VOOrganization> result = new ArrayList<>();

    PlatformUser user = dm.getCurrentUser();
    Organization seller = user.getOrganization();

    List<Organization> list = getCustomersOptimization(seller);

    for (Organization customer : list) {
        result.add(OrganizationAssembler.toVOOrganization(customer, false,
                null, PerformanceHint.ONLY_FIELDS_FOR_LISTINGS));
    }

    return result;
}
 
Example #7
Source File: SecurityInvocationHandler.java    From development with Apache License 2.0 6 votes vote down vote up
SecurityInvocationHandler(SessionContext sessionContext, Method beanMethod) {
    this.sessionContext = sessionContext;
    RolesAllowed rolesAllowed = beanMethod
            .getAnnotation(RolesAllowed.class);

    // a somewhat nasty scenario: a bean is spied using Mockito, so the
    // roles allowed annotations have to be retrieved from the superclass...
    Class<?> declaringClass = beanMethod.getDeclaringClass();
    Class<?> superclass = declaringClass.getSuperclass();
    if (declaringClass.getName().contains("Mockito")
            && !superclass.equals(Object.class)) {
        try {
            Method method = superclass.getMethod(beanMethod.getName(),
                    beanMethod.getParameterTypes());
            rolesAllowed = method.getAnnotation(RolesAllowed.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    if (rolesAllowed == null) {
        this.rolesAllowed = new String[0];
    } else {
        this.rolesAllowed = rolesAllowed.value();
    }
}
 
Example #8
Source File: DocumentManagerBean.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID)
@Override
public DocumentRevision[] getDocumentRevisionsWithOpenedTasksForGivenUser(String pWorkspaceId, String assignedUserLogin)
        throws WorkspaceNotFoundException, UserNotFoundException, UserNotActiveException, WorkspaceNotEnabledException {
    User user = userManager.checkWorkspaceReadAccess(pWorkspaceId);
    List<DocumentRevision> docRs = documentRevisionDAO.findDocsWithOpenedTasksForGivenUser(pWorkspaceId, assignedUserLogin);

    ListIterator<DocumentRevision> ite = docRs.listIterator();
    while (ite.hasNext()) {
        DocumentRevision docR = ite.next();
        if (!hasDocumentRevisionReadAccess(user, docR)) {
            ite.remove();
        } else if (isCheckoutByAnotherUser(user, docR)) {
            em.detach(docR);
            docR.removeLastIteration();
        }
    }

    return docRs.toArray(new DocumentRevision[docRs.size()]);
}
 
Example #9
Source File: ManagerResource.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Path("/pipeline/{pipelineId}/committedOffsets")
@GET
@ApiOperation(value = "Return Committed Offsets. Note: Returned offset format will change between releases.",
    response = SourceOffsetJson.class,
    authorizations = @Authorization(value = "basic"))
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({
    AuthzRole.MANAGER,
    AuthzRole.ADMIN,
    AuthzRole.MANAGER_REMOTE,
    AuthzRole.ADMIN_REMOTE
})
public Response getCommittedOffsets(
    @PathParam("pipelineId") String pipelineId,
    @QueryParam("rev") @DefaultValue("0") String rev
) throws PipelineException {
  PipelineInfo pipelineInfo = store.getInfo(pipelineId);
  RestAPIUtils.injectPipelineInMDC(pipelineInfo.getTitle(), pipelineInfo.getPipelineId());
  Runner runner = manager.getRunner(pipelineId, rev);
  return Response.ok()
      .type(MediaType.APPLICATION_JSON)
      .entity(BeanHelper.wrapSourceOffset(runner.getCommittedOffsets()))
      .build();
}
 
Example #10
Source File: IdentityManagerImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@RolesAllowed( { "Identity-Management|Write", "Identity-Management|Update" } )
@Override
public UserDelegate createUserDelegate( User user, String delegateUserId, boolean genKeyPair )
{
    String id = "";

    if ( StringUtils.isBlank( delegateUserId ) )
    {
        id = user.getId() + "-" + UUID.randomUUID();
    }

    UserDelegate userDelegate = new UserDelegateEntity();
    userDelegate.setId( id );
    userDelegate.setUserId( user.getId() );
    identityDataService.persistUserDelegate( userDelegate );


    if ( genKeyPair )
    {
        generateKeyPair( id, SecurityKeyType.USER_KEY.getId() );
    }

    return userDelegate;
}
 
Example #11
Source File: ChangeManagerBean.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID)
@Override
public ChangeOrder updateChangeOrder(int pId, String pWorkspaceId, String description, int milestoneId, ChangeItemPriority priority, String assignee, ChangeItemCategory category) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeOrderNotFoundException, AccessRightException, WorkspaceNotEnabledException, AccountNotFoundException, NotAllowedException {
    User user = userManager.checkWorkspaceReadAccess(pWorkspaceId);
    ChangeOrder changeOrder = loadChangeOrder(pId);
    checkChangeItemWriteAccess(changeOrder, user);
    changeOrder.setDescription(description);
    changeOrder.setPriority(priority);
    changeOrder.setCategory(category);

    if (assignee != null && !assignee.isEmpty()) {
        if (!userManager.isUserEnabled(assignee, pWorkspaceId)) {
            throw new NotAllowedException("NotAllowedException71");
        }
        changeOrder.setAssignee(em.find(User.class, new UserKey(pWorkspaceId, assignee)));
    } else {
        changeOrder.setAssignee(null);
    }

    changeOrder.setMilestone(em.find(Milestone.class, milestoneId));
    return changeOrder;
}
 
Example #12
Source File: OntologyRest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Returns datatype IRIs in the imports closure for the ontology identified by the provided IDs.
 *
 * @param context     the context of the request.
 * @param recordIdStr the String representing the record Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:".
 * @param branchIdStr the String representing the Branch Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the
 *                    master Branch.
 * @param commitIdStr the String representing the Commit Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the head
 *                    Commit. The provided commitId must be on the Branch identified by the provided branchId;
 *                    otherwise, nothing will be returned.
 * @return datatypes in the ontology identified by the provided IDs.
 */
@GET
@Path("{recordId}/imported-datatypes")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Gets the datatypes from the imported ontologies of the identified ontology.")
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response getDatatypesInImportedOntologies(@Context ContainerRequestContext context,
                                                 @PathParam("recordId") String recordIdStr,
                                                 @QueryParam("branchId") String branchIdStr,
                                                 @QueryParam("commitId") String commitIdStr) {
    try {
        return doWithImportedOntologies(context, recordIdStr, branchIdStr, commitIdStr, this::getDatatypeIRIObject);
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example #13
Source File: OntologyRest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Returns the SKOS concept hierarchy for the ontology identified by the provided IDs as a JSON object with keys for
 * a map of parent concept IRIs to arrays of children concept IRIs and a map of child concept IRIs to arrays of
 * parent concept IRIs. Optionally can also have a key for a nested JSON-LD representation of the hierarchy.
 *
 * @param context     the context of the request.
 * @param recordIdStr the String representing the record Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:".
 * @param branchIdStr the String representing the Branch Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the
 *                    master Branch.
 * @param commitIdStr the String representing the Commit Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the head
 *                    Commit. The provided commitId must be on the Branch identified by the provided branchId;
 *                    otherwise, nothing will be returned.
 * @param nested      Whether to return the nested JSON-LD version of the hierarchy.
 * @return A JSON object that represents the SKOS concept hierarchy for the ontology identified by the provided IDs.
 */
@GET
@Path("{recordId}/concept-hierarchies")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Gets the concept hierarchies for the identified ontology.")
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response getConceptHierarchy(@Context ContainerRequestContext context,
                                    @PathParam("recordId") String recordIdStr,
                                    @QueryParam("branchId") String branchIdStr,
                                    @QueryParam("commitId") String commitIdStr,
                                    @DefaultValue("false") @QueryParam("nested") boolean nested) {
    try {
        Ontology ontology = getOntology(context, recordIdStr, branchIdStr, commitIdStr, true).orElseThrow(() ->
                ErrorUtils.sendError("The ontology could not be found.", Response.Status.BAD_REQUEST));
        Hierarchy hierarchy = ontology.getConceptRelationships(valueFactory, modelFactory);
        return Response.ok(getHierarchyStream(hierarchy, nested, getConceptIRIs(ontology))).build();
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example #14
Source File: UserGroupServiceBean.java    From development with Apache License 2.0 6 votes vote down vote up
@Override
@RolesAllowed({ "ORGANIZATION_ADMIN", "UNIT_ADMINISTRATOR" })
public boolean handleRemovingCurrentUserFromGroup() {
    if (!userGroupService.handleRemovingCurrentUserFromGroup()) {
        return false;
    }
    PlatformUser currentUser = dm.getCurrentUser();
    if (currentUser.hasSubscriptionOwnerRole()) {
        return true;
    }
    List<Subscription> subscriptions = slsl
            .getSubscriptionsForOwner(currentUser);
    for (Subscription subscription : subscriptions) {
        ssl.removeSubscriptionOwner(subscription);
    }
    return true;

}
 
Example #15
Source File: UserResource.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@RolesAllowed({"admin", "user"})
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Deprecated
public UserUI updateUser(UserForm userForm, @PathParam("userName") UserName userName)
  throws IOException, IllegalArgumentException, NamespaceException, UserNotFoundException, DACUnauthorizedException {
  checkUser(userName, "update");

  User userConfig = userForm.getUserConfig();
  if (userConfig != null && userConfig.getUserName() != null && !userConfig.getUserName().equals(userName.getName())) {
    final UserName newUserName = new UserName(userForm.getUserConfig().getUserName());
    userConfig = userService.updateUserName(userName.getName(),
      newUserName.getName(),
      userConfig, userForm.getPassword());
    // TODO: rename home space and all uploaded files along with it
    // new username
    return new UserUI(new UserResourcePath(newUserName), newUserName, userConfig);
  } else {
    User newUser = SimpleUser.newBuilder(userForm.getUserConfig()).setUserName(userName.getName()).build();
    newUser = userService.updateUser(newUser, userForm.getPassword());
    return new UserUI(new UserResourcePath(userName), userName, newUser);
  }
}
 
Example #16
Source File: VertexAPI.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@DELETE
@Timed
@Path("{id}")
@Consumes(APPLICATION_JSON)
@RolesAllowed({"admin", "$owner=$graph $action=vertex_delete"})
public void delete(@Context GraphManager manager,
                   @PathParam("graph") String graph,
                   @PathParam("id") String idValue) {
    LOG.debug("Graph [{}] remove vertex by id '{}'", graph, idValue);

    Id id = checkAndParseVertexId(idValue);
    HugeGraph g = graph(manager, graph);
    // TODO: add removeVertex(id) to improve
    commit(g, () -> {
        Iterator<Vertex> iter = g.vertices(id);
        try {
            E.checkArgument(iter.hasNext(),
                            "No such vertex with id: '%s'", idValue);
            iter.next().remove();
        } finally {
            CloseableIterator.closeIterator(iter);
        }
    });
}
 
Example #17
Source File: AuthDynamicFeature.java    From dropwizard-java8 with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    final AnnotatedMethod am = new AnnotatedMethod(resourceInfo.getResourceMethod());
    final Annotation[][] parameterAnnotations = am.getParameterAnnotations();
    if (am.isAnnotationPresent(RolesAllowed.class) || am.isAnnotationPresent(DenyAll.class) ||
        am.isAnnotationPresent(PermitAll.class)) {
        context.register(authFilter);
    } else {
        for (Annotation[] annotations : parameterAnnotations) {
            for (Annotation annotation : annotations) {
                if (annotation instanceof Auth) {
                    context.register(authFilter);
                    return;
                }
            }
        }
    }
}
 
Example #18
Source File: DirectoryAdminWebController.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
@RolesAllowed("CREATE")
@POST
public DirectoryAJAXResponse create(CreateDirectoryAJAXRequest createDirectoryAJAXRequest) {
    DirectoryResponse parentDirectory = directoryService.get(createDirectoryAJAXRequest.parentId);
    CreateDirectoryRequest instance = new CreateDirectoryRequest();
    instance.path = parentDirectory.path.substring(0, parentDirectory.path.length() - 1) + createDirectoryAJAXRequest.path;
    instance.parentId = createDirectoryAJAXRequest.parentId;
    instance.description = createDirectoryAJAXRequest.description;
    instance.ownerId = createDirectoryAJAXRequest.ownerId;
    instance.ownerRoles = createDirectoryAJAXRequest.ownerRoles;
    instance.groupId = createDirectoryAJAXRequest.groupId;
    instance.groupRoles = createDirectoryAJAXRequest.groupRoles;
    instance.othersRoles = createDirectoryAJAXRequest.othersRoles;
    instance.requestBy = userInfo.username();
    return response(directoryService.create(instance));
}
 
Example #19
Source File: OperatorServiceLocalBean.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Load properties for platform objects names
 * 
 * @param languageCode
 *            - which language's platform objects names need to be loaded
 * @return - properties map: key is the language code, value is properties
 *         object
 * @throws ObjectNotFoundException
 */
@RolesAllowed({ "PLATFORM_OPERATOR" })
public Map<String, Properties> loadPlatformObjects(String languageCode)
        throws ObjectNotFoundException {
    Map<String, Properties> propertiesMap = loadStandardLanguageProperties(PROPERTY_TYPE_PLATFORMOBJECT);
    if (languageCode != null && !propertiesMap.containsKey(languageCode)) {
        Properties props = loadPlatformObjectsFromDB(languageCode);
        propertiesMap.put(languageCode, props);
    }
    return propertiesMap;
}
 
Example #20
Source File: MetricsAPI.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
@GET
@Timed
@Path("counters")
@Produces(APPLICATION_JSON_WITH_CHARSET)
@RolesAllowed("admin")
public String counters() {
    ServerReporter reporter = ServerReporter.instance();
    return JsonUtil.toJson(reporter.counters());
}
 
Example #21
Source File: OrganizationManagerBean.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
@RolesAllowed({UserGroupMapping.REGULAR_USER_ROLE_ID, UserGroupMapping.ADMIN_ROLE_ID})
@Override
public void addAccountInOrganization(String pOrganizationName, String pLogin) throws OrganizationNotFoundException, AccountNotFoundException, NotAllowedException, AccessRightException {
    Organization organization = organizationDAO.loadOrganization(pOrganizationName);
    accountManager.checkAdmin(organization);

    Account accountToAdd = accountDAO.loadAccount(pLogin);
    Organization accountToAddOrg = organizationDAO.findOrganizationOfAccount(accountToAdd);
    if (accountToAddOrg != null) {
        throw new NotAllowedException("NotAllowedException12");
    } else {
        organization.addMember(accountToAdd);
    }
}
 
Example #22
Source File: Users.java    From jeeshop with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/count")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({ADMIN, ADMIN_READONLY})
public Long count(@QueryParam("search") String search) {
    if (search != null)
        return userFinder.countBySearchCriteria(search);
    else
        return userFinder.countAll();
}
 
Example #23
Source File: DocumentWorkflowManagerBean.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
@RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID)
@Override
public Workflow[] getAbortedWorkflow(DocumentRevisionKey documentRevisionKey) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, DocumentRevisionNotFoundException, AccessRightException, WorkspaceNotEnabledException {
    User user = userManager.checkWorkspaceReadAccess(documentRevisionKey.getDocumentMaster().getWorkspace());
    if (!documentManager.canUserAccess(user, documentRevisionKey)) {
        throw new AccessRightException(user);
    }

    DocumentRevision docR = documentRevisionDAO.loadDocR(documentRevisionKey);
    List<Workflow> abortedWorkflowList = docR.getAbortedWorkflows();
    return abortedWorkflowList.toArray(new Workflow[abortedWorkflowList.size()]);
}
 
Example #24
Source File: FactEndpoint.java    From act-platform with ISC License 5 votes vote down vote up
@POST
@Path("/uuid/{fact}/access/{subject}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Grant a Subject access to a Fact.",
        notes = "This operation grants a Subject explicit access to a non-public Fact. The request will be rejected " +
                "with a 403 if a user does not have access to the Fact or is not allowed to grant further access.",
        response = AclEntry.class,
        code = 201
)
@ApiResponses({
        @ApiResponse(code = 401, message = "User could not be authenticated."),
        @ApiResponse(code = 403, message = "User is not allowed to perform this operation."),
        @ApiResponse(code = 404, message = "Fact does not exist."),
        @ApiResponse(code = 412, message = "Any parameter has an invalid format.")
})
@RolesAllowed("grantThreatIntelFactAccess")
public Response grantFactAccess(
        @PathParam("fact") @ApiParam(value = "UUID of Fact.") @NotNull @Valid UUID fact,
        @PathParam("subject") @ApiParam(value = "UUID or name of Subject.") @NotBlank String subject,
        @ApiParam(hidden = true) @Valid GrantFactAccessRequest request
) throws AccessDeniedException, AuthenticationFailedException, InvalidArgumentException, ObjectNotFoundException {
  // Swagger won't send a request object because it's hidden from the API, thus, make sure that it's initialized.
  request = ObjectUtils.ifNull(request, new GrantFactAccessRequest());

  return ResultStash.builder()
          .setStatus(Response.Status.CREATED)
          .setData(service.grantFactAccess(credentialsResolver.getRequestHeader(), request.setFact(fact).setSubject(subject)))
          .buildResponse();
}
 
Example #25
Source File: RolesEndpoint.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
/**
 * This endpoint requires a Tester role, and also validates that the caller has the role Echoer by calling
 * {@linkplain SecurityContext#isUserInRole(String)}.
 *
 * @return principal name or FORBIDDEN error
 */
@GET
@Path("/checkIsUserInRole")
@RolesAllowed("Tester")
public Response checkIsUserInRole(@Context SecurityContext sec) {
    Principal user = sec.getUserPrincipal();
    Response response;
    if(!sec.isUserInRole("Echoer")) {
        response = Response.status(new Response.StatusType() {
            @Override
            public int getStatusCode() {
                return Response.Status.FORBIDDEN.getStatusCode();
            }

            @Override
            public Response.Status.Family getFamily() {
                return Response.Status.FORBIDDEN.getFamily();
            }

            @Override
            public String getReasonPhrase() {
                return "SecurityContext.isUserInRole(Echoer) was false";
            }
        }).build();
    }
    else {
        response = Response.ok(user.getName(), MediaType.TEXT_PLAIN).build();
    }
    return response;
}
 
Example #26
Source File: UserManagerBean.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
@RolesAllowed({UserGroupMapping.REGULAR_USER_ROLE_ID, UserGroupMapping.ADMIN_ROLE_ID})
@Override
public UserGroup[] getUserGroups(String pWorkspaceId) throws WorkspaceNotFoundException, UserNotFoundException, UserNotActiveException, AccountNotFoundException, WorkspaceNotEnabledException {
    if (contextManager.isCallerInRole(UserGroupMapping.ADMIN_ROLE_ID)) {
        accountDAO.loadAccount(contextManager.getCallerPrincipalLogin());
        return userGroupDAO.findAllUserGroups(pWorkspaceId);
    } else {
        checkWorkspaceReadAccess(pWorkspaceId);
        return userGroupDAO.findAllUserGroups(pWorkspaceId);
    }
}
 
Example #27
Source File: DocumentManagerBean.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
@RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID)
@Override
public DocumentRevision[] getCheckedOutDocumentRevisions(String pWorkspaceId) throws WorkspaceNotFoundException, UserNotFoundException, UserNotActiveException, WorkspaceNotEnabledException {
    User user = userManager.checkWorkspaceReadAccess(pWorkspaceId);
    List<DocumentRevision> docRs = documentRevisionDAO.findCheckedOutDocRs(user);
    return docRs.toArray(new DocumentRevision[docRs.size()]);
}
 
Example #28
Source File: EdgeAPI.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
@PUT
@Timed(name = "single-update")
@Path("{id}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON_WITH_CHARSET)
@RolesAllowed({"admin", "$owner=$graph $action=edge_write"})
public String update(@Context GraphManager manager,
                     @PathParam("graph") String graph,
                     @PathParam("id") String id,
                     @QueryParam("action") String action,
                     JsonEdge jsonEdge) {
    LOG.debug("Graph [{}] update edge: {}", graph, jsonEdge);
    checkUpdatingBody(jsonEdge);

    if (jsonEdge.id != null) {
        E.checkArgument(id.equals(jsonEdge.id),
                        "The ids are different between url('%s') and " +
                        "request body('%s')", id, jsonEdge.id);
    }

    // Parse action param
    boolean append = checkAndParseAction(action);

    HugeGraph g = graph(manager, graph);
    HugeEdge edge = (HugeEdge) g.edges(id).next();
    EdgeLabel edgeLabel = edge.schemaLabel();

    for (String key : jsonEdge.properties.keySet()) {
        PropertyKey pkey = g.propertyKey(key);
        E.checkArgument(edgeLabel.properties().contains(pkey.id()),
                        "Can't update property for edge '%s' because " +
                        "there is no property key '%s' in its edge label",
                        id, key);
    }

    commit(g, () -> updateProperties(edge, jsonEdge, append));

    return manager.serializer(g).writeEdge(edge);
}
 
Example #29
Source File: UserServiceBean.java    From development with Apache License 2.0 5 votes vote down vote up
@Override
@RolesAllowed("ORGANIZATION_ADMIN")
public Response importUsersInOwnOrganization(byte[] users,
        String marketplaceId) throws SaaSApplicationException {
    isr.importUsersInOwnOrganization(users, marketplaceId);
    return new Response();
}
 
Example #30
Source File: GenericSettingProvider.java    From pnc with Apache License 2.0 5 votes vote down vote up
@RolesAllowed("system-user")
public void setAnnouncementBanner(String banner) {

    log.info("Announcement banner set to: '{}'", banner);
    GenericSetting announcementBanner = createGenericParameterIfNotFound(ANNOUNCEMENT_BANNER);
    announcementBanner.setValue(banner);
    genericSettingRepository.save(announcementBanner);
    notifier.sendMessage(GenericSettingNotification.newAnnoucement(banner));
}