Search in sources :

Example 1 with JsonArray

use of com.bluenimble.platform.json.JsonArray in project serverless by bluenimble.

the class ScriptableApiServiceSpi method execute.

@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
    Object jsApi = ((SpecAndSpiPair) api.getHelper()).spec();
    if (jsApi == null) {
        throw new ApiServiceExecutionException("api '" + api.getNamespace() + "' doesn't support scripting");
    }
    SpecAndSpiPair serviceHelper = (SpecAndSpiPair) request.getService().getHelper();
    Object spi = serviceHelper.spi();
    if (spi == null) {
        throw new ApiServiceExecutionException("service spi not found");
    }
    ScriptingEngine engine = api.space().feature(ScriptingEngine.class, ApiSpace.Features.Default, request);
    if (!engine.has(spi, Functions.Execute)) {
        return null;
    }
    // invoke execute
    Object result = null;
    try {
        result = engine.invoke(spi, Functions.Execute, jsApi, consumer, request, response);
    } catch (ScriptingEngineException ex) {
        ex.setScript(Json.getString(request.getService().getRuntime(), Api.Spec.Runtime.Function));
        throw new ApiServiceExecutionException(ex.getMessage(), ex);
    }
    if (result == null || (result instanceof Undefined)) {
        return null;
    }
    if (ApiOutput.class.isAssignableFrom(result.getClass())) {
        return (ApiOutput) result;
    }
    if (ScriptObjectMirror.class.isAssignableFrom(result.getClass())) {
        ScriptObjectMirror som = (ScriptObjectMirror) result;
        Object clazz = som.get(ClassField);
        if (clazz == null) {
            return new ApiSomOutput(som);
        }
        if (clazz.equals(ApiOutputClass)) {
            return (ApiOutput) som.getMember(ProxyField);
        }
    }
    Object converted = Converters.convert(result);
    if (converted instanceof JsonArray) {
        converted = new JsonObject().set(ApiOutput.Defaults.Items, converted);
    }
    if (!(converted instanceof JsonObject)) {
        throw new ApiServiceExecutionException("result should be a valid json object");
    }
    return new JsonApiOutput((JsonObject) converted);
}
Also used : JsonArray(com.bluenimble.platform.json.JsonArray) Undefined(jdk.nashorn.internal.runtime.Undefined) ScriptObjectMirror(jdk.nashorn.api.scripting.ScriptObjectMirror) ApiOutput(com.bluenimble.platform.api.ApiOutput) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput) ScriptingEngineException(com.bluenimble.platform.scripting.ScriptingEngineException) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) JsonObject(com.bluenimble.platform.json.JsonObject) JsonObject(com.bluenimble.platform.json.JsonObject) ScriptingEngine(com.bluenimble.platform.scripting.ScriptingEngine) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput)

Example 2 with JsonArray

use of com.bluenimble.platform.json.JsonArray in project serverless by bluenimble.

the class SignatureConsumerResolver method getSecretKey.

private String getSecretKey(Api api, ApiRequest request, ApiConsumer consumer, String accessKey) throws ApiAuthenticationException {
    JsonObject auth = Json.getObject(Json.getObject(Json.getObject(api.getSecurity(), Api.Spec.Security.Schemes), MethodName), Api.Spec.Security.Auth);
    if (auth == null || auth.isEmpty()) {
        return null;
    }
    String feature = Json.getString(auth, Spec.Auth.Feature);
    String secretKeyField = Json.getString(auth, Spec.Auth.SecretKeyField, Defaults.SecretKey);
    JsonObject query = Json.getObject(auth, Spec.Auth.Query);
    JsonArray parameters = Json.getArray(auth, Spec.Auth.Parameters);
    if (query == null || query.isEmpty()) {
        return null;
    }
    Map<String, Object> bindings = new HashMap<String, Object>();
    bindings.put(ApiConsumer.Fields.AccessKey, accessKey);
    // addt params
    if (parameters != null && !parameters.isEmpty()) {
        for (int i = 0; i < parameters.count(); i++) {
            String key = String.valueOf(parameters.get(i));
            Object o = request.get(key);
            if (o != null) {
                bindings.put(key, o);
            }
        }
    }
    JsonQuery q = new JsonQuery(query, bindings);
    DatabaseObject odb = null;
    try {
        odb = api.space().feature(Database.class, feature, request).findOne(null, q);
    } catch (Exception ex) {
        throw new ApiAuthenticationException(ex.getMessage(), ex);
    }
    if (odb == null) {
        throw new ApiAuthenticationException("invalid accessKey " + accessKey);
    }
    JsonObject oRecord = odb.toJson(null);
    String[] secretKeyProps = Lang.split(secretKeyField, Lang.DOT);
    Object oSecretKey = Json.find(oRecord, secretKeyProps);
    if (oSecretKey == null) {
        throw new ApiAuthenticationException("secret key not found for accessKey " + accessKey);
    }
    if (!(oSecretKey instanceof String)) {
        throw new ApiAuthenticationException("secret key should be a valid String");
    }
    consumer.set(ApiConsumer.Fields.AccessKey, accessKey);
    consumer.set(ApiConsumer.Fields.SecretKey, oSecretKey);
    JsonObject oConsumer = oRecord;
    for (Object k : oConsumer.keySet()) {
        consumer.set(String.valueOf(k), oConsumer.get(k));
    }
    consumer.set(ApiConsumer.Fields.Anonymous, false);
    return (String) oSecretKey;
}
Also used : JsonArray(com.bluenimble.platform.json.JsonArray) JsonQuery(com.bluenimble.platform.db.query.impls.JsonQuery) HashMap(java.util.HashMap) ApiAuthenticationException(com.bluenimble.platform.api.security.ApiAuthenticationException) JsonObject(com.bluenimble.platform.json.JsonObject) DatabaseObject(com.bluenimble.platform.db.DatabaseObject) JsonObject(com.bluenimble.platform.json.JsonObject) DatabaseObject(com.bluenimble.platform.db.DatabaseObject) ApiAuthenticationException(com.bluenimble.platform.api.security.ApiAuthenticationException) ParseException(java.text.ParseException)

