Search in sources :

Example 26 with ApiServiceExecutionException

use of com.bluenimble.platform.api.ApiServiceExecutionException in project serverless by bluenimble.

the class OAuthServiceSpi method execute.

@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
    JsonObject config = request.getService().getCustom();
    JsonObject providers = Json.getObject(config, Providers);
    JsonObject provider = Json.getObject(providers, (String) request.get(Spec.Provider));
    if (provider == null || provider.isEmpty()) {
        throw new ApiServiceExecutionException("provider " + request.get(Spec.Provider) + " not supported").status(ApiResponse.NOT_ACCEPTABLE);
    }
    JsonObject oAuthKeys = Json.getObject(provider, OAuth.Keys);
    if (oAuthKeys == null || oAuthKeys.isEmpty()) {
        throw new ApiServiceExecutionException("provider " + request.get(Spec.Provider) + ". client_id and client_secret not found").status(ApiResponse.NOT_ACCEPTABLE);
    }
    JsonObject oAuthEndpoints = Json.getObject(provider, OAuth.Endpoints);
    if (oAuthEndpoints == null || oAuthEndpoints.isEmpty()) {
        throw new ApiServiceExecutionException("provider " + request.get(Spec.Provider) + ". oAuth endpoints authorize and profile not configured").status(ApiResponse.NOT_ACCEPTABLE);
    }
    JsonObject endpoint = Json.getObject(oAuthEndpoints, OAuth.Urls.Authorize);
    if (endpoint == null || endpoint.isEmpty()) {
        throw new ApiServiceExecutionException("provider " + request.get(Spec.Provider) + ". oAuth authorize endpoint not configured").status(ApiResponse.NOT_ACCEPTABLE);
    }
    JsonObject data = (JsonObject) new JsonObject().set(OAuth.Code, request.get(Spec.AuthCode)).set(OAuth.ClientId, Json.getString(oAuthKeys, OAuth.ClientId)).set(OAuth.ClientSecret, Json.getString(oAuthKeys, OAuth.ClientSecret));
    if (provider.containsKey(OAuth.Redirect)) {
        data.set(OAuth.RedirectUri, Json.getString(provider, OAuth.Redirect));
    }
    JsonObject params = Json.getObject(endpoint, OAuth.Endpoint.Parameters);
    if (params != null && !params.isEmpty()) {
        Iterator<String> keys = params.keys();
        while (keys.hasNext()) {
            String p = keys.next();
            data.set(p, params.get(p));
        }
    }
    JsonObject hRequest = (JsonObject) new JsonObject().set(OAuth.Endpoint.Url, Json.getString(endpoint, OAuth.Endpoint.Url)).set(OAuth.Endpoint.Headers, new JsonObject().set(HttpHeaders.ACCEPT, ContentTypes.Json)).set(OAuth.Endpoint.Data, data);
    HttpResponse hResponse = null;
    try {
        hResponse = Http.post(hRequest, null);
    } catch (HttpClientException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    }
    if (hResponse.getStatus() != 200) {
        throw new ApiServiceExecutionException("invalid authorization code");
    }
    InputStream out = hResponse.getBody().get(0).toInputStream();
    JsonObject oAuthResult = null;
    try {
        oAuthResult = new JsonObject(out);
    } catch (Exception e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    // get profile
    endpoint = Json.getObject(oAuthEndpoints, OAuth.Urls.Profile);
    if (endpoint == null || endpoint.isEmpty()) {
        return new JsonApiOutput(oAuthResult);
    }
    String accessToken = Json.getString(oAuthResult, OAuth.AccessToken);
    data.clear();
    data.set(OAuth.AccessToken, accessToken);
    hRequest = (JsonObject) new JsonObject().set(OAuth.Endpoint.Url, Json.getString(endpoint, OAuth.Endpoint.Url)).set(OAuth.Endpoint.Headers, new JsonObject().set(HttpHeaders.ACCEPT, ContentTypes.Json)).set(OAuth.Endpoint.Data, data);
    try {
        hResponse = Http.post(hRequest, null);
    } catch (HttpClientException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    }
    if (hResponse.getStatus() != 200) {
        throw new ApiServiceExecutionException("invalid access token");
    }
    out = hResponse.getBody().get(0).toInputStream();
    try {
        oAuthResult = new JsonObject(out);
    } catch (Exception e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    // email endpoint
    endpoint = Json.getObject(oAuthEndpoints, OAuth.Urls.Email);
    if (endpoint == null || endpoint.isEmpty()) {
        return new JsonApiOutput(oAuthResult);
    }
    hRequest = (JsonObject) new JsonObject().set(OAuth.Endpoint.Url, Json.getString(endpoint, OAuth.Endpoint.Url)).set(OAuth.Endpoint.Headers, new JsonObject().set(HttpHeaders.ACCEPT, ContentTypes.Json)).set(OAuth.Endpoint.Data, data);
    try {
        hResponse = Http.post(hRequest, null);
    } catch (HttpClientException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    }
    if (hResponse.getStatus() != 200) {
        throw new ApiServiceExecutionException("invalid access token");
    }
    out = hResponse.getBody().get(0).toInputStream();
    JsonObject oEmail = null;
    try {
        oEmail = new JsonObject(out);
    } catch (Exception e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    Iterator<String> keys = oEmail.keys();
    while (keys.hasNext()) {
        String k = keys.next();
        oAuthResult.set(k, oEmail.get(k));
    }
    // call extend if any
    JsonObject onFinish = Json.getObject(config, Config.onFinish.class.getSimpleName());
    ApiOutput onFinishOutput = SecurityUtils.onFinish(api, consumer, request, onFinish, oAuthResult);
    if (onFinishOutput != null) {
        oAuthResult.set(Json.getString(onFinish, Config.onFinish.ResultProperty, Config.onFinish.class.getSimpleName()), onFinishOutput.data());
    }
    return new JsonApiOutput(oAuthResult);
}
Also used : HttpClientException(com.bluenimble.platform.http.HttpClientException) ApiOutput(com.bluenimble.platform.api.ApiOutput) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) InputStream(java.io.InputStream) Config(com.bluenimble.platform.api.impls.im.LoginServiceSpi.Config) JsonObject(com.bluenimble.platform.json.JsonObject) HttpResponse(com.bluenimble.platform.http.response.HttpResponse) HttpClientException(com.bluenimble.platform.http.HttpClientException) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput)

