Search in sources :

Example 21 with JsonApiOutput

use of com.bluenimble.platform.api.impls.JsonApiOutput in project serverless by bluenimble.

the class SignupServiceSpi method execute.

@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
    JsonObject config = request.getService().getCustom();
    JsonObject payload = (JsonObject) request.get(ApiRequest.Payload);
    Database db = api.space().feature(Database.class, Json.getString(config, Config.Database, ApiSpace.Features.Default), request);
    DatabaseObject account = null;
    try {
        JsonObject where = null;
        JsonObject query = Json.getObject(config, Config.Query);
        if (query == null) {
            query = new JsonObject();
            where = new JsonObject();
            query.set(Query.Construct.where.name(), where);
        } else {
            where = Json.getObject(query, Query.Construct.where.name());
        }
        query.set(Database.Fields.Entity, Json.getString(config, Config.UsersEntity, Defaults.Users));
        where.set(Json.getString(config, Config.UserProperty, Fields.Email), Json.getString(payload, Spec.User));
        account = db.findOne(null, new JsonQuery(query));
    } catch (Exception ex) {
        throw new ApiServiceExecutionException(ex.getMessage(), ex);
    }
    if (account != null) {
        throw new ApiServiceExecutionException("account already exists").status(ApiResponse.CONFLICT);
    }
    boolean requiresActivation = Json.getBoolean(config, Config.RequiresActivation, false);
    try {
        account = db.create(Json.getString(config, Config.UsersEntity, Defaults.Users));
        account.load(payload);
        // set user property
        account.set(Json.getString(config, Config.UserProperty, Fields.Email), Json.getString(payload, Spec.User));
        account.remove(Spec.User);
        boolean encryptPassword = Json.getBoolean(config, Config.EncryptPassword, true);
        account.set(Json.getString(config, Config.PasswordProperty, Spec.Password), encryptPassword ? Crypto.md5(Json.getString(payload, Spec.Password), Encodings.UTF8) : Json.getString(payload, Spec.Password));
        JsonObject extraData = Json.getObject(config, Config.Data);
        if (extraData != null && !extraData.isEmpty()) {
            Iterator<String> keys = extraData.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                account.set(key, extraData.get(key));
            }
        }
    } catch (Exception ex) {
        throw new ApiServiceExecutionException(ex.getMessage(), ex);
    }
    try {
        String activationCode = null;
        if (requiresActivation) {
            String acType = Json.getString(config, Config.ActivationCodeType, ActivationCodeTypes.CPIN).toLowerCase();
            int pinLength = Json.getInteger(config, Config.PinLength, 6);
            if (acType.equals(ActivationCodeTypes.CPIN)) {
                activationCode = Lang.UUID(pinLength);
            } else if (acType.equals(ActivationCodeTypes.NPIN)) {
                activationCode = Lang.pin(pinLength);
            } else {
                activationCode = Lang.rand();
            }
            account.set(Json.getString(config, Config.ActivationCodeProperty, Defaults.ActivationCode), activationCode);
        }
        account.save();
    } catch (Exception ex) {
        throw new ApiServiceExecutionException(ex.getMessage(), ex);
    }
    payload.remove(Spec.Password);
    JsonObject result = account.toJson(DefaultDatabaseObjectSerializer.Default);
    String email = Json.getString(payload, Spec.Email);
    if (Lang.isNullOrEmpty(email)) {
        if (Json.getBoolean(config, Config.UseUserAsEmailAddress, false)) {
            email = Json.getString(payload, Spec.User);
        }
    }
    result.remove(Json.getString(config, Config.PasswordProperty, Spec.Password));
    if (!requiresActivation || Lang.isNullOrEmpty(email)) {
        Date now = new Date();
        // update lastLogin
        try {
            account.set(Json.getString(config, Config.LastLoginProperty, Fields.LastLogin), now);
            account.save();
        } catch (Exception ex) {
            throw new ApiServiceExecutionException(ex.getMessage(), ex);
        }
        // create token
        String[] tokenAndExpiration = SecurityUtils.tokenAndExpiration(api, result, now);
        result.set(Defaults.Token, tokenAndExpiration[0]);
        result.set(Defaults.ExpiresOn, tokenAndExpiration[1]);
        return new JsonApiOutput(result);
    }
    // requires activation and email is present in payload
    JsonObject oEmail = Json.getObject(config, Config.SignupEmail);
    String feature = Json.getString(oEmail, Email.Messenger);
    String template = Json.getString(oEmail, Email.Template);
    if (oEmail != null && !Lang.isNullOrEmpty(feature) && !Lang.isNullOrEmpty(template)) {
        String fromEmail = Json.getString(oEmail, Email.FromEmail);
        String fromName = Json.getString(oEmail, Email.FromName);
        String subject = Json.getString(oEmail, Email.Subject, "Welcome to " + api.getName());
        final Messenger messenger = api.space().feature(Messenger.class, feature, request);
        final JsonObject emailTemplateData = account.toJson(null);
        try {
            final String fEmail = email;
            api.space().executor().execute(new Callable<Void>() {

                @Override
                public Void call() {
                    try {
                        messenger.send(new JsonSender((JsonObject) new JsonObject().set(JsonActor.Spec.Id, fromEmail).set(JsonActor.Spec.Name, fromName)), new JsonRecipient[] { new JsonRecipient((JsonObject) new JsonObject().set(JsonActor.Spec.Id, fEmail)) }, subject, api.getResourcesManager().get(Lang.split(template, Lang.SLASH)), emailTemplateData);
                    } catch (Exception ex) {
                        throw new RuntimeException(ex.getMessage(), ex);
                    }
                    return null;
                }
            }, CodeExecutor.Mode.Async);
        } catch (Exception ex) {
            throw new ApiServiceExecutionException(ex.getMessage(), ex);
        }
    }
    // call extend if any
    JsonObject onFinish = Json.getObject(config, Config.onFinish.class.getSimpleName());
    ApiOutput onFinishOutput = SecurityUtils.onFinish(api, consumer, request, onFinish, result);
    if (onFinishOutput != null) {
        result.set(Json.getString(onFinish, Config.onFinish.ResultProperty, Config.onFinish.class.getSimpleName()), onFinishOutput.data());
    }
    return new JsonApiOutput(result);
}
Also used : JsonQuery(com.bluenimble.platform.db.query.impls.JsonQuery) Config(com.bluenimble.platform.api.impls.im.LoginServiceSpi.Config) JsonObject(com.bluenimble.platform.json.JsonObject) JsonRecipient(com.bluenimble.platform.messaging.impls.JsonRecipient) Messenger(com.bluenimble.platform.messaging.Messenger) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) Date(java.util.Date) JsonSender(com.bluenimble.platform.messaging.impls.JsonSender) ApiOutput(com.bluenimble.platform.api.ApiOutput) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) Database(com.bluenimble.platform.db.Database) DatabaseObject(com.bluenimble.platform.db.DatabaseObject) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput)

