All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.bandwidth.multifactorauth.controllers.MFAController Maven / Gradle / Ivy

Go to download

The official client SDK for Bandwidth's Voice, Messaging, MFA, and WebRTC APIs

There is a newer version: 12.0.0
Show newest version
/*
 * BandwidthLib
 *
 * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ).
 */

package com.bandwidth.multifactorauth.controllers;

import com.bandwidth.ApiHelper;
import com.bandwidth.AuthManager;
import com.bandwidth.Configuration;
import com.bandwidth.Server;
import com.bandwidth.controllers.BaseController;
import com.bandwidth.exceptions.ApiException;
import com.bandwidth.http.Headers;
import com.bandwidth.http.client.HttpCallback;
import com.bandwidth.http.client.HttpClient;
import com.bandwidth.http.client.HttpContext;
import com.bandwidth.http.request.HttpRequest;
import com.bandwidth.http.response.ApiResponse;
import com.bandwidth.http.response.HttpResponse;
import com.bandwidth.http.response.HttpStringResponse;
import com.bandwidth.multifactorauth.exceptions.ErrorWithRequestException;
import com.bandwidth.multifactorauth.exceptions.ForbiddenRequestException;
import com.bandwidth.multifactorauth.exceptions.UnauthorizedRequestException;
import com.bandwidth.multifactorauth.models.TwoFactorCodeRequestSchema;
import com.bandwidth.multifactorauth.models.TwoFactorMessagingResponse;
import com.bandwidth.multifactorauth.models.TwoFactorVerifyCodeResponse;
import com.bandwidth.multifactorauth.models.TwoFactorVerifyRequestSchema;
import com.bandwidth.multifactorauth.models.TwoFactorVoiceResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.io.IOException;
import java.util.AbstractMap.SimpleEntry;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * This class lists all the endpoints of the groups.
 */
public final class MFAController extends BaseController {

    /**
     * Initializes the controller.
     * @param config    Configurations added in client.
     * @param httpClient    Send HTTP requests and read the responses.
     * @param authManagers    Apply authorization to requests.
     */
    public MFAController(Configuration config, HttpClient httpClient,
            Map authManagers) {
        super(config, httpClient, authManagers);
    }

    /**
     * Initializes the controller with HTTPCallback.
     * @param config    Configurations added in client.
     * @param httpClient    Send HTTP requests and read the responses.
     * @param authManagers    Apply authorization to requests.
     * @param httpCallback    Callback to be called before and after the HTTP call.
     */
    public MFAController(Configuration config, HttpClient httpClient,
            Map authManagers, HttpCallback httpCallback) {
        super(config, httpClient, authManagers, httpCallback);
    }

    /**
     * Multi-Factor authentication with Bandwidth Voice services. Allows for a user to send an MFA
     * code via a phone call.
     * @param  accountId  Required parameter: Bandwidth Account ID with Voice service enabled
     * @param  body  Required parameter: Example:
     * @return    Returns the TwoFactorVoiceResponse wrapped in ApiResponse response from the API call
     * @throws    ApiException    Represents error response from the server.
     * @throws    IOException    Signals that an I/O exception of some sort has occurred.
     */
    public ApiResponse createVoiceTwoFactor(
            final String accountId,
            final TwoFactorCodeRequestSchema body) throws ApiException, IOException {
        HttpRequest request = buildCreateVoiceTwoFactorRequest(accountId, body);
        authManagers.get("multiFactorAuth").apply(request);

        HttpResponse response = getClientInstance().execute(request, false);
        HttpContext context = new HttpContext(request, response);

        return handleCreateVoiceTwoFactorResponse(context);
    }