Example 27 with ApiServiceExecutionException

use of com.bluenimble.platform.api.ApiServiceExecutionException in project serverless by bluenimble.

the class ResendActivationRequestSpi method execute.

@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
    JsonObject config = request.getService().getCustom();
    Database db = api.space().feature(Database.class, Json.getString(config, Config.Database, ApiSpace.Features.Default), request);
    DatabaseObject account = null;
    try {
        account = db.get(Json.getString(config, Config.UsersEntity, Defaults.Users), (String) consumer.get(ApiConsumer.Fields.Id));
    } catch (Exception ex) {
        throw new ApiServiceExecutionException(ex.getMessage(), ex);
    }
    if (account == null) {
        throw new ApiServiceExecutionException("account not found").status(ApiResponse.NOT_FOUND);
    }
    String email = (String) account.get(Json.getString(config, Config.UserProperty, Fields.Email));
    if (Lang.isNullOrEmpty(email)) {
        throw new ApiServiceExecutionException("user email not found").status(ApiResponse.NOT_FOUND);
    }
    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);
        }
    }
    return new JsonApiOutput(JsonObject.Blank);
}
Also used : 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) JsonSender(com.bluenimble.platform.messaging.impls.JsonSender) 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 28 with ApiServiceExecutionException

use of com.bluenimble.platform.api.ApiServiceExecutionException 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 29 with ApiServiceExecutionException

use of com.bluenimble.platform.api.ApiServiceExecutionException in project serverless by bluenimble.

the class SecurityUtils method onFinish.

public static ApiOutput onFinish(Api api, ApiConsumer consumer, ApiRequest pRequest, final JsonObject onFinish, JsonObject account) throws ApiServiceExecutionException {
    if (onFinish == null || onFinish.isEmpty()) {
        return null;
    }
    ApiRequest request = api.space().request(pRequest, consumer, new Endpoint() {

        @Override
        public String space() {
            return Json.getString(onFinish, Config.onFinish.Space, api.space().getNamespace());
        }

        @Override
        public String api() {
            return Json.getString(onFinish, Config.onFinish.Api, api.getNamespace());
        }

        @Override
        public String[] resource() {
            String resource = Json.getString(onFinish, Config.onFinish.Resource);
            if (resource.startsWith(Lang.SLASH)) {
                resource = resource.substring(1);
            }
            if (resource.endsWith(Lang.SLASH)) {
                resource = resource.substring(0, resource.length() - 1);
            }
            if (Lang.isNullOrEmpty(resource)) {
                return null;
            }
            return Lang.split(resource, Lang.SLASH);
        }

        @Override
        public ApiVerb verb() {
            try {
                return ApiVerb.valueOf(Json.getString(onFinish, Config.onFinish.Verb, ApiVerb.POST.name()).toUpperCase());
            } catch (Exception ex) {
                return ApiVerb.POST;
            }
        }
    });
    request.set(ApiRequest.Payload, account);
    return api.call(request);
}
Also used : Endpoint(com.bluenimble.platform.api.ApiSpace.Endpoint) ApiRequest(com.bluenimble.platform.api.ApiRequest) ApiVerb(com.bluenimble.platform.api.ApiVerb) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) ApiManagementException(com.bluenimble.platform.api.ApiManagementException)