Example 3 with JsonArray

use of com.bluenimble.platform.json.JsonArray in project serverless by bluenimble.

the class TokenConsumerResolver method authorize.

@Override
public ApiConsumer authorize(Api api, ApiService service, ApiRequest request, ApiConsumer consumer) throws ApiAuthenticationException {
    JsonObject auth = Json.getObject(Json.getObject(Json.getObject(api.getSecurity(), Api.Spec.Security.Schemes), MethodName), Api.Spec.Security.Auth);
    if (auth == null || auth.isEmpty()) {
        return consumer;
    }
    String token = (String) consumer.get(ApiConsumer.Fields.Token);
    // decrypt token
    String decrypted = null;
    JsonObject secrets;
    try {
        secrets = api.space().getSecrets(Json.getString(auth, Spec.Auth.Secrets));
    } catch (ApiManagementException e) {
        throw new ApiAuthenticationException(e.getMessage(), e);
    }
    if (secrets != null && secrets.containsKey(ApiSpace.Spec.secrets.Key)) {
        String key = Json.getString(secrets, ApiSpace.Spec.secrets.Key);
        Crypto.Algorithm alg = Crypto.Algorithm.AES;
        try {
            alg = Crypto.Algorithm.valueOf(Json.getString(secrets, ApiSpace.Spec.secrets.Algorithm, Crypto.Algorithm.AES.name()).toUpperCase());
        } catch (Exception ex) {
            api.tracer().log(Tracer.Level.Error, Lang.BLANK, ex);
        // IGNORE - > invalid token
        }
        try {
            decrypted = new String(Crypto.decrypt(Lang.decodeHex(token.toCharArray()), key, alg));
        } catch (Exception ex) {
            api.tracer().log(Tracer.Level.Error, Lang.BLANK, ex);
        // IGNORE - > invalid token
        }
    }
    boolean isServiceSecure = Json.getBoolean(service.getSecurity(), ApiService.Spec.Security.Enabled, true);
    if (decrypted == null) {
        if (isServiceSecure) {
            throw new ApiAuthenticationException("invalid token");
        } else {
            return consumer;
        }
    }
    int indexOfSpace = decrypted.indexOf(Lang.SPACE);
    if (indexOfSpace < 0) {
        if (isServiceSecure) {
            throw new ApiAuthenticationException("invalid token");
        } else {
            return consumer;
        }
    }
    String sExpiry = decrypted.substring(0, indexOfSpace);
    long expiry = Long.valueOf(sExpiry);
    if (expiry < System.currentTimeMillis()) {
        if (isServiceSecure) {
            throw new ApiAuthenticationException("token expired");
        }
    }
    consumer.set(ApiConsumer.Fields.ExpiryDate, Lang.toUTC(new Date(expiry)));
    String sInfo = decrypted.substring(indexOfSpace + 1);
    JsonArray fields = Json.getArray(api.getSecurity(), Api.Spec.Security.Encrypt);
    if (fields == null || fields.isEmpty()) {
        consumer.set(ApiConsumer.Fields.Id, sInfo);
    } else {
        String[] values = Lang.split(sInfo, Lang.SEMICOLON);
        for (int i = 0; i < fields.count(); i++) {
            if (i >= values.length) {
                break;
            }
            consumer.set((String) fields.get(i), values[i]);
        }
    }
    consumer.set(ApiConsumer.Fields.Permissions, secrets.get(ApiConsumer.Fields.Permissions));
    consumer.set(ApiConsumer.Fields.Anonymous, false);
    return consumer;
}
Also used : JsonObject(com.bluenimble.platform.json.JsonObject) ApiManagementException(com.bluenimble.platform.api.ApiManagementException) ApiManagementException(com.bluenimble.platform.api.ApiManagementException) ApiAuthenticationException(com.bluenimble.platform.api.security.ApiAuthenticationException) Date(java.util.Date) JsonArray(com.bluenimble.platform.json.JsonArray) Crypto(com.bluenimble.platform.Crypto) ApiAuthenticationException(com.bluenimble.platform.api.security.ApiAuthenticationException)