    /**
     * Multi-Factor authentication with Bandwidth Voice services. Allows for a user to send an MFA
     * code via a phone call.
     * @param  accountId  Required parameter: Bandwidth Account ID with Voice service enabled
     * @param  body  Required parameter: Example:
     * @return    Returns the TwoFactorVoiceResponse wrapped in ApiResponse response from the API call
     */
    public CompletableFuture> createVoiceTwoFactorAsync(
            final String accountId,
            final TwoFactorCodeRequestSchema body) {
        return makeHttpCallAsync(() -> buildCreateVoiceTwoFactorRequest(accountId, body),
            req -> authManagers.get("multiFactorAuth").applyAsync(req)
                .thenCompose(request -> getClientInstance()
                        .executeAsync(request, false)),
            context -> handleCreateVoiceTwoFactorResponse(context));
    }

    /**
     * Builds the HttpRequest object for createVoiceTwoFactor.
     */
    private HttpRequest buildCreateVoiceTwoFactorRequest(
            final String accountId,
            final TwoFactorCodeRequestSchema body) throws JsonProcessingException {
        //the base uri for api requests
        String baseUri = config.getBaseUri(Server.MULTIFACTORAUTHDEFAULT);

        //prepare query string for API call
        final StringBuilder queryBuilder = new StringBuilder(baseUri
                + "/accounts/{accountId}/code/voice");

        //process template parameters
        Map> templateParameters = new HashMap<>();
        templateParameters.put("accountId",
                new SimpleEntry(accountId, false));
        ApiHelper.appendUrlWithTemplateParameters(queryBuilder, templateParameters);

        //load all headers for the outgoing API request
        Headers headers = new Headers();
        headers.add("user-agent", BaseController.userAgent);
        headers.add("accept", "application/json");
        headers.add("content-type", "application/json");

        //prepare and invoke the API call request to fetch the response
        String bodyJson = ApiHelper.serialize(body);
        HttpRequest request = getClientInstance().postBody(queryBuilder, headers, null, bodyJson);

        // Invoke the callback before request if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onBeforeRequest(request);
        }

