Search in sources :

Example 26 with SecurityContext

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

the class StructrScriptable method get.

@Override
public Object get(final String name, Scriptable start) {
    if ("get".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                if (parameters.length == 1 && parameters[0] != null) {
                    try {
                        return wrap(context, thisObject, null, actionContext.evaluate(entity, parameters[0].toString(), null, null, 0));
                    } catch (FrameworkException ex) {
                        exception = ex;
                    }
                } else if (parameters.length > 1) {
                    // execute builtin get function
                    final Function<Object, Object> function = Functions.get("get");
                    try {
                        final Object[] unwrappedParameters = new Object[parameters.length];
                        int i = 0;
                        // unwrap JS objects
                        for (final Object param : parameters) {
                            unwrappedParameters[i++] = unwrap(param);
                        }
                        return wrap(context, scope, null, function.apply(actionContext, entity, unwrappedParameters));
                    } catch (FrameworkException fex) {
                        exception = fex;
                    }
                    return null;
                }
                return null;
            }
        }, null, 0, 0);
    }
    if ("clear".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                actionContext.clear();
                return null;
            }
        }, null, 0, 0);
    }
    if ("this".equals(name)) {
        return wrap(this.scriptingContext, start, null, entity);
    }
    if ("me".equals(name)) {
        return wrap(this.scriptingContext, start, null, actionContext.getSecurityContext().getUser(false));
    }
    if ("vars".equals(name)) {
        NativeObject nobj = new NativeObject();
        for (Map.Entry<String, Object> entry : actionContext.getAllVariables().entrySet()) {
            nobj.defineProperty(entry.getKey(), entry.getValue(), NativeObject.READONLY);
        }
        return nobj;
    }
    if ("include".equals(name) || "render".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                if (parameters.length > 0 && parameters[0] != null) {
                    try {
                        final Function func = Functions.get(name);
                        if (func != null) {
                            actionContext.print(func.apply(actionContext, entity, parameters));
                        }
                        return null;
                    } catch (FrameworkException ex) {
                        exception = ex;
                    }
                }
                return null;
            }
        }, null, 0, 0);
    }
    if ("includeJs".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                if (parameters.length == 1) {
                    final String fileName = parameters[0].toString();
                    final String source = actionContext.getJavascriptLibraryCode(fileName);
                    // use cached / compiled source code for JS libs
                    Scripting.compileOrGetCached(context, source, fileName, 1).exec(context, scope);
                } else {
                    logger.warn("Incorrect usage of includeJs function. Takes exactly one parameter: The filename of the javascript file!");
                }
                return null;
            }
        }, null, 0, 0);
    }
    if ("batch".equals(name)) {
        return new IdFunctionObject(new BatchFunctionCall(actionContext, this), null, 0, 0);
    }
    if ("cache".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                final CacheExpression cacheExpr = new CacheExpression();
                Object retVal = null;
                try {
                    for (int i = 0; i < parameters.length; i++) {
                        cacheExpr.add(new ConstantExpression(parameters[i]));
                    }
                    retVal = cacheExpr.evaluate(actionContext, entity);
                } catch (FrameworkException ex) {
                    exception = ex;
                }
                return retVal;
            }
        }, null, 0, 0);
    }
    if ("slice".equals(name)) {
        return new IdFunctionObject(new SliceFunctionCall(actionContext, entity, scriptingContext), null, 0, 0);
    }
    if ("doPrivileged".equals(name) || "do_privileged".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                // backup security context
                final SecurityContext securityContext = StructrScriptable.this.actionContext.getSecurityContext();
                try {
                    // replace security context with super user context
                    actionContext.setSecurityContext(SecurityContext.getSuperUserInstance());
                    if (parameters != null && parameters.length == 1) {
                        final Object param = parameters[0];
                        if (param instanceof Script) {
                            final Script script = (Script) param;
                            return script.exec(context, scope);
                        } else {
                        // ...
                        }
                    } else {
                    // ...
                    }
                    return null;
                } finally {
                    // restore saved security context
                    StructrScriptable.this.actionContext.setSecurityContext(securityContext);
                }
            }
        }, null, 0, 0);
    }
    // execute builtin function?
    final Function<Object, Object> function = Functions.get(CaseHelper.toUnderscore(name, false));
    if (function != null) {
        return new IdFunctionObject(new FunctionWrapper(function), null, 0, 0);
    }
    return null;
}
Also used : SecurityContext(org.structr.common.SecurityContext) Context(org.mozilla.javascript.Context) ActionContext(org.structr.schema.action.ActionContext) Script(org.mozilla.javascript.Script) FrameworkException(org.structr.common.error.FrameworkException) ConstantExpression(org.structr.core.parser.ConstantExpression) IdFunctionCall(org.mozilla.javascript.IdFunctionCall) Scriptable(org.mozilla.javascript.Scriptable) CacheExpression(org.structr.core.parser.CacheExpression) NativeObject(org.mozilla.javascript.NativeObject) Function(org.structr.schema.action.Function) GrantFunction(org.structr.core.function.GrantFunction) SecurityContext(org.structr.common.SecurityContext) NativeObject(org.mozilla.javascript.NativeObject) IdFunctionObject(org.mozilla.javascript.IdFunctionObject) GraphObject(org.structr.core.GraphObject) ScriptableObject(org.mozilla.javascript.ScriptableObject) IdFunctionObject(org.mozilla.javascript.IdFunctionObject) PropertyMap(org.structr.core.property.PropertyMap) Map(java.util.Map) GraphObjectMap(org.structr.core.GraphObjectMap)

