Search in sources :

Example 11 with JsonObject

use of com.bluenimble.platform.json.JsonObject 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 12 with JsonObject

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

the class SpaceKeyStoreImpl method create.

@Override
public List<KeyPair> create(int pack, final Date expiryDate, final Map<String, Object> properties) throws SpaceKeyStoreException {
    if (pack < 1) {
        return null;
    }
    List<KeyPair> keys = null;
    try {
        keys = new ArrayList<KeyPair>();
        for (int i = 0; i < pack; i++) {
            final String[] aKeys = Lang.keys();
            KeyPair skp = new KeyPair() {

                private static final long serialVersionUID = -1855450550265796892L;

                @Override
                public String accessKey() {
                    return aKeys[0];
                }

                @Override
                public String secretKey() {
                    return aKeys[1];
                }

                @Override
                public Date expiryDate() {
                    return expiryDate;
                }

                @Override
                public Iterator<String> properties() {
                    if (properties == null) {
                        return null;
                    }
                    return properties.keySet().iterator();
                }

                @Override
                public Object property(String name) {
                    if (properties == null) {
                        return null;
                    }
                    return properties.get(name);
                }

                @Override
                public JsonObject toJson() {
                    JsonObject out = new JsonObject();
                    out.set(KeyPair.Fields.AccessKey, accessKey()).set(KeyPair.Fields.SecretKey, secretKey());
                    if (expiryDate() != null) {
                        out.set(KeyPair.Fields.ExpiryDate, Lang.toUTC(expiryDate()));
                    }
                    if (properties != null) {
                        out.set(KeyPair.Fields.Properties, properties);
                    }
                    return out;
                }

                @Override
                public String toString() {
                    return toJson().toString();
                }
            };
            put(skp);
            keys.add(skp);
        }
    } catch (Exception ex) {
        throw new SpaceKeyStoreException(ex.getMessage(), ex);
    }
    return keys;
}
Also used : KeyPair(com.bluenimble.platform.security.KeyPair) SpaceKeyStoreException(com.bluenimble.platform.security.SpaceKeyStoreException) JsonObject(com.bluenimble.platform.json.JsonObject) SpaceKeyStoreException(com.bluenimble.platform.security.SpaceKeyStoreException)

Example 13 with JsonObject

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

the class ExtendedApiRequestVisitor method enrich.

@Override
protected void enrich(AbstractApiRequest request) {
    JsonObject device = request.getDevice();
    String agent = (String) request.get(ApiHeaders.UserAgent, Scope.Header);
    if (agent != null) {
        device.set(ApiRequest.Fields.Device.Agent, agent);
        device.putAll(Classifier.parse(agent));
    }
}
Also used : JsonObject(com.bluenimble.platform.json.JsonObject)

Example 14 with JsonObject

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

the class FileSystemStoragePlugin method createStorage.

private void createStorage(ApiSpace space) {
    JsonObject storageFeature = Json.getObject(space.getFeatures(), feature);
    if (storageFeature == null || storageFeature.isEmpty()) {
        return;
    }
    Iterator<String> keys = storageFeature.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        JsonObject source = Json.getObject(storageFeature, key);
        if (!this.getName().equalsIgnoreCase(Json.getString(source, ApiSpace.Features.Provider))) {
            continue;
        }
        JsonObject spec = Json.getObject(source, ApiSpace.Features.Spec);
        if (spec == null) {
            continue;
        }
        String mount = Json.getString(spec, Spec.Mount);
        if (Lang.isNullOrEmpty(mount)) {
            continue;
        }
        File spaceStorage = new File(fRoot, mount);
        if (!spaceStorage.exists()) {
            spaceStorage.mkdir();
        }
        mounts.put(createStorageKey(key, space), mount);
    }
}
Also used : JsonObject(com.bluenimble.platform.json.JsonObject) File(java.io.File)

Example 15 with JsonObject

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

the class IndexerApiRequestTrack method finish.

@Override
public void finish(JsonObject feedback) {
    final Date now = new Date();
    Json.getObject(track, Fields.Time.class.getSimpleName().toLowerCase()).set(Fields.Time.Finished, Lang.toString(now, DateFormat));
    int code = Json.getInteger(feedback, ApiResponse.Error.Code, ApiResponse.OK.getCode());
    track.set(Fields.Status, code);
    if (feedback.containsKey(Fields.FeedBack.Message)) {
        feedback.set(Fields.FeedBack.Message, feedback.get(Fields.FeedBack.Message).toString());
    }
    track.set(Fields.Feedback, feedback);
    JsonObject metrics = Json.getObject(track, Fields.Metrics.class.getSimpleName().toLowerCase());
    if (MX.isCurrentThreadCpuTimeSupported()) {
        metrics.set(Fields.Metrics.Cpu, MX.getCurrentThreadUserTime());
    }
    if (MX.isCurrentThreadCpuTimeSupported()) {
        metrics.set(Fields.Metrics.Memory, MX.getThreadAllocatedBytes(Thread.currentThread().getId()));
    }
    try {
        tracker.executor().execute(new Runnable() {

            @Override
            public void run() {
                api.tracer().log(Tracer.Level.Info, "Executor Started Track Thread ...");
                // shrink
                track.shrink();
                JsonObject oTracking = api.getTracking();
                // put
                Indexer indexer = null;
                try {
                    indexer = api.space().feature(Indexer.class, Json.getString(oTracking, Spec.Feature, ApiSpace.Features.Default), tracker.context());
                    if (indexer == null) {
                        api.tracer().log(Tracer.Level.Error, "CantStore[{0}] due to indexer declared in the api is not defined at the space level", track.toString());
                        return;
                    }
                    String entity = Json.getString(oTracking, Spec.Entity, DefaultEntity);
                    if (!indexer.exists(entity)) {
                        api.tracer().log(Tracer.Level.Info, "Entity not found in Index, Create Mapping...");
                        indexer.create(entity, requestMapping());
                    }
                    indexer.put(entity, track);
                } catch (IndexerException e) {
                    api.tracer().log(Tracer.Level.Error, "CantStore[{0}] due to {1}", track.toString(), e.getMessage());
                    api.tracer().log(Tracer.Level.Error, Lang.BLANK, e);
                }
            }
        });
    } catch (Exception ex) {
        api.tracer().log(Tracer.Level.Error, Lang.BLANK, ex);
    }
}
Also used : Indexer(com.bluenimble.platform.indexer.Indexer) JsonObject(com.bluenimble.platform.json.JsonObject) IndexerException(com.bluenimble.platform.indexer.IndexerException) Date(java.util.Date) IndexerException(com.bluenimble.platform.indexer.IndexerException)

Aggregations

JsonObject (com.bluenimble.platform.json.JsonObject)230 ApiServiceExecutionException (com.bluenimble.platform.api.ApiServiceExecutionException)40 DatabaseObject (com.bluenimble.platform.db.DatabaseObject)37 JsonArray (com.bluenimble.platform.json.JsonArray)37 JsonApiOutput (com.bluenimble.platform.api.impls.JsonApiOutput)34 Database (com.bluenimble.platform.db.Database)29 ApiSpace (com.bluenimble.platform.api.ApiSpace)26 File (java.io.File)25 ApiAccessDeniedException (com.bluenimble.platform.api.ApiAccessDeniedException)23 Map (java.util.Map)22 IOException (java.io.IOException)20 CommandExecutionException (com.bluenimble.platform.cli.command.CommandExecutionException)17 JsonQuery (com.bluenimble.platform.db.query.impls.JsonQuery)16 InputStream (java.io.InputStream)14 Date (java.util.Date)14 DefaultCommandResult (com.bluenimble.platform.cli.command.impls.DefaultCommandResult)13 ApiManagementException (com.bluenimble.platform.api.ApiManagementException)12 DefaultDatabaseObjectSerializer (com.bluenimble.platform.db.impls.DefaultDatabaseObjectSerializer)11 HashMap (java.util.HashMap)11 DatabaseException (com.bluenimble.platform.db.DatabaseException)9