Example 22 with JsonApiOutput

use of com.bluenimble.platform.api.impls.JsonApiOutput in project serverless by bluenimble.

the class ImportDatabaseSpi method execute.

@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
    String provider = (String) request.get(CommonSpec.Provider);
    String[] aEntities = Lang.split((String) request.get(Spec.Entities), Lang.COMMA, true);
    Set<String> entities = null;
    if (aEntities != null && aEntities.length > 0) {
        entities = new HashSet<String>();
        for (String entity : aEntities) {
            entities.add(entity.toUpperCase());
        }
    }
    String[] aOptions = Lang.split((String) request.get(Spec.Options), Lang.COMMA, true);
    Map<ExchangeOption, Boolean> options = null;
    if (aOptions != null && aOptions.length > 0) {
        for (String o : aOptions) {
            try {
                options.put(ExchangeOption.valueOf(o.toLowerCase()), true);
            } catch (Exception ex) {
            // ignore malformed options
            }
        }
    }
    ApiSpace space;
    try {
        space = MgmUtils.space(consumer, api);
    } catch (ApiAccessDeniedException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e).status(ApiResponse.FORBIDDEN);
    }
    String file = (String) request.get(Spec.File);
    JsonObject result = new JsonObject();
    result.set(Spec.File, file);
    final StringBuilder sb = new StringBuilder();
    try {
        space.feature(Database.class, provider, request).imp(entities, space.feature(Storage.class, provider, request).root().get(file).reader(request), options, new Database.ExchangeListener() {

            @Override
            public void onMessage(String message) {
                sb.append(message).append(Lang.ENDLN);
            }
        });
    } catch (Exception e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    }
    result.set(Output.Feedback, sb.toString());
    sb.setLength(0);
    return new JsonApiOutput(result);
}
Also used : JsonObject(com.bluenimble.platform.json.JsonObject) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) ApiAccessDeniedException(com.bluenimble.platform.api.ApiAccessDeniedException) ApiAccessDeniedException(com.bluenimble.platform.api.ApiAccessDeniedException) ApiSpace(com.bluenimble.platform.api.ApiSpace) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) Database(com.bluenimble.platform.db.Database) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput) ExchangeOption(com.bluenimble.platform.db.Database.ExchangeOption)

Example 23 with JsonApiOutput

use of com.bluenimble.platform.api.impls.JsonApiOutput in project serverless by bluenimble.

the class QueryEntitySpi method execute.

@Override
public ApiOutput execute(Api api, final ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
    String provider = (String) request.get(CommonSpec.Provider);
    String sEntity = (String) request.get(CommonSpec.Entity);
    String serializer = (String) request.get(CommonSpec.Serializer);
    String[] levels = Lang.split(serializer, Lang.COMMA);
    int allStopLevel = 2;
    if (levels != null && levels.length > 0) {
        try {
            allStopLevel = Integer.valueOf(levels[0]);
        } catch (Exception ex) {
        }
    }
    int minStopLevel = 3;
    if (levels != null && levels.length > 0) {
        try {
            minStopLevel = Integer.valueOf(levels[1]);
        } catch (Exception ex) {
        }
    }
    JsonObject payload = (JsonObject) request.get(ApiRequest.Payload);
    payload.set(Database.Fields.Entity, sEntity);
    ApiSpace space;
    try {
        space = MgmUtils.space(consumer, api);
    } catch (ApiAccessDeniedException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e).status(ApiResponse.FORBIDDEN);
    }
    List<DatabaseObject> records = null;
    try {
        Database db = space.feature(Database.class, provider, request);
        records = db.find(null, new JsonQuery(payload), null);
    } catch (DatabaseException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    }
    JsonObject result = new JsonObject();
    JsonArray aRecords = new JsonArray();
    result.set(Output.Records, aRecords);
    if (records == null || records.isEmpty()) {
        return new JsonApiOutput(result);
    }
    for (int i = 0; i < records.size(); i++) {
        aRecords.add(records.get(i).toJson(new DefaultDatabaseObjectSerializer(allStopLevel, minStopLevel)));
    }
    return new JsonApiOutput(result);
}
Also used : JsonQuery(com.bluenimble.platform.db.query.impls.JsonQuery) JsonObject(com.bluenimble.platform.json.JsonObject) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) ApiAccessDeniedException(com.bluenimble.platform.api.ApiAccessDeniedException) DatabaseException(com.bluenimble.platform.db.DatabaseException) JsonArray(com.bluenimble.platform.json.JsonArray) ApiAccessDeniedException(com.bluenimble.platform.api.ApiAccessDeniedException) DefaultDatabaseObjectSerializer(com.bluenimble.platform.db.impls.DefaultDatabaseObjectSerializer) ApiSpace(com.bluenimble.platform.api.ApiSpace) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) Database(com.bluenimble.platform.db.Database) DatabaseObject(com.bluenimble.platform.db.DatabaseObject) DatabaseException(com.bluenimble.platform.db.DatabaseException) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput)

Example 24 with JsonApiOutput

use of com.bluenimble.platform.api.impls.JsonApiOutput in project serverless by bluenimble.

the class CreateKeysSpi method execute.

@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
    JsonObject payload = (JsonObject) request.get(ApiRequest.Payload);
    Role cRole = Role.valueOf((String) consumer.get(CommonSpec.Role));
    Role role = Role.SUPER.equals(cRole) ? Role.ADMIN : Role.DEVELOPER;
    String sRole = Json.getString(payload, CommonSpec.Role);
    if (!Lang.isNullOrEmpty(sRole)) {
        try {
            role = Role.valueOf(sRole.trim().toUpperCase());
        } catch (Exception ex) {
        // undefined role
        }
    }
    if (Role.SUPER.equals(cRole) && role.equals(Role.DEVELOPER)) {
        throw new ApiServiceExecutionException("super users can't create developer keys").status(ApiResponse.FORBIDDEN);
    }
    if (Role.ADMIN.equals(cRole) && role.equals(Role.ADMIN)) {
        throw new ApiServiceExecutionException("admin users can't create admin keys").status(ApiResponse.FORBIDDEN);
    }
    ApiSpace space;
    if (Role.SUPER.equals(cRole)) {
        String spaceNs = Json.getString(payload, Spec.Space);
        if (Lang.isNullOrEmpty(spaceNs)) {
            throw new ApiServiceExecutionException("no space found in payload").status(ApiResponse.BAD_REQUEST);
        }
        try {
            space = api.space().space(spaceNs);
        } catch (ApiAccessDeniedException e) {
            throw new ApiServiceExecutionException(e.getMessage(), e).status(ApiResponse.FORBIDDEN);
        }
    } else {
        try {
            space = MgmUtils.space(consumer, api);
        } catch (ApiAccessDeniedException e) {
            throw new ApiServiceExecutionException(e.getMessage(), e).status(ApiResponse.FORBIDDEN);
        }
    }
    if (space == null) {
        throw new ApiServiceExecutionException("target space where to create the keys isn't found").status(ApiResponse.BAD_REQUEST);
    }
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(CommonSpec.Role, role.name());
    Date expiryDate = null;
    if (!Json.isNullOrEmpty(payload)) {
        expiryDate = (Date) payload.get(KeyPair.Fields.ExpiryDate);
        Iterator<String> props = payload.keys();
        while (props.hasNext()) {
            String p = props.next();
            if (Exclude.contains(p)) {
                continue;
            }
            properties.put(p, payload.get(p));
        }
    }
    List<KeyPair> list = null;
    try {
        list = space.keystore().create(1, expiryDate, properties);
    } catch (SpaceKeyStoreException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e).status(ApiResponse.BAD_REQUEST);
    }
    if (list == null) {
        return new JsonApiOutput(null);
    }
    return new JsonApiOutput(list.get(0).toJson());
}
Also used : KeyPair(com.bluenimble.platform.security.KeyPair) HashMap(java.util.HashMap) JsonObject(com.bluenimble.platform.json.JsonObject) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) ApiAccessDeniedException(com.bluenimble.platform.api.ApiAccessDeniedException) SpaceKeyStoreException(com.bluenimble.platform.security.SpaceKeyStoreException) Date(java.util.Date) Role(com.bluenimble.platform.apis.mgm.Role) ApiAccessDeniedException(com.bluenimble.platform.api.ApiAccessDeniedException) ApiSpace(com.bluenimble.platform.api.ApiSpace) SpaceKeyStoreException(com.bluenimble.platform.security.SpaceKeyStoreException) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) JsonObject(com.bluenimble.platform.json.JsonObject) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput)

Example 25 with JsonApiOutput

use of com.bluenimble.platform.api.impls.JsonApiOutput in project serverless by bluenimble.

the class ListKeysSpi method execute.