Example 27 with SecurityContext

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

the class LogResource method doPost.

@Override
public RestMethodResult doPost(Map<String, Object> propertySet) throws FrameworkException {
    final HttpServletRequest request = securityContext.getRequest();
    if (request != null) {
        // initialize?!
        if ("true".equals(request.getParameter("initialize"))) {
            final String filesPath = Settings.FilesPath.getValue();
            try (final Context context = new Context(1000)) {
                collectFilesAndStore(context, new File(filesPath + SUBJECTS).toPath(), 0);
            } catch (FrameworkException fex) {
                logger.warn("", fex);
            }
            return new RestMethodResult(200);
        }
        final String subjectId = (String) propertySet.get(subjectProperty.jsonName());
        final String objectId = (String) propertySet.get(objectProperty.jsonName());
        final String action = (String) propertySet.get(actionProperty.jsonName());
        final String message = (String) propertySet.get(messageProperty.jsonName());
        if (subjectId != null && objectId != null && action != null) {
            final App app = StructrApp.getInstance(securityContext);
            LogEvent event = null;
            try (final Tx tx = app.tx()) {
                final PropertyMap properties = new PropertyMap();
                properties.put(LogEvent.timestampProperty, new Date());
                properties.put(LogEvent.actionProperty, action);
                properties.put(LogEvent.subjectProperty, subjectId);
                properties.put(LogEvent.objectProperty, objectId);
                properties.put(LogEvent.messageProperty, message);
                properties.put(LogEvent.visibleToPublicUsers, true);
                properties.put(LogEvent.visibleToAuthenticatedUsers, true);
                event = app.create(LogEvent.class, properties);
                tx.success();
            }
            final RestMethodResult result = new RestMethodResult(201);
            result.addContent(event);
            return result;
        } else {
            final ErrorBuffer errorBuffer = new ErrorBuffer();
            if (StringUtils.isEmpty(subjectId)) {
                errorBuffer.add(new EmptyPropertyToken("LogFile", subjectProperty));
            }
            if (StringUtils.isEmpty(objectId)) {
                errorBuffer.add(new EmptyPropertyToken("LogFile", objectProperty));
            }
            if (StringUtils.isEmpty(action)) {
                errorBuffer.add(new EmptyPropertyToken("LogFile", actionProperty));
            }
            throw new FrameworkException(422, "Log entry must consist of at least subjectId, objectId and action", errorBuffer);
        }
    }
    // no request object, this is fatal
    throw new FrameworkException(500, "No request object present, aborting.");
}
Also used : SecurityContext(org.structr.common.SecurityContext) App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) EmptyPropertyToken(org.structr.common.error.EmptyPropertyToken) FrameworkException(org.structr.common.error.FrameworkException) Tx(org.structr.core.graph.Tx) LogEvent(org.structr.rest.logging.entity.LogEvent) Date(java.util.Date) HttpServletRequest(javax.servlet.http.HttpServletRequest) PropertyMap(org.structr.core.property.PropertyMap) ErrorBuffer(org.structr.common.error.ErrorBuffer) File(java.io.File) RestMethodResult(org.structr.rest.RestMethodResult)

