Search in sources :

Example 81 with SecurityContext

use of org.structr.common.SecurityContext in project structr by structr.

the class User method onCreateAndModify.

// ----- public static methods -----
public static void onCreateAndModify(final User user, final SecurityContext securityContext) throws FrameworkException {
    final PropertyKey skipSecurityRels = StructrApp.key(User.class, "skipSecurityRelationships");
    if (user.getProperty(skipSecurityRels).equals(Boolean.TRUE) && !user.isAdmin()) {
        throw new FrameworkException(422, "", new SemanticErrorToken(user.getClass().getSimpleName(), skipSecurityRels, "can_only_be_set_for_admin_accounts"));
    }
    if (Settings.FilesystemEnabled.getValue()) {
        final PropertyKey<Folder> homeFolderKey = StructrApp.key(Folder.class, "homeFolderOfUser");
        final PropertyKey<Folder> parentKey = StructrApp.key(AbstractFile.class, "parent");
        // use superuser context here
        final SecurityContext storedContext = user.getSecurityContext();
        try {
            user.setSecurityContext(SecurityContext.getSuperUserInstance());
            Folder homeDir = user.getHomeDirectory();
            if (homeDir == null) {
                // create home directory
                final App app = StructrApp.getInstance();
                Folder homeFolder = app.nodeQuery(Folder.class).and(Folder.name, "home").and(parentKey, null).getFirst();
                if (homeFolder == null) {
                    homeFolder = app.create(Folder.class, new NodeAttribute(Folder.name, "home"), new NodeAttribute(Folder.owner, null), new NodeAttribute(Folder.visibleToAuthenticatedUsers, true));
                }
                app.create(Folder.class, new NodeAttribute(Folder.name, user.getUuid()), new NodeAttribute(Folder.owner, user), new NodeAttribute(Folder.visibleToAuthenticatedUsers, true), new NodeAttribute(parentKey, homeFolder), new NodeAttribute(homeFolderKey, user));
            }
        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            // restore previous context
            user.setSecurityContext(storedContext);
        }
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) NodeAttribute(org.structr.core.graph.NodeAttribute) SemanticErrorToken(org.structr.common.error.SemanticErrorToken) FrameworkException(org.structr.common.error.FrameworkException) SecurityContext(org.structr.common.SecurityContext) PropertyKey(org.structr.core.property.PropertyKey)

Example 82 with SecurityContext

use of org.structr.common.SecurityContext in project structr by structr.

the class User method checkAndRemoveHomeDirectory.

public static void checkAndRemoveHomeDirectory(final User user, final SecurityContext securityContext) throws FrameworkException {
    if (Settings.FilesystemEnabled.getValue()) {
        // use superuser context here
        final SecurityContext storedContext = user.getSecurityContext();
        try {
            user.setSecurityContext(SecurityContext.getSuperUserInstance());
            final Folder homeDir = user.getHomeDirectory();
            if (homeDir != null) {
                StructrApp.getInstance().delete(homeDir);
            }
        } catch (Throwable ignore) {
        } finally {
            // restore previous context
            user.setSecurityContext(storedContext);
        }
    }
}
Also used : SecurityContext(org.structr.common.SecurityContext)

Example 83 with SecurityContext

use of org.structr.common.SecurityContext in project structr by structr.

the class IdRequestParameterGraphDataSource method getData.

@Override
public Iterable<GraphObject> getData(final RenderContext renderContext, final DOMNode referenceNode) throws FrameworkException {
    final SecurityContext securityContext = renderContext.getSecurityContext();
    if (securityContext != null && securityContext.getRequest() != null) {
        String nodeId = securityContext.getRequest().getParameter(parameterName);
        if (nodeId != null) {
            AbstractNode node = (AbstractNode) StructrApp.getInstance(securityContext).getNodeById(nodeId);
            if (node != null) {
                List<GraphObject> graphData = new LinkedList<>();
                graphData.add(node);
                return graphData;
            }
        }
    }
    return null;
}
Also used : AbstractNode(org.structr.core.entity.AbstractNode) SecurityContext(org.structr.common.SecurityContext) GraphObject(org.structr.core.GraphObject) LinkedList(java.util.LinkedList)

Example 84 with SecurityContext

use of org.structr.common.SecurityContext in project structr by structr.

the class RestDataSource method getData.

// FIXME: this method is needed by the websocket search command because there is no reference node for the above method
public List<GraphObject> getData(final RenderContext renderContext, final String restQuery) throws FrameworkException {
    final Map<Pattern, Class<? extends Resource>> resourceMap = new LinkedHashMap<>();
    final SecurityContext securityContext = renderContext.getSecurityContext();
    ResourceProvider resourceProvider = renderContext.getResourceProvider();
    if (resourceProvider == null) {
        try {
            resourceProvider = UiResourceProvider.class.newInstance();
        } catch (Throwable t) {
            logger.error("Couldn't establish a resource provider", t);
            return Collections.EMPTY_LIST;
        }
    }
    // inject resources
    resourceMap.putAll(resourceProvider.getResources());
    Value<String> propertyView = new ThreadLocalPropertyView();
    propertyView.set(securityContext, PropertyView.Ui);
    HttpServletRequest request = securityContext.getRequest();
    if (request == null) {
        request = renderContext.getRequest();
    }
    // initialize variables
    // mimic HTTP request
    final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(request) {

        @Override
        public Enumeration<String> getParameterNames() {
            return new IteratorEnumeration(getParameterMap().keySet().iterator());
        }

        @Override
        public String getParameter(final String key) {
            String[] p = getParameterMap().get(key);
            return p != null ? p[0] : null;
        }

        @Override
        public String[] getParameterValues(final String key) {
            return getParameterMap().get(key);
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            String[] parts = StringUtils.split(getQueryString(), "&");
            Map<String, String[]> parameterMap = new HashMap();
            for (String p : parts) {
                String[] kv = StringUtils.split(p, "=");
                if (kv.length > 1) {
                    parameterMap.put(kv[0], new String[] { kv[1] });
                }
            }
            return parameterMap;
        }

        @Override
        public String getQueryString() {
            return StringUtils.substringAfter(restQuery, "?");
        }

        @Override
        public String getPathInfo() {
            return StringUtils.substringBefore(restQuery, "?");
        }

        @Override
        public StringBuffer getRequestURL() {
            return new StringBuffer(restQuery);
        }
    };
    // store original request
    final HttpServletRequest origRequest = securityContext.getRequest();
    // update request in security context
    securityContext.setRequest(wrappedRequest);
    // HttpServletResponse response = renderContext.getResponse();
    Resource resource = null;
    try {
        resource = ResourceHelper.applyViewTransformation(wrappedRequest, securityContext, ResourceHelper.optimizeNestedResourceChain(securityContext, wrappedRequest, resourceMap, propertyView), propertyView);
    } catch (IllegalPathException | NotFoundException e) {
        logger.warn("Illegal path for REST query: {}", restQuery);
    }
    // reset request to old context
    securityContext.setRequest(origRequest);
    if (resource == null) {
        return Collections.EMPTY_LIST;
    }
    // experimental: disable result count, prevents instantiation
    // of large collections just for counting all the objects..
    securityContext.ignoreResultCount(true);
    // TODO: decide if we need to rest the REST request here
    // securityContext.checkResourceAccess(request, resource.getResourceSignature(), resource.getGrant(request, response), PropertyView.Ui);
    // add sorting & paging
    String pageSizeParameter = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_SIZE);
    String pageParameter = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_NUMBER);
    String sortOrder = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_ORDER);
    String sortKeyName = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_KEY);
    boolean sortDescending = (sortOrder != null && "desc".equals(sortOrder.toLowerCase()));
    int pageSize = parseInt(pageSizeParameter, NodeFactory.DEFAULT_PAGE_SIZE);
    int page = parseInt(pageParameter, NodeFactory.DEFAULT_PAGE);
    PropertyKey sortKey = null;
    // set sort key
    if (sortKeyName != null) {
        Class<? extends GraphObject> type = resource.getEntityClass();
        if (type == null) {
            // fallback to default implementation
            // if no type can be determined
            type = AbstractNode.class;
        }
        sortKey = StructrApp.getConfiguration().getPropertyKeyForDatabaseName(type, sortKeyName, false);
    }
    // do action
    Result result = Result.EMPTY_RESULT;
    try {
        result = resource.doGet(sortKey, sortDescending, pageSize, page);
    } catch (NotFoundException nfe) {
        logger.warn("No result from internal REST query: {}", restQuery);
    }
    result.setIsCollection(resource.isCollectionResource());
    result.setIsPrimitiveArray(resource.isPrimitiveArray());
    // Integer rawResultCount = (Integer) Services.getAttribute(NodeFactory.RAW_RESULT_COUNT + Thread.currentThread().getId());
    PagingHelper.addPagingParameter(result, pageSize, page);
    List<GraphObject> res = result.getResults();
    renderContext.setResult(result);
    return res != null ? res : Collections.EMPTY_LIST;
}
Also used : IllegalPathException(org.structr.rest.exception.IllegalPathException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) NotFoundException(org.structr.rest.exception.NotFoundException) GraphObject(org.structr.core.GraphObject) LinkedHashMap(java.util.LinkedHashMap) Result(org.structr.core.Result) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) ResourceProvider(org.structr.rest.ResourceProvider) UiResourceProvider(org.structr.web.common.UiResourceProvider) Pattern(java.util.regex.Pattern) IteratorEnumeration(org.apache.commons.collections.iterators.IteratorEnumeration) Resource(org.structr.rest.resource.Resource) UiResourceProvider(org.structr.web.common.UiResourceProvider) SecurityContext(org.structr.common.SecurityContext) PropertyKey(org.structr.core.property.PropertyKey)

