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;
}
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.");
}
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());
}
}
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());
}
}
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 "";
}
Aggregations