Example 4 with JsonArray

use of com.bluenimble.platform.json.JsonArray in project serverless by bluenimble.

the class FileSystemKeyStoreManager method read.

@Override
public SpaceKeyStore read(ApiSpace space) throws IOException {
    SpaceKeyStoreImpl ks = new SpaceKeyStoreImpl(this, space);
    // load default keys
    JsonArray aKeys = space.keys();
    if (aKeys != null && !aKeys.isEmpty()) {
        for (int i = 0; i < aKeys.count(); i++) {
            KeyPair skp = toKeyPair((String) aKeys.get(i));
            ks._put(skp);
        }
    }
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(keyStoreFile(space, true)), Encodings.UTF8));
        String line = reader.readLine();
        while (line != null) {
            KeyPair skp = toKeyPair(line);
            ks._put(skp);
            line = reader.readLine();
        }
    } finally {
        IOUtils.closeQuietly(reader);
    }
    return ks;
}
Also used : JsonArray(com.bluenimble.platform.json.JsonArray) KeyPair(com.bluenimble.platform.security.KeyPair) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) FileInputStream(java.io.FileInputStream)

Example 5 with JsonArray

use of com.bluenimble.platform.json.JsonArray in project serverless by bluenimble.

the class FileUtils method readStartsWith.

public static JsonArray readStartsWith(File file, String startsWith, boolean addLineNumber) throws IOException {
    JsonArray list = new JsonArray();
    Reader reader = null;
    try {
        reader = new FileReader(file);
        @SuppressWarnings("resource") BufferedReader br = new BufferedReader(reader);
        int lineIndex = 1;
        String line = br.readLine();
        while (line != null) {
            line = line.trim();
            if (line.startsWith(startsWith)) {
                list.add(addLineNumber ? lineIndex + Lang.SPACE + line : line);
            }
            lineIndex++;
            line = br.readLine();
        }
    } finally {
        IOUtils.closeQuietly(reader);
    }
    return list;
}
Also used : JsonArray(com.bluenimble.platform.json.JsonArray) BufferedReader(java.io.BufferedReader) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) Reader(java.io.Reader) FileReader(java.io.FileReader)

Aggregations

JsonArray (com.bluenimble.platform.json.JsonArray)42 JsonObject (com.bluenimble.platform.json.JsonObject)37 DatabaseObject (com.bluenimble.platform.db.DatabaseObject)9 Map (java.util.Map)8 ApiServiceExecutionException (com.bluenimble.platform.api.ApiServiceExecutionException)6 ApiSpace (com.bluenimble.platform.api.ApiSpace)5 JsonApiOutput (com.bluenimble.platform.api.impls.JsonApiOutput)5 Database (com.bluenimble.platform.db.Database)5 IOException (java.io.IOException)5 ApiAccessDeniedException (com.bluenimble.platform.api.ApiAccessDeniedException)4 ApiAuthenticationException (com.bluenimble.platform.api.security.ApiAuthenticationException)4 CommandExecutionException (com.bluenimble.platform.cli.command.CommandExecutionException)4 DefaultCommandResult (com.bluenimble.platform.cli.command.impls.DefaultCommandResult)4 ApiService (com.bluenimble.platform.api.ApiService)3 DescribeOption (com.bluenimble.platform.api.DescribeOption)3 DatabaseException (com.bluenimble.platform.db.DatabaseException)3 JsonQuery (com.bluenimble.platform.db.query.impls.JsonQuery)3 KeyPair (com.bluenimble.platform.security.KeyPair)3 ArrayList (java.util.ArrayList)3 ApiOutput (com.bluenimble.platform.api.ApiOutput)2