"use strict";
var ApiAuthMethodsLegacy_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApiAuthMethodsLegacy = void 0;
const tslib_1 = require("tslib");
const path = require("path");
const inversify_1 = require("inversify");
const axios_1 = require("axios");
const contracts = require("@codiac.io/codiac-common/contracts");
const codiac_common_1 = require("@codiac.io/codiac-common");
const jwt_lib_1 = require("@codiac.io/jwt-lib");
const api_client_base_1 = require("../api-client-base");
const auth_constants_1 = require("./auth-constants");
const token_holder_1 = require("./token-holder");
/** Contains hard-coded Codiac Auth methods.
 * It is considered legacy because it is to be replaced by methods generated from an openApi spec. */
let ApiAuthMethodsLegacy = ApiAuthMethodsLegacy_1 = class ApiAuthMethodsLegacy {
    // /**
    //  * @param apiRootUrl The base url of the api.  That is, prepending it to any individual endpoint route will yield the fully qualified url for that endpoint.
    //  * @param authToken Either a Principal or TenantUser token for the api this client is targeting.  NOTE: Also gets hydrated on successful attempts of authenticate / switchTenant / refreshToken / registerTenant. 
    //  */
    // constructor(logger: IBetterLogger, apiRootUrl?: string, authToken?: string) {
    //   super(logger, apiRootUrl, authToken);
    //   this.tokenHeaderName = ApiClientBaseWithAuth.TOKEN_HEADER_PARAM;  // Right now this is redundant bc this class and the apiClientBase have the same value for tokenHeaderName.  But it's here bc the auth client should explicitly declare it anyway and the base is just a default.
    // }
    constructor(core, logger) {
        this.core = core;
        this.logger = logger;
        this.authConstants = new auth_constants_1.AuthConstants();
        this.tokenHeaderName = ApiAuthMethodsLegacy_1.TOKEN_HEADER_PARAM; // Right now this is redundant bc this class and the apiClientBase have the same value for tokenHeaderName.  But it's here bc this auth client should explicitly declare it anyway and the base is just a default.
    }
    ;
    /** Logs in remotely with the given credentials.
     * Returns a valid token in the headers of the response
     * and the user info in the body of the response.
     * NOTE: If successful, keeps the returned auth token in scope for this client instance.
     * @param login The human readable unique identifier for the user.
     * @param password the secret held for this particular user.
     * @param tenantCode (optional) Unique identifier of the tenant to activate with this authentication.
     */
    authenticate(login, password, tenantCode) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                var _a, _b, _c, _d, _e;
                try {
                    let url = path.posix.join(this.authConstants.ROUTE_PREFIX, this.authConstants.ROUTE_SUBPATH_LOGIN);
                    let req = { login: login, password: password.trim(), tenantCode: tenantCode };
                    let options = {
                        "baseURL": this.core.apiRootUrl,
                        "headers": { "content-type": "application/json" }
                    };
                    // let apiResponse = await axios.post<contracts.SingleResult<TenantUser>>(url, req, options);
                    // let result = this.convertToTokenHolderResponse(apiResponse);
                    let httpResp = yield this.executeAxiosRequest(codiac_common_1.httpRestVerb.POST, (contracts.SingleResult), url, req, options);
                    if (httpResp.data === undefined) {
                        throw new Error(`Authentication request did not return an output object. HttpStatus: ${(_a = httpResp.status) !== null && _a !== void 0 ? _a : ""} ${(_b = httpResp.statusText) !== null && _b !== void 0 ? _b : ""}`);
                    }
                    let result = this.convertToTokenHolderResult(httpResp.data, httpResp.headers);
                    if ((_c = result.output) === null || _c === void 0 ? void 0 : _c.token) {
                        this.core.authToken = result.output.token;
                    }
                    resolve(result);
                }
                catch (err) {
                    let output = new contracts.SingleResult(false, `Error during authenticate: ${(_d = err.name) !== null && _d !== void 0 ? _d : ""} ${(_e = err.message) !== null && _e !== void 0 ? _e : "(no error message available)"}`, err);
                    this.logger.debug(output.message);
                    resolve(output);
                }
            }));
        });
    }
    /** Traps the errors thrown by axios on non-200 statuses. */
    executeAxiosRequest(verb, responseType, url, request, options) {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                let axr;
                switch (verb) {
                    case codiac_common_1.httpRestVerb.POST:
                        axr = yield axios_1.default.post(url, request, options);
                        break;
                    case codiac_common_1.httpRestVerb.PUT:
                        axr = yield axios_1.default.put(url, request, options);
                        break;
                    case codiac_common_1.httpRestVerb.PATCH:
                        axr = yield axios_1.default.patch(url, request, options);
                        break;
                    case codiac_common_1.httpRestVerb.DELETE:
                        axr = yield axios_1.default.delete(url, options);
                        break;
                    default: // GET
                        axr = yield axios_1.default.get(url, options);
                        break;
                }
                let expected = responseType; // <-- just to satisfy TS (we want to infer the generics, dont want the caller to have to explicitly type them)
                return axr; // { data: axr.data, headers: axr.headers, status: axr.status, statusText: axr.statusText };
            }
            catch (err) {
                if (err.isAxiosError === true && err.response) {
                    let axErrResponse = (err.response);
                    this.logger.debug(`Remote api returned failure http status: ${axErrResponse.status || ""} ${axErrResponse.statusText || ""}.`); // , stringify(axr);  // need json-safe-stringify
                    return { data: axErrResponse.data, headers: axErrResponse.headers, status: axErrResponse.status, statusText: axErrResponse.statusText };
                }
                else {
                    let result = new contracts.Result(false, `Error communicating with remote api: ${(_a = err.name) !== null && _a !== void 0 ? _a : ""} ${(_b = err.message) !== null && _b !== void 0 ? _b : "unspecified error."}`, err);
                    return { data: result, headers: (_d = (_c = err.response) === null || _c === void 0 ? void 0 : _c.headers) !== null && _d !== void 0 ? _d : {}, status: (_f = (_e = err.response) === null || _e === void 0 ? void 0 : _e.status) !== null && _f !== void 0 ? _f : -1, statusText: (_h = (_g = err.response) === null || _g === void 0 ? void 0 : _g.statusText) !== null && _h !== void 0 ? _h : "" };
                }
            }
        });
    }
    /** Replaces the user in the output with a TokenHolder so that they client consumer has access to the token.
     * throws if the axios response does not contain a data property. */
    convertToTokenHolderResult(apiResponse, headers) {
        let result = new contracts.SingleResult(apiResponse.success, apiResponse.message, apiResponse.error, undefined, apiResponse.validation);
        if (apiResponse.output) {
            let token = headers[this.tokenHeaderName];
            if (!token)
                throw new Error(`Authentication service did not provide a user token.`);
            let exp = this.extractTokenExpiration(token);
            result.output = new token_holder_1.TokenHolder(apiResponse.output, token, exp);
        }
        return result;
    }
    /** Replaces the user in the output with a TokenHolder so that they client consumer has access to the token.
     * throws if the axios response does not contain a data property.
     * @deprecated Use `convertToTokenHolderResult()` instead.*/
    convertToTokenHolderResponse(apiResponse) {
        if (apiResponse.data) {
            // TODO:  Dont construct new - just cast or ducktype and replace the output property.
            let result = new contracts.SingleResult(apiResponse.data.success, apiResponse.data.message, apiResponse.data.error, undefined, apiResponse.data.validation);
            if (apiResponse.data.output) {
                let token = apiResponse.headers[this.tokenHeaderName];
                if (!token)
                    throw new Error(`Authentication service did not provide a user token.`);
                let exp = this.extractTokenExpiration(token);
                result.output = new token_holder_1.TokenHolder(apiResponse.data.output, token, exp);
            }
            return result;
        }
        else {
            throw new Error(`Authentication request did not return an output object. HttpStatus: ${apiResponse.status} ${apiResponse.statusText}`);
        }
    }
    /** Determines whether the given token is expired.
     * @param throwOnError throws any encountered errors, including token parsing errors.
     */
    isExpired(token, throwOnError = false) {
        try {
            const exp = this.extractTokenExpiration(token);
            return (exp == undefined) || !(0, codiac_common_1.isFuture)(exp);
        }
        catch (err) {
            let newErr = new contracts.CodiacError(`Error determining expiry status: ${err.message || ""}`, err);
            this.logger.detail(newErr.message);
            if (throwOnError) {
                throw newErr;
            }
            else {
                return true;
            }
        }
    }
    extractTokenExpiration(token) {
        let exp;
        try {
            const encoder = new jwt_lib_1.JwtEncoder();
            const tokenObj = encoder.tryDecode(token);
            const CLAIM_KEY_FOR_EXPIRATION = "exp"; // this is just a standard claim so it ought to come from the jwt lib
            const rawExp = tokenObj === null || tokenObj === void 0 ? void 0 : tokenObj.payload[CLAIM_KEY_FOR_EXPIRATION];
            if (rawExp) {
                try {
                    exp = new Date(rawExp);
                    this.logger.trace(`Exracted token expiration (utc): ${(exp === null || exp === void 0 ? void 0 : exp.toUTCString()) || "undefined"}`);
                }
                catch (_a) {
                    this.logger.trace(`Invalid date format in token expiration: [${rawExp}]`);
                }
            }
            return exp;
        }
        catch (err) {
            throw new Error(`Error parsing expiration from token: ${err.message}`);
        }
    }
    /** Provides the ability to extend an existing token.
     *  Returns failure for invalid or revoked tokens.
     *  Returns any errors encountered refreshing.
     *  NOTE: If successful, keeps the returned auth token in scope for this client instance.
     * @param currentToken The JWT token returned in a prior request.
     * */
    refreshToken(currentToken) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                var _a, _b, _c, _d, _e;
                try {
                    let url = path.posix.join(this.authConstants.ROUTE_PREFIX, this.authConstants.ROUTE_SUBPATH_TOKEN_REFRESH);
                    let req = {};
                    let options = {
                        "baseURL": this.core.apiRootUrl,
                        "headers": {
                            "content-type": "application/json",
                            [this.tokenHeaderName]: currentToken
                        }
                    };
                    // let apiResponse = await axios.post<contracts.SingleResult<TenantUser>>(url, req, options);
                    // let result = this.convertToTokenHolderResponse(apiResponse);
                    let httpResp = yield this.executeAxiosRequest(codiac_common_1.httpRestVerb.POST, (contracts.SingleResult), url, req, options);
                    if (httpResp.data === undefined) {
                        throw new Error(`refreshToken request did not return an output object. HttpStatus: ${(_a = httpResp.status) !== null && _a !== void 0 ? _a : ""} ${(_b = httpResp.statusText) !== null && _b !== void 0 ? _b : ""}`);
                    }
                    let result = this.convertToTokenHolderResult(httpResp.data, httpResp.headers);
                    if ((_c = result.output) === null || _c === void 0 ? void 0 : _c.token) {
                        this.core.authToken = result.output.token;
                    }
                    resolve(result);
                }
                catch (err) {
                    let output = new contracts.SingleResult(false, `Error during refreshToken: ${(_d = err.name) !== null && _d !== void 0 ? _d : ""} ${(_e = err.message) !== null && _e !== void 0 ? _e : "(no error message available)"}`, err);
                    this.logger.debug(output.message);
                    resolve(output);
                }
            }));
        });
    }
    /** Retrieves the full account info for the current user (minus any passwords),
     *  including all tenant profiles.
     *  Returns failure for invalid or revoked tokens.
     *  Returns any errors encountered refreshing.
     *  NOTE: keeps the returned auth token in scope for this client instance.
     * @param currentToken (optional if the client instance has already authenticated) The JWT token returned in a prior request.
     */
    whoAmI(currentToken) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                var _a, _b, _c, _d, _e;
                try {
                    let url = path.posix.join(this.authConstants.ROUTE_PREFIX, this.authConstants.ROUTE_SUBPATH_TOKEN_WHOAMI);
                    let options = {
                        "baseURL": this.core.apiRootUrl,
                        "headers": {
                            "content-type": "application/json"
                        }
                    };
                    if (currentToken || this.core.authToken)
                        options.headers[this.tokenHeaderName] = currentToken || this.core.authToken;
                    // let apiResponse = await axios.get<contracts.SingleResult<TenantUser>>(url, options);
                    // let result = apiResponse.data;
                    // if (apiResponse.headers[RestClientBaseWithAuth.TOKEN_HEADER_PARAM]) {
                    //   this.core.authToken = apiResponse.headers[RestClientBaseWithAuth.TOKEN_HEADER_PARAM];
                    // }
                    let httpResp = yield this.executeAxiosRequest(codiac_common_1.httpRestVerb.GET, (contracts.SingleResult), url, undefined, options);
                    if (httpResp.data === undefined) {
                        throw new Error(`whoAmI request did not return an output object. HttpStatus: ${(_a = httpResp.status) !== null && _a !== void 0 ? _a : ""} ${(_b = httpResp.statusText) !== null && _b !== void 0 ? _b : ""}`);
                    }
                    let result = this.convertToTokenHolderResult(httpResp.data, httpResp.headers);
                    if ((_c = result.output) === null || _c === void 0 ? void 0 : _c.token) {
                        this.core.authToken = result.output.token;
                    }
                    resolve(httpResp.data); // result);  // this method should have returned a tokenHolder, not a tenantUser.
                }
                catch (err) {
                    let output = new contracts.SingleResult(false, `Error during whoAmI: ${(_d = err.name) !== null && _d !== void 0 ? _d : ""} ${(_e = err.message) !== null && _e !== void 0 ? _e : "(no error message available)"}`, err);
                    this.logger.debug(output.message);
                    resolve(output);
                }
            }));
        });
    }
    /** Provides the ability to extend an existing token.
     *  Returns failure for invalid or revoked tokens.
     *  NOTE: If successful, keeps the returned auth token in scope for this client instance.
     * @param currentToken The JWT token returned in a prior request.
     * @param tenantCode Unique identifier of the tenant being switched to.
     *  Returns any errors encountered refreshing.  */
    switchTenant(currentToken, tenantCode) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                var _a, _b, _c, _d, _e;
                try {
                    let url = path.posix.join(this.authConstants.ROUTE_PREFIX, this.authConstants.ROUTE_SUBPATH_SWITCH_TENANT);
                    let req = { newTenantCode: tenantCode };
                    let options = {
                        "baseURL": this.core.apiRootUrl,
                        "headers": {
                            "content-type": "application/json",
                            [this.tokenHeaderName]: currentToken
                        }
                    };
                    let httpResp = yield this.executeAxiosRequest(codiac_common_1.httpRestVerb.POST, (contracts.SingleResult), url, req, options);
                    if (httpResp.data === undefined) {
                        throw new Error(`switchTenant request did not return an output object. HttpStatus: ${(_a = httpResp.status) !== null && _a !== void 0 ? _a : ""} ${(_b = httpResp.statusText) !== null && _b !== void 0 ? _b : ""}`);
                    }
                    let result = this.convertToTokenHolderResult(httpResp.data, httpResp.headers);
                    if ((_c = result.output) === null || _c === void 0 ? void 0 : _c.token) {
                        this.core.authToken = result.output.token;
                    }
                    resolve(result);
                }
                catch (err) {
                    let output = new contracts.SingleResult(false, `Error during switchTenant: ${(_d = err.name) !== null && _d !== void 0 ? _d : ""} ${(_e = err.message) !== null && _e !== void 0 ? _e : "(no error message available)"}`, err);
                    this.logger.debug(output.message);
                    resolve(output);
                }
            }));
        });
    }
    /** Declares a new organization in the toyhauler system.
     * The given user account is made the administrator for that organization,
     * and if the new user flag is given,
     * the user account will get created.
     * NOTE: If successful, keeps the returned auth token in scope for this client instance.
     * @param tenantName Human readable friendly title for the tenant.  NOT used for system identification.
     * @param newUser Flag to create a new user account with the given credentials.
     * @param userName User to be the adminstrator for the new tenant.
     * @param password Password for the given user (desired password if the newuser flag is set).
     * @param tenantCode (optional) Desired unique identifier for the new tenant (if omitted one will be generated).
     * @param currentToken The JWT token returned in a prior request.
     *  */
    registerTenant(tenantName, newUser, userName, password, tenantCode, currentToken) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                var _a, _b, _c, _d;
                try {
                    let url = path.posix.join(this.authConstants.ROUTE_PREFIX, this.authConstants.ROUTE_SUBPATH_TENANT_REGISTER);
                    let req = { tenantName: tenantName, newUser: newUser, userName: userName, password: password, tenantCode: tenantCode };
                    let options = {
                        "baseURL": this.core.apiRootUrl,
                        "headers": {
                            "content-type": "application/json"
                        }
                    };
                    if (currentToken)
                        options.headers[this.tokenHeaderName] = currentToken;
                    // let response = await axios.post<contracts.SingleResult<AuthTenant>>(url, req, options);
                    // let opResult = response.data;
                    // if (opResult && opResult.success && response.headers[this.tokenHeaderName]) {
                    //   this.core.authToken = response.headers[this.tokenHeaderName];
                    // }
                    // resolve(response.data);
                    let httpResp = yield this.executeAxiosRequest(codiac_common_1.httpRestVerb.POST, (contracts.SingleResult), url, req, options);
                    if (httpResp.data === undefined) {
                        throw new Error(`registerTenant request did not return an output object. HttpStatus: ${(_a = httpResp.status) !== null && _a !== void 0 ? _a : ""} ${(_b = httpResp.statusText) !== null && _b !== void 0 ? _b : ""}`);
                    }
                    let result = httpResp.data;
                    if (result.success && httpResp.headers[this.tokenHeaderName]) {
                        this.core.authToken = httpResp.headers[this.tokenHeaderName];
                    }
                    resolve(result); // this should have been a tokenHolder result instead of an AuthTenant.
                }
                catch (err) {
                    let output = new contracts.SingleResult(false, `Error during registerTenant: ${(_c = err.name) !== null && _c !== void 0 ? _c : ""} ${(_d = err.message) !== null && _d !== void 0 ? _d : "(no error message available)"}`, err);
                    this.logger.debug(output.message);
                    resolve(output);
                }
            }));
        });
    }
};
/** Hardcoded to match the current setting on the server.
 * TODO: Get this from a config that is copied from the server project to the client project on build.
 */
ApiAuthMethodsLegacy.TOKEN_HEADER_PARAM = "authorization";
ApiAuthMethodsLegacy = ApiAuthMethodsLegacy_1 = tslib_1.__decorate([
    (0, inversify_1.injectable)(),
    tslib_1.__metadata("design:paramtypes", [api_client_base_1.ApiClientBase, Object])
], ApiAuthMethodsLegacy);
exports.ApiAuthMethodsLegacy = ApiAuthMethodsLegacy;
//# sourceMappingURL=api-auth-methods-legacy.js.map