Example 85 with SecurityContext

use of org.structr.common.SecurityContext in project structr by structr.

the class GetRequestHeaderFunction method apply.

@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) {
    try {
        if (!arrayHasLengthAndAllElementsNotNull(sources, 1)) {
            return null;
        }
        final SecurityContext securityContext = ctx.getSecurityContext();
        final String name = sources[0].toString();
        if (securityContext != null) {
            final HttpServletRequest request = securityContext.getRequest();
            if (request != null) {
                return request.getHeader(name);
            }
        }
        return "";
    } catch (final IllegalArgumentException e) {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
        return usage(ctx.isJavaScriptContext());
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) SecurityContext(org.structr.common.SecurityContext)

Aggregations

SecurityContext (org.structr.common.SecurityContext)131 FrameworkException (org.structr.common.error.FrameworkException)76 App (org.structr.core.app.App)56 StructrApp (org.structr.core.app.StructrApp)56 Tx (org.structr.core.graph.Tx)36 GraphObject (org.structr.core.GraphObject)35 PropertyKey (org.structr.core.property.PropertyKey)26 PropertyMap (org.structr.core.property.PropertyMap)26 AbstractNode (org.structr.core.entity.AbstractNode)19 IOException (java.io.IOException)18 Map (java.util.Map)17 File (org.structr.web.entity.File)14 LinkedList (java.util.LinkedList)13 DatabaseService (org.structr.api.DatabaseService)12 DOMNode (org.structr.web.entity.dom.DOMNode)12 Result (org.structr.core.Result)11 PropertyConverter (org.structr.core.converter.PropertyConverter)11 GraphObjectMap (org.structr.core.GraphObjectMap)10 Query (org.structr.core.app.Query)10 Principal (org.structr.core.entity.Principal)10