        return request;
    }

    /**
     * Processes the response for createVoiceTwoFactor.
     * @return An object of type TwoFactorVoiceResponse
     */
    private ApiResponse handleCreateVoiceTwoFactorResponse(
            HttpContext context) throws ApiException, IOException {
        HttpResponse response = context.getResponse();

        //invoke the callback after response if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onAfterResponse(context);
        }

        //Error handling using HTTP status codes
        int responseCode = response.getStatusCode();

        if (responseCode == 400) {
            throw new ErrorWithRequestException(
                    "If there is any issue with values passed in by the user", context);
        }
        if (responseCode == 401) {
            throw new UnauthorizedRequestException(
                    "Authentication is either incorrect or not present", context);
        }
        if (responseCode == 403) {
            throw new ForbiddenRequestException(
                    "The user is not authorized to access this resource", context);
        }
        if (responseCode == 500) {
            throw new ErrorWithRequestException("An internal server error occurred", context);
        }
        //handle errors defined at the API level
        validateResponse(response, context);

        //extract result from the http response
        String responseBody = ((HttpStringResponse) response).getBody();
        TwoFactorVoiceResponse result = ApiHelper.deserialize(responseBody,
                TwoFactorVoiceResponse.class);

        return new ApiResponse(response.getStatusCode(), response.getHeaders(), result);
    }

    /**
     * Multi-Factor authentication with Bandwidth Messaging services. Allows a user to send an MFA
     * code via a text message (SMS).
     * @param  accountId  Required parameter: Bandwidth Account ID with Messaging service enabled
     * @param  body  Required parameter: Example:
     * @return    Returns the TwoFactorMessagingResponse wrapped in ApiResponse response from the API call
     * @throws    ApiException    Represents error response from the server.
     * @throws    IOException    Signals that an I/O exception of some sort has occurred.
     */
    public ApiResponse createMessagingTwoFactor(
            final String accountId,
            final TwoFactorCodeRequestSchema body) throws ApiException, IOException {
        HttpRequest request = buildCreateMessagingTwoFactorRequest(accountId, body);
        authManagers.get("multiFactorAuth").apply(request);

        HttpResponse response = getClientInstance().execute(request, false);
        HttpContext context = new HttpContext(request, response);

        return handleCreateMessagingTwoFactorResponse(context);
    }

    /**
     * Multi-Factor authentication with Bandwidth Messaging services. Allows a user to send an MFA
     * code via a text message (SMS).
     * @param  accountId  Required parameter: Bandwidth Account ID with Messaging service enabled
     * @param  body  Required parameter: Example:
     * @return    Returns the TwoFactorMessagingResponse wrapped in ApiResponse response from the API call
     */
    public CompletableFuture> createMessagingTwoFactorAsync(
            final String accountId,
            final TwoFactorCodeRequestSchema body) {
        return makeHttpCallAsync(() -> buildCreateMessagingTwoFactorRequest(accountId, body),
            req -> authManagers.get("multiFactorAuth").applyAsync(req)
                .thenCompose(request -> getClientInstance()
                        .executeAsync(request, false)),
            context -> handleCreateMessagingTwoFactorResponse(context));
    }

    /**
     * Builds the HttpRequest object for createMessagingTwoFactor.
     */
    private HttpRequest buildCreateMessagingTwoFactorRequest(
            final String accountId,
            final TwoFactorCodeRequestSchema body) throws JsonProcessingException {
        //the base uri for api requests
        String baseUri = config.getBaseUri(Server.MULTIFACTORAUTHDEFAULT);

        //prepare query string for API call
        final StringBuilder queryBuilder = new StringBuilder(baseUri
                + "/accounts/{accountId}/code/messaging");

        //process template parameters
        Map> templateParameters = new HashMap<>();
        templateParameters.put("accountId",
                new SimpleEntry(accountId, false));
        ApiHelper.appendUrlWithTemplateParameters(queryBuilder, templateParameters);

        //load all headers for the outgoing API request
        Headers headers = new Headers();
        headers.add("user-agent", BaseController.userAgent);
        headers.add("accept", "application/json");
        headers.add("content-type", "application/json");

        //prepare and invoke the API call request to fetch the response
        String bodyJson = ApiHelper.serialize(body);
        HttpRequest request = getClientInstance().postBody(queryBuilder, headers, null, bodyJson);

        // Invoke the callback before request if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onBeforeRequest(request);
        }

        return request;
    }

    /**
     * Processes the response for createMessagingTwoFactor.
     * @return An object of type TwoFactorMessagingResponse
     */
    private ApiResponse handleCreateMessagingTwoFactorResponse(
            HttpContext context) throws ApiException, IOException {
        HttpResponse response = context.getResponse();

        //invoke the callback after response if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onAfterResponse(context);
        }

        //Error handling using HTTP status codes
        int responseCode = response.getStatusCode();

        if (responseCode == 400) {
            throw new ErrorWithRequestException(
                    "If there is any issue with values passed in by the user", context);
        }
        if (responseCode == 401) {
            throw new UnauthorizedRequestException(
                    "Authentication is either incorrect or not present", context);
        }
        if (responseCode == 403) {
            throw new ForbiddenRequestException(
                    "The user is not authorized to access this resource", context);
        }
        if (responseCode == 500) {
            throw new ErrorWithRequestException("An internal server error occurred", context);
        }
        //handle errors defined at the API level
        validateResponse(response, context);

        //extract result from the http response
        String responseBody = ((HttpStringResponse) response).getBody();
        TwoFactorMessagingResponse result = ApiHelper.deserialize(responseBody,
                TwoFactorMessagingResponse.class);

        return new ApiResponse(response.getStatusCode(), response.getHeaders(), result);
    }

    /**
     * Allows a user to verify an MFA code.
     * @param  accountId  Required parameter: Bandwidth Account ID with Two-Factor enabled
     * @param  body  Required parameter: Example:
     * @return    Returns the TwoFactorVerifyCodeResponse wrapped in ApiResponse response from the API call
     * @throws    ApiException    Represents error response from the server.
     * @throws    IOException    Signals that an I/O exception of some sort has occurred.
     */
    public ApiResponse createVerifyTwoFactor(
            final String accountId,
            final TwoFactorVerifyRequestSchema body) throws ApiException, IOException {
        HttpRequest request = buildCreateVerifyTwoFactorRequest(accountId, body);
        authManagers.get("multiFactorAuth").apply(request);

        HttpResponse response = getClientInstance().execute(request, false);
        HttpContext context = new HttpContext(request, response);

        return handleCreateVerifyTwoFactorResponse(context);
    }

    /**
     * Allows a user to verify an MFA code.
     * @param  accountId  Required parameter: Bandwidth Account ID with Two-Factor enabled
     * @param  body  Required parameter: Example:
     * @return    Returns the TwoFactorVerifyCodeResponse wrapped in ApiResponse response from the API call
     */
    public CompletableFuture> createVerifyTwoFactorAsync(
            final String accountId,
            final TwoFactorVerifyRequestSchema body) {
        return makeHttpCallAsync(() -> buildCreateVerifyTwoFactorRequest(accountId, body),
            req -> authManagers.get("multiFactorAuth").applyAsync(req)
                .thenCompose(request -> getClientInstance()
                        .executeAsync(request, false)),
            context -> handleCreateVerifyTwoFactorResponse(context));
    }

    /**
     * Builds the HttpRequest object for createVerifyTwoFactor.
     */
    private HttpRequest buildCreateVerifyTwoFactorRequest(
            final String accountId,
            final TwoFactorVerifyRequestSchema body) throws JsonProcessingException {
        //the base uri for api requests
        String baseUri = config.getBaseUri(Server.MULTIFACTORAUTHDEFAULT);

        //prepare query string for API call
        final StringBuilder queryBuilder = new StringBuilder(baseUri
                + "/accounts/{accountId}/code/verify");

        //process template parameters
        Map> templateParameters = new HashMap<>();
        templateParameters.put("accountId",
                new SimpleEntry(accountId, false));
        ApiHelper.appendUrlWithTemplateParameters(queryBuilder, templateParameters);

        //load all headers for the outgoing API request
        Headers headers = new Headers();
        headers.add("user-agent", BaseController.userAgent);
        headers.add("accept", "application/json");
        headers.add("content-type", "application/json");

        //prepare and invoke the API call request to fetch the response
        String bodyJson = ApiHelper.serialize(body);
        HttpRequest request = getClientInstance().postBody(queryBuilder, headers, null, bodyJson);

        // Invoke the callback before request if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onBeforeRequest(request);
        }

        return request;
    }

    /**
     * Processes the response for createVerifyTwoFactor.
     * @return An object of type TwoFactorVerifyCodeResponse
     */
    private ApiResponse handleCreateVerifyTwoFactorResponse(
            HttpContext context) throws ApiException, IOException {
        HttpResponse response = context.getResponse();

        //invoke the callback after response if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onAfterResponse(context);
        }

        //Error handling using HTTP status codes
        int responseCode = response.getStatusCode();

        if (responseCode == 400) {
            throw new ErrorWithRequestException(
                    "If there is any issue with values passed in by the user", context);
        }
        if (responseCode == 401) {
            throw new UnauthorizedRequestException(
                    "Authentication is either incorrect or not present", context);
        }
        if (responseCode == 403) {
            throw new ForbiddenRequestException(
                    "The user is not authorized to access this resource", context);
        }
        if (responseCode == 429) {
            throw new ErrorWithRequestException(
                    "The user has made too many bad requests and is temporarily locked out",
                    context);
        }
        if (responseCode == 500) {
            throw new ErrorWithRequestException("An internal server error occurred", context);
        }
        //handle errors defined at the API level
        validateResponse(response, context);

        //extract result from the http response
        String responseBody = ((HttpStringResponse) response).getBody();
        TwoFactorVerifyCodeResponse result = ApiHelper.deserialize(responseBody,
                TwoFactorVerifyCodeResponse.class);

        return new ApiResponse(response.getStatusCode(), response.getHeaders(), result);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy