{"size": 1804, "ext": "js", "max_stars_repo_path": "lib/cli-api/_b2cAuthBMUser.js", "max_stars_repo_name": "gabrielrodriguesrocha/b2c-crm-sync", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/cli-api/_b2cAuthBMUser.js", "max_issues_repo_name": "gabrielrodriguesrocha/b2c-crm-sync", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/cli-api/_b2cAuthBMUser.js", "max_forks_repo_name": "gabrielrodriguesrocha/b2c-crm-sync", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.1875, "max_line_length": 121, "alphanum_fraction": 0.6319290466}
'use strict';

// Initialize constants
const config = require('config');

// Include B2C Commerce API functions
const b2cAuthBMUser = require('../apis/sfcc/ocapi/auth/_bmUserGrant');

/**
 * @function _b2cAuthBMUserGrant
 * @description Attempts to authenticate against the B2C Commerce instance using BM User credentials --
 * and returns the results of the request via the CLI.
 *
 * @param {Object} environmentDef Represents the already-validated environment details to use when performing the actions
 *
 * @returns {Promise}
 */
module.exports = environmentDef => new Promise(async (resolve, reject) => {

    // Initialize the output
    const output = {
        apiCalls: {
            authenticate: {}
        },
        outputDisplay: {}
    };

    try {

        // Execute the BM User authentication attempt
        output.apiCalls.authenticate = await b2cAuthBMUser(environmentDef);

        // Was an authentication error caught?
        if (output.apiCalls.authenticate.status !== 200) {

            // Capture the error message
            output.success = false;

            // Build the output display
            output.outputDisplay = [
                ['errorType', output.apiCalls.authenticate.data.error],
                ['errorMessage', output.apiCalls.authenticate.data.error_description]
            ];

        } else {

            // Capture the authToken and build out the display details
            output.authToken = output.apiCalls.authenticate.data.access_token;
            output.success = true;

            // Build the output display
            output.outputDisplay = [output.apiCalls.authenticate.data.access_token];
        }

        resolve(output);

    } catch (e) {

        reject(`${config.get('errors.b2c.unableToAuthenticate')}: ${e}`);

    }

});