Example 28 with SecurityContext

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

the class GetFunction method apply.

@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) throws FrameworkException {
    final SecurityContext securityContext = ctx.getSecurityContext();
    try {
        if (!arrayHasLengthAndAllElementsNotNull(sources, 2)) {
            return "";
        }
        final String keyName = sources[1].toString();
        GraphObject dataObject = null;
        // handle GraphObject
        if (sources[0] instanceof GraphObject) {
            dataObject = (GraphObject) sources[0];
        }
        // handle first element of a list of graph objects
        if (sources[0] instanceof List) {
            final List list = (List) sources[0];
            final int size = list.size();
            if (size == 1) {
                final Object value = list.get(0);
                if (value != null) {
                    if (value instanceof GraphObject) {
                        dataObject = (GraphObject) list.get(0);
                    } else {
                        return "get(): first element of collection is of type " + value.getClass() + " which is not supported.";
                    }
                } else {
                    return "get(): first element of collection is null.";
                }
            }
        }
        // handle map separately
        if (sources[0] instanceof Map && !(sources[0] instanceof GraphObjectMap)) {
            final Map map = (Map) sources[0];
            return map.get(keyName);
        }
        // handle request object
        if (sources[0] instanceof HttpServletRequest) {
            final HttpServletRequest request = (HttpServletRequest) sources[0];
            return request.getParameter(keyName);
        }
        if (dataObject != null) {
            final PropertyKey key = StructrApp.key(dataObject.getClass(), keyName);
            if (key != null) {
                final PropertyConverter inputConverter = key.inputConverter(securityContext);
                Object value = dataObject.getProperty(key);
                if (inputConverter != null) {
                    return inputConverter.revert(value);
                }
                return dataObject.getProperty(key);
            }
            return "";
        } else {
            return ERROR_MESSAGE_GET_ENTITY;
        }
    } catch (final IllegalArgumentException e) {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
        return usage(ctx.isJavaScriptContext());
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) GraphObjectMap(org.structr.core.GraphObjectMap) SecurityContext(org.structr.common.SecurityContext) PropertyConverter(org.structr.core.converter.PropertyConverter) List(java.util.List) GraphObject(org.structr.core.GraphObject) GraphObject(org.structr.core.GraphObject) Map(java.util.Map) GraphObjectMap(org.structr.core.GraphObjectMap) PropertyKey(org.structr.core.property.PropertyKey)

Example 29 with SecurityContext

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

the class GetOrCreateFunction method apply.

@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) throws FrameworkException {
    try {
        if (sources == null) {
            throw new IllegalArgumentException();
        }
        final SecurityContext securityContext = ctx.getSecurityContext();
        final ConfigurationProvider config = StructrApp.getConfiguration();
        final App app = StructrApp.getInstance(securityContext);
        final PropertyMap properties = new PropertyMap();
        // the type to query for
        Class type = null;
        if (sources.length >= 1 && sources[0] != null) {
            final String typeString = sources[0].toString();
            type = config.getNodeEntityClass(typeString);
            if (type == null) {
                logger.warn("Error in get_or_create(): type \"{}\" not found.", typeString);
                return ERROR_MESSAGE_TYPE_NOT_FOUND + typeString;
            }
        }
        // exit gracefully instead of crashing..
        if (type == null) {
            logger.warn("Error in get_or_create(): no type specified. Parameters: {}", getParametersAsString(sources));
            return ERROR_MESSAGE_NO_TYPE_SPECIFIED;
        }
        // experimental: disable result count, prevents instantiation
        // of large collections just for counting all the objects..
        securityContext.ignoreResultCount(true);
        // extension for native javascript objects
        if (sources.length == 2 && sources[1] instanceof Map) {
            properties.putAll(PropertyMap.inputTypeToJavaType(securityContext, type, (Map) sources[1]));
        } else {
            final int parameter_count = sources.length;
            if (parameter_count % 2 == 0) {
                throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_GET_OR_CREATE);
            }
            for (int c = 1; c < parameter_count; c += 2) {
                if (sources[c] == null) {
                    throw new IllegalArgumentException();
                }
                final PropertyKey key = StructrApp.key(type, sources[c].toString());
                if (key != null) {
                    final PropertyConverter inputConverter = key.inputConverter(securityContext);
                    Object value = sources[c + 1];
                    if (inputConverter != null) {
                        value = inputConverter.convert(value);
                    }
                    properties.put(key, value);
                }
            }
        }
        final GraphObject obj = app.nodeQuery(type).disableSorting().pageSize(1).and(properties).getFirst();
        if (obj != null) {
            // return existing object
            return obj;
        }
        // create new object
        return app.create(type, properties);
    } catch (final IllegalArgumentException e) {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
        return usage(ctx.isJavaScriptContext());
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) FrameworkException(org.structr.common.error.FrameworkException) ConfigurationProvider(org.structr.schema.ConfigurationProvider) GraphObject(org.structr.core.GraphObject) PropertyMap(org.structr.core.property.PropertyMap) SecurityContext(org.structr.common.SecurityContext) PropertyConverter(org.structr.core.converter.PropertyConverter) GraphObject(org.structr.core.GraphObject) PropertyMap(org.structr.core.property.PropertyMap) Map(java.util.Map) PropertyKey(org.structr.core.property.PropertyKey)