@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
    Role cRole = Role.valueOf((String) consumer.get(CommonSpec.Role));
    int offset = (Integer) request.get(Spec.Offset);
    int length = (Integer) request.get(Spec.Length);
    String sFilters = (String) request.get(Spec.Filters);
    SpaceKeyStore.ListFilter[] filters = null;
    if (!Lang.isNullOrEmpty(sFilters)) {
        String[] aFilters = Lang.split(sFilters, Lang.COMMA, true);
        filters = new SpaceKeyStore.ListFilter[aFilters.length + 1];
        for (int i = 0; i < aFilters.length; i++) {
            String f = aFilters[i];
            int idexOfStartUnderscore = f.indexOf(Token);
            if (idexOfStartUnderscore < -1) {
                continue;
            }
            int idexOfEndUnderscore = f.indexOf(Token, idexOfStartUnderscore + 2);
            if (idexOfEndUnderscore < -1) {
                continue;
            }
            filters[i] = new SpaceKeyStore.ListFilter() {

                @Override
                public String name() {
                    return f.substring(0, idexOfStartUnderscore);
                }

                @Override
                public Object value() {
                    String value = f.substring(idexOfEndUnderscore + 2);
                    if (Lang.isNullOrEmpty(value)) {
                        return null;
                    }
                    return value;
                }

                @Override
                public Operator operator() {
                    try {
                        return Operator.valueOf(f.substring(idexOfStartUnderscore + 2, idexOfEndUnderscore));
                    } catch (Exception ex) {
                        return Operator.eq;
                    }
                }
            };
        }
    } else {
        filters = new SpaceKeyStore.ListFilter[1];
    }
    JsonObject result = new JsonObject();
    JsonArray aKeys = new JsonArray();
    result.set(Output.Keys, aKeys);
    if (Role.SUPER.equals(cRole)) {
        filters[filters.length - 1] = new SpaceKeyStore.ListFilter() {

            @Override
            public String name() {
                return CommonSpec.Role;
            }

            @Override
            public Object value() {
                return Role.ADMIN.name();
            }

            @Override
            public Operator operator() {
                return Operator.eq;
            }
        };
        try {
            Collection<ApiSpace> spaces = api.space().spaces();
            for (ApiSpace space : spaces) {
                addSpaceKeys(space, offset, length, filters, aKeys);
            }
        } catch (ApiAccessDeniedException e) {
            throw new ApiServiceExecutionException(e.getMessage(), e).status(ApiResponse.NOT_FOUND);
        }
    } else {
        filters[filters.length - 1] = new SpaceKeyStore.ListFilter() {

            @Override
            public String name() {
                return CommonSpec.Role;
            }

            @Override
            public Object value() {
                return Role.DEVELOPER.name();
            }

            @Override
            public Operator operator() {
                return Operator.eq;
            }
        };
        ApiSpace consumerSpace;
        try {
            consumerSpace = MgmUtils.space(consumer, api);
        } catch (ApiAccessDeniedException e) {
            throw new ApiServiceExecutionException(e.getMessage(), e).status(ApiResponse.NOT_FOUND);
        }
        addSpaceKeys(consumerSpace, offset, length, filters, aKeys);
    }
    return new JsonApiOutput(result);
}
Also used : JsonObject(com.bluenimble.platform.json.JsonObject) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) ApiAccessDeniedException(com.bluenimble.platform.api.ApiAccessDeniedException) Role(com.bluenimble.platform.apis.mgm.Role) JsonArray(com.bluenimble.platform.json.JsonArray) ApiAccessDeniedException(com.bluenimble.platform.api.ApiAccessDeniedException) ApiSpace(com.bluenimble.platform.api.ApiSpace) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) SpaceKeyStore(com.bluenimble.platform.security.SpaceKeyStore) JsonObject(com.bluenimble.platform.json.JsonObject) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput)

Aggregations

ApiServiceExecutionException (com.bluenimble.platform.api.ApiServiceExecutionException)39 JsonApiOutput (com.bluenimble.platform.api.impls.JsonApiOutput)39 JsonObject (com.bluenimble.platform.json.JsonObject)34 ApiSpace (com.bluenimble.platform.api.ApiSpace)27 ApiAccessDeniedException (com.bluenimble.platform.api.ApiAccessDeniedException)25 Database (com.bluenimble.platform.db.Database)13 DatabaseObject (com.bluenimble.platform.db.DatabaseObject)9 DatabaseException (com.bluenimble.platform.db.DatabaseException)8 ApiOutput (com.bluenimble.platform.api.ApiOutput)7 Api (com.bluenimble.platform.api.Api)6 Storage (com.bluenimble.platform.storage.Storage)6 StorageException (com.bluenimble.platform.storage.StorageException)6 StorageObject (com.bluenimble.platform.storage.StorageObject)6 JsonArray (com.bluenimble.platform.json.JsonArray)5 ApiStreamSource (com.bluenimble.platform.api.ApiStreamSource)4 JsonQuery (com.bluenimble.platform.db.query.impls.JsonQuery)4 Date (java.util.Date)4 ApiManagementException (com.bluenimble.platform.api.ApiManagementException)3 Config (com.bluenimble.platform.api.impls.im.LoginServiceSpi.Config)3 Cache (com.bluenimble.platform.cache.Cache)3