Example 30 with ApiServiceExecutionException

use of com.bluenimble.platform.api.ApiServiceExecutionException in project serverless by bluenimble.

the class SecurityUtils method tokenAndExpiration.

public static String[] tokenAndExpiration(Api api, JsonObject entity, Date now) throws ApiServiceExecutionException {
    String thing = salt(api, entity);
    JsonObject auth = Json.getObject(Json.getObject(Json.getObject(api.getSecurity(), Api.Spec.Security.Schemes), Schemes.Token), Api.Spec.Security.Auth);
    if (auth == null) {
        auth = Json.getObject(Json.getObject(Json.getObject(api.getSecurity(), Api.Spec.Security.Schemes), Schemes.Cookie), Api.Spec.Security.Auth);
    }
    String secretsName = Json.getString(auth, ApiSpace.Spec.secrets.class.getSimpleName(), ApiSpace.Secrets.Default);
    // encrypt
    JsonObject secrets;
    try {
        secrets = api.space().getSecrets(secretsName);
    } catch (ApiManagementException e) {
        throw new ApiServiceExecutionException(e.getMessage(), e);
    }
    if (secrets == null || !secrets.containsKey(ApiSpace.Spec.secrets.Key)) {
        throw new ApiServiceExecutionException("space secrets '" + secretsName + "' not found").status(ApiResponse.SERVICE_UNAVAILABLE);
    }
    Crypto.Algorithm alg = null;
    try {
        alg = Crypto.Algorithm.valueOf(Json.getString(secrets, ApiSpace.Spec.secrets.Algorithm, Crypto.Algorithm.AES.name()).toUpperCase());
    } catch (Exception ex) {
        alg = Crypto.Algorithm.AES;
    }
    long expiresOn = now.getTime() + Json.getLong(secrets, ApiSpace.Spec.secrets.Age, 60) * 60 * 1000;
    String toEncrypt = expiresOn + Lang.SPACE + thing;
    try {
        return new String[] { new String(Lang.encodeHex(Crypto.encrypt(toEncrypt.getBytes(), Json.getString(secrets, ApiSpace.Spec.secrets.Key), alg))), Lang.toUTC(new Date(expiresOn)) };
    } catch (Exception ex) {
        throw new ApiServiceExecutionException(ex.getMessage(), ex);
    }
}
Also used : Crypto(com.bluenimble.platform.Crypto) ApiSpace(com.bluenimble.platform.api.ApiSpace) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) JsonObject(com.bluenimble.platform.json.JsonObject) ApiManagementException(com.bluenimble.platform.api.ApiManagementException) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) ApiManagementException(com.bluenimble.platform.api.ApiManagementException) Date(java.util.Date)

Aggregations

ApiServiceExecutionException (com.bluenimble.platform.api.ApiServiceExecutionException)52 JsonObject (com.bluenimble.platform.json.JsonObject)41 JsonApiOutput (com.bluenimble.platform.api.impls.JsonApiOutput)39 ApiSpace (com.bluenimble.platform.api.ApiSpace)31 ApiAccessDeniedException (com.bluenimble.platform.api.ApiAccessDeniedException)28 Database (com.bluenimble.platform.db.Database)13 DatabaseObject (com.bluenimble.platform.db.DatabaseObject)9 ApiOutput (com.bluenimble.platform.api.ApiOutput)8 DatabaseException (com.bluenimble.platform.db.DatabaseException)8 Storage (com.bluenimble.platform.storage.Storage)8 StorageException (com.bluenimble.platform.storage.StorageException)8 StorageObject (com.bluenimble.platform.storage.StorageObject)8 Api (com.bluenimble.platform.api.Api)6 ApiManagementException (com.bluenimble.platform.api.ApiManagementException)5 JsonArray (com.bluenimble.platform.json.JsonArray)5 ScriptingEngine (com.bluenimble.platform.scripting.ScriptingEngine)5 ScriptingEngineException (com.bluenimble.platform.scripting.ScriptingEngineException)5 Date (java.util.Date)5 ApiStreamSource (com.bluenimble.platform.api.ApiStreamSource)4 ApiVerb (com.bluenimble.platform.api.ApiVerb)4