Example 30 with SecurityContext

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

the class PrivilegedFindFunction method apply.

@Override
public Object apply(final ActionContext ctx, final Object caller, Object[] sources) throws FrameworkException {
    if (sources != null) {
        final SecurityContext securityContext = SecurityContext.getSuperUserInstance();
        final ConfigurationProvider config = StructrApp.getConfiguration();
        final Query query = StructrApp.getInstance(securityContext).nodeQuery().sort(GraphObject.createdDate).order(false);
        // the type to query for
        Class type = null;
        if (sources.length >= 1 && sources[0] != null) {
            final String typeString = sources[0].toString();
            type = config.getNodeEntityClass(typeString);
            if (type != null) {
                query.andTypes(type);
            } else {
                logger.warn("Error in find_privileged(): type \"{}\" not found.", typeString);
                return "Error in find_privileged(): type " + typeString + " not found.";
            }
        }
        // exit gracefully instead of crashing..
        if (type == null) {
            logger.warn("Error in find_privileged(): no type specified. Parameters: {}", getParametersAsString(sources));
            return "Error in find_privileged(): no type specified.";
        }
        // experimental: disable result count, prevents instantiation
        // of large collections just for counting all the objects..
        securityContext.ignoreResultCount(true);
        // extension for native javascript objects
        if (sources.length == 2 && sources[1] instanceof Map) {
            query.and(PropertyMap.inputTypeToJavaType(securityContext, type, (Map) sources[1]));
        } else if (sources.length == 2) {
            if (sources[1] == null) {
                throw new IllegalArgumentException();
            }
            // special case: second parameter is a UUID
            final PropertyKey key = StructrApp.key(type, "id");
            query.and(key, sources[1].toString());
            final int resultCount = query.getResult().size();
            switch(resultCount) {
                case 1:
                    return query.getFirst();
                case 0:
                    return null;
                default:
                    throw new FrameworkException(400, "Multiple Objects found for id! [" + sources[1].toString() + "]");
            }
        } else {
            final int parameter_count = sources.length;
            if (parameter_count % 2 == 0) {
                throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_PRIVILEGEDFIND);
            }
            for (int c = 1; c < parameter_count; c += 2) {
                final PropertyKey key = StructrApp.key(type, sources[c].toString());
                if (key != null) {
                    final PropertyConverter inputConverter = key.inputConverter(securityContext);
                    Object value = sources[c + 1];
                    if (inputConverter != null) {
                        value = inputConverter.convert(value);
                    }
                    query.and(key, value);
                }
            }
        }
        return query.getAsList();
    }
    return "";
}
Also used : Query(org.structr.core.app.Query) FrameworkException(org.structr.common.error.FrameworkException) ConfigurationProvider(org.structr.schema.ConfigurationProvider) SecurityContext(org.structr.common.SecurityContext) PropertyConverter(org.structr.core.converter.PropertyConverter) GraphObject(org.structr.core.GraphObject) PropertyMap(org.structr.core.property.PropertyMap) Map(java.util.Map) PropertyKey(org.structr.core.property.PropertyKey)

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