/*
Copyright 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
"use strict";

/** @module interactive-auth */

var _getIterator2 = require("babel-runtime/core-js/get-iterator");

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _stringify = require("babel-runtime/core-js/json/stringify");

var _stringify2 = _interopRequireDefault(_stringify);

var _regenerator = require("babel-runtime/regenerator");

var _regenerator2 = _interopRequireDefault(_regenerator);

var _bluebird = require("bluebird");

var _bluebird2 = _interopRequireDefault(_bluebird);

var _logger = require("../src/logger");

var _logger2 = _interopRequireDefault(_logger);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var url = require("url");

var utils = require("./utils");


var EMAIL_STAGE_TYPE = "m.login.email.identity";
var MSISDN_STAGE_TYPE = "m.login.msisdn";

/**
 * Abstracts the logic used to drive the interactive auth process.
 *
 * <p>Components implementing an interactive auth flow should instantiate one of
 * these, passing in the necessary callbacks to the constructor. They should
 * then call attemptAuth, which will return a promise which will resolve or
 * reject when the interactive-auth process completes.
 *
 * <p>Meanwhile, calls will be made to the startAuthStage and doRequest
 * callbacks, and information gathered from the user can be submitted with
 * submitAuthDict.
 *
 * @constructor
 * @alias module:interactive-auth
 *
 * @param {object} opts  options object
 *
 * @param {object} opts.matrixClient A matrix client to use for the auth process
 *
 * @param {object?} opts.authData error response from the last request. If
 *    null, a request will be made with no auth before starting.
 *
 * @param {function(object?): module:client.Promise} opts.doRequest
 *     called with the new auth dict to submit the request. Also passes a
 *     second deprecated arg which is a flag set to true if this request
 *     is a background request. The busyChanged callback should be used
 *     instead of the backfround flag. Should return a promise which resolves
 *     to the successful response or rejects with a MatrixError.
 *
 * @param {function(bool): module:client.Promise} opts.busyChanged
 *     called whenever the interactive auth logic becomes busy submitting
 *     information provided by the user or finsihes. After this has been
 *     called with true the UI should indicate that a request is in progress
 *     until it is called again with false.
 *
 * @param {function(string, object?)} opts.stateUpdated
 *     called when the status of the UI auth changes, ie. when the state of
 *     an auth stage changes of when the auth flow moves to a new stage.
 *     The arguments are: the login type (eg m.login.password); and an object
 *     which is either an error or an informational object specific to the
 *     login type. If the 'errcode' key is defined, the object is an error,
 *     and has keys:
 *         errcode: string, the textual error code, eg. M_UNKNOWN
 *         error: string, human readable string describing the error
 *
 *     The login type specific objects are as follows:
 *         m.login.email.identity:
 *          * emailSid: string, the sid of the active email auth session
 *
 * @param {object?} opts.inputs Inputs provided by the user and used by different
 *     stages of the auto process. The inputs provided will affect what flow is chosen.
 *
 * @param {string?} opts.inputs.emailAddress An email address. If supplied, a flow
 *     using email verification will be chosen.
 *
 * @param {string?} opts.inputs.phoneCountry An ISO two letter country code. Gives
 *     the country that opts.phoneNumber should be resolved relative to.
 *
 * @param {string?} opts.inputs.phoneNumber A phone number. If supplied, a flow
 *     using phone number validation will be chosen.
 *
 * @param {string?} opts.sessionId If resuming an existing interactive auth session,
 *     the sessionId of that session.
 *
 * @param {string?} opts.clientSecret If resuming an existing interactive auth session,
 *     the client secret for that session
 *
 * @param {string?} opts.emailSid If returning from having completed m.login.email.identity
 *     auth, the sid for the email verification session.
 *
 * @param {function?} opts.requestEmailToken A function that takes the email address (string),
 *     clientSecret (string), attempt number (int) and sessionId (string) and calls the
 *     relevant requestToken function and returns the promise returned by that function.
 *     If the resulting promise rejects, the rejection will propagate through to the
 *     attemptAuth promise.
 *
 */
function InteractiveAuth(opts) {
    this._matrixClient = opts.matrixClient;
    this._data = opts.authData || {};
    this._requestCallback = opts.doRequest;
    this._busyChangedCallback = opts.busyChanged;
    // startAuthStage included for backwards compat
    this._stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage;
    this._resolveFunc = null;
    this._rejectFunc = null;
    this._inputs = opts.inputs || {};
    this._requestEmailTokenCallback = opts.requestEmailToken;

    if (opts.sessionId) this._data.session = opts.sessionId;
    this._clientSecret = opts.clientSecret || this._matrixClient.generateClientSecret();
    this._emailSid = opts.emailSid;
    if (this._emailSid === undefined) this._emailSid = null;
    this._requestingEmailToken = false;

    this._chosenFlow = null;
    this._currentStage = null;

    // if we are currently trying to submit an auth dict (which includes polling)
    // the promise the will resolve/reject when it completes
    this._submitPromise = null;
}

InteractiveAuth.prototype = {
    /**
     * begin the authentication process.
     *
     * @return {module:client.Promise} which resolves to the response on success,
     * or rejects with the error on failure. Rejects with NoAuthFlowFoundError if
     *     no suitable authentication flow can be found
     */
    attemptAuth: function attemptAuth() {
        var _this = this;

        // This promise will be quite long-lived and will resolve when the
        // request is authenticated and completes successfully.
        return new _bluebird2.default(function (resolve, reject) {
            _this._resolveFunc = resolve;
            _this._rejectFunc = reject;

            // if we have no flows, try a request (we'll have
            // just a session ID in _data if resuming)
            if (!_this._data.flows) {
                if (_this._busyChangedCallback) _this._busyChangedCallback(true);
                _this._doRequest(_this._data).finally(function () {
                    if (_this._busyChangedCallback) _this._busyChangedCallback(false);
                });
            } else {
                _this._startNextAuthStage();
            }
        });
    },

    /**
     * Poll to check if the auth session or current stage has been
     * completed out-of-band. If so, the attemptAuth promise will
     * be resolved.
     */
    poll: function () {
        var _ref = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
            var authDict, creds, idServerParsedUrl;
            return _regenerator2.default.wrap(function _callee$(_context) {
                while (1) {
                    switch (_context.prev = _context.next) {
                        case 0:
                            if (this._data.session) {
                                _context.next = 2;
                                break;
                            }

                            return _context.abrupt("return");

                        case 2:
                            if (!this._submitPromise) {
                                _context.next = 4;
                                break;
                            }

                            return _context.abrupt("return");

                        case 4:
                            authDict = {};

                            if (!(this._currentStage == EMAIL_STAGE_TYPE)) {
                                _context.next = 14;
                                break;
                            }

                            if (!this._emailSid) {
                                _context.next = 14;
                                break;
                            }

                            creds = {
                                sid: this._emailSid,
                                client_secret: this._clientSecret
                            };
                            _context.next = 10;
                            return (0, _bluebird.resolve)(this._matrixClient.doesServerRequireIdServerParam());

                        case 10:
                            if (!_context.sent) {
                                _context.next = 13;
                                break;
                            }

                            idServerParsedUrl = url.parse(this._matrixClient.getIdentityServerUrl());

                            creds.id_server = idServerParsedUrl.host;

                        case 13:
                            authDict = {
                                type: EMAIL_STAGE_TYPE,
                                threepid_creds: creds
                            };

                        case 14:

                            this.submitAuthDict(authDict, true);

                        case 15:
                        case "end":
                            return _context.stop();
                    }
                }
            }, _callee, this);
        }));

        function poll() {
            return _ref.apply(this, arguments);
        }

        return poll;
    }(),

    /**
     * get the auth session ID
     *
     * @return {string} session id
     */
    getSessionId: function getSessionId() {
        return this._data ? this._data.session : undefined;
    },

    /**
     * get the client secret used for validation sessions
     * with the ID server.
     *
     * @return {string} client secret
     */
    getClientSecret: function getClientSecret() {
        return this._clientSecret;
    },

    /**
     * get the server params for a given stage
     *
     * @param {string} loginType login type for the stage
     * @return {object?} any parameters from the server for this stage
     */
    getStageParams: function getStageParams(loginType) {
        var params = {};
        if (this._data && this._data.params) {
            params = this._data.params;
        }
        return params[loginType];
    },

    getChosenFlow: function getChosenFlow() {
        return this._chosenFlow;
    },


    /**
     * submit a new auth dict and fire off the request. This will either
     * make attemptAuth resolve/reject, or cause the startAuthStage callback
     * to be called for a new stage.
     *
     * @param {object} authData new auth dict to send to the server. Should
     *    include a `type` propterty denoting the login type, as well as any
     *    other params for that stage.
     * @param {bool} background If true, this request failing will not result
     *    in the attemptAuth promise being rejected. This can be set to true
     *    for requests that just poll to see if auth has been completed elsewhere.
     */
    submitAuthDict: function () {
        var _ref2 = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(authData, background) {
            var auth;
            return _regenerator2.default.wrap(function _callee2$(_context2) {
                while (1) {
                    switch (_context2.prev = _context2.next) {
                        case 0:
                            if (this._resolveFunc) {
                                _context2.next = 2;
                                break;
                            }

                            throw new Error("submitAuthDict() called before attemptAuth()");

                        case 2:

                            if (!background && this._busyChangedCallback) {
                                this._busyChangedCallback(true);
                            }

                            // if we're currently trying a request, wait for it to finish
                            // as otherwise we can get multiple 200 responses which can mean
                            // things like multiple logins for register requests.
                            // (but discard any expections as we only care when its done,
                            // not whether it worked or not)

                        case 3:
                            if (!this._submitPromise) {
                                _context2.next = 13;
                                break;
                            }

                            _context2.prev = 4;
                            _context2.next = 7;
                            return (0, _bluebird.resolve)(this._submitPromise);

                        case 7:
                            _context2.next = 11;
                            break;

                        case 9:
                            _context2.prev = 9;
                            _context2.t0 = _context2["catch"](4);

                        case 11:
                            _context2.next = 3;
                            break;

                        case 13:

                            // use the sessionid from the last request.
                            auth = {
                                session: this._data.session
                            };

                            utils.extend(auth, authData);

                            _context2.prev = 15;

                            // NB. the 'background' flag is deprecated by the busyChanged
                            // callback and is here for backwards compat
                            this._submitPromise = this._doRequest(auth, background);
                            _context2.next = 19;
                            return (0, _bluebird.resolve)(this._submitPromise);

                        case 19:
                            _context2.prev = 19;

                            this._submitPromise = null;
                            if (!background && this._busyChangedCallback) {
                                this._busyChangedCallback(false);
                            }
                            return _context2.finish(19);

                        case 23:
                        case "end":
                            return _context2.stop();
                    }
                }
            }, _callee2, this, [[4, 9], [15,, 19, 23]]);
        }));

        function submitAuthDict(_x, _x2) {
            return _ref2.apply(this, arguments);
        }

        return submitAuthDict;
    }(),

    /**
     * Gets the sid for the email validation session
     * Specific to m.login.email.identity
     *
     * @returns {string} The sid of the email auth session
     */
    getEmailSid: function getEmailSid() {
        return this._emailSid;
    },

    /**
     * Sets the sid for the email validation session
     * This must be set in order to successfully poll for completion
     * of the email validation.
     * Specific to m.login.email.identity
     *
     * @param {string} sid The sid for the email validation session
     */
    setEmailSid: function setEmailSid(sid) {
        this._emailSid = sid;
    },

    /**
     * Fire off a request, and either resolve the promise, or call
     * startAuthStage.
     *
     * @private
     * @param {object?} auth new auth dict, including session id
     * @param {bool?} background If true, this request is a background poll, so it
     *    failing will not result in the attemptAuth promise being rejected.
     *    This can be set to true for requests that just poll to see if auth has
     *    been completed elsewhere.
     */
    _doRequest: function () {
        var _ref3 = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(auth, background) {
            var result, errorFlows, haveFlows, requestTokenResult;
            return _regenerator2.default.wrap(function _callee3$(_context3) {
                while (1) {
                    switch (_context3.prev = _context3.next) {
                        case 0:
                            _context3.prev = 0;
                            _context3.next = 3;
                            return (0, _bluebird.resolve)(this._requestCallback(auth, background));

                        case 3:
                            result = _context3.sent;

                            this._resolveFunc(result);
                            _context3.next = 30;
                            break;

                        case 7:
                            _context3.prev = 7;
                            _context3.t0 = _context3["catch"](0);

                            // sometimes UI auth errors don't come with flows
                            errorFlows = _context3.t0.data ? _context3.t0.data.flows : null;
                            haveFlows = Boolean(this._data.flows) || Boolean(errorFlows);

                            if (_context3.t0.httpStatus !== 401 || !_context3.t0.data || !haveFlows) {
                                // doesn't look like an interactive-auth failure.
                                if (!background) {
                                    this._rejectFunc(_context3.t0);
                                } else {
                                    // We ignore all failures here (even non-UI auth related ones)
                                    // since we don't want to suddenly fail if the internet connection
                                    // had a blip whilst we were polling
                                    _logger2.default.log("Background poll request failed doing UI auth: ignoring", _context3.t0);
                                }
                            }
                            // if the error didn't come with flows, completed flows or session ID,
                            // copy over the ones we have. Synapse sometimes sends responses without
                            // any UI auth data (eg. when polling for email validation, if the email
                            // has not yet been validated). This appears to be a Synapse bug, which
                            // we workaround here.
                            if (!_context3.t0.data.flows && !_context3.t0.data.completed && !_context3.t0.data.session) {
                                _context3.t0.data.flows = this._data.flows;
                                _context3.t0.data.completed = this._data.completed;
                                _context3.t0.data.session = this._data.session;
                            }
                            this._data = _context3.t0.data;
                            this._startNextAuthStage();

                            if (!(!this._emailSid && !this._requestingEmailToken && this._chosenFlow.stages.includes('m.login.email.identity'))) {
                                _context3.next = 30;
                                break;
                            }

                            // If we've picked a flow with email auth, we send the email
                            // now because we want the request to fail as soon as possible
                            // if the email address is not valid (ie. already taken or not
                            // registered, depending on what the operation is).
                            this._requestingEmailToken = true;
                            _context3.prev = 17;
                            _context3.next = 20;
                            return (0, _bluebird.resolve)(this._requestEmailTokenCallback(this._inputs.emailAddress, this._clientSecret, 1, // TODO: Multiple send attempts?
                            this._data.session));

                        case 20:
                            requestTokenResult = _context3.sent;

                            this._emailSid = requestTokenResult.sid;
                            // NB. promise is not resolved here - at some point, doRequest
                            // will be called again and if the user has jumped through all
                            // the hoops correctly, auth will be complete and the request
                            // will succeed.
                            // Also, we should expose the fact that this request has compledted
                            // so clients can know that the email has actually been sent.
                            _context3.next = 27;
                            break;

                        case 24:
                            _context3.prev = 24;
                            _context3.t1 = _context3["catch"](17);

                            // we failed to request an email token, so fail the request.
                            // This could be due to the email already beeing registered
                            // (or not being registered, depending on what we're trying
                            // to do) or it could be a network failure. Either way, pass
                            // the failure up as the user can't complete auth if we can't
                            // send the email, foe whatever reason.
                            this._rejectFunc(_context3.t1);

                        case 27:
                            _context3.prev = 27;

                            this._requestingEmailToken = false;
                            return _context3.finish(27);

                        case 30:
                        case "end":
                            return _context3.stop();
                    }
                }
            }, _callee3, this, [[0, 7], [17, 24, 27, 30]]);
        }));

        function _doRequest(_x3, _x4) {
            return _ref3.apply(this, arguments);
        }

        return _doRequest;
    }(),

    /**
     * Pick the next stage and call the callback
     *
     * @private
     * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found
     */
    _startNextAuthStage: function _startNextAuthStage() {
        var nextStage = this._chooseStage();
        if (!nextStage) {
            throw new Error("No incomplete flows from the server");
        }
        this._currentStage = nextStage;

        if (nextStage === 'm.login.dummy') {
            this.submitAuthDict({
                type: 'm.login.dummy'
            });
            return;
        }

        if (this._data.errcode || this._data.error) {
            this._stateUpdatedCallback(nextStage, {
                errcode: this._data.errcode || "",
                error: this._data.error || ""
            });
            return;
        }

        var stageStatus = {};
        if (nextStage == EMAIL_STAGE_TYPE) {
            stageStatus.emailSid = this._emailSid;
        }
        this._stateUpdatedCallback(nextStage, stageStatus);
    },

    /**
     * Pick the next auth stage
     *
     * @private
     * @return {string?} login type
     * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found
     */
    _chooseStage: function _chooseStage() {
        if (this._chosenFlow === null) {
            this._chosenFlow = this._chooseFlow();
        }
        _logger2.default.log("Active flow => %s", (0, _stringify2.default)(this._chosenFlow));
        var nextStage = this._firstUncompletedStage(this._chosenFlow);
        _logger2.default.log("Next stage: %s", nextStage);
        return nextStage;
    },

    /**
     * Pick one of the flows from the returned list
     * If a flow using all of the inputs is found, it will
     * be returned, otherwise, null will be returned.
     *
     * Only flows using all given inputs are chosen because it
     * is likley to be surprising if the user provides a
     * credential and it is not used. For example, for registration,
     * this could result in the email not being used which would leave
     * the account with no means to reset a password.
     *
     * @private
     * @return {object} flow
     * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found
     */
    _chooseFlow: function _chooseFlow() {
        var flows = this._data.flows || [];

        // we've been given an email or we've already done an email part
        var haveEmail = Boolean(this._inputs.emailAddress) || Boolean(this._emailSid);
        var haveMsisdn = Boolean(this._inputs.phoneCountry) && Boolean(this._inputs.phoneNumber);

        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
            for (var _iterator = (0, _getIterator3.default)(flows), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                var flow = _step.value;

                var flowHasEmail = false;
                var flowHasMsisdn = false;
                var _iteratorNormalCompletion2 = true;
                var _didIteratorError2 = false;
                var _iteratorError2 = undefined;

                try {
                    for (var _iterator2 = (0, _getIterator3.default)(flow.stages), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
                        var stage = _step2.value;

                        if (stage === EMAIL_STAGE_TYPE) {
                            flowHasEmail = true;
                        } else if (stage == MSISDN_STAGE_TYPE) {
                            flowHasMsisdn = true;
                        }
                    }
                } catch (err) {
                    _didIteratorError2 = true;
                    _iteratorError2 = err;
                } finally {
                    try {
                        if (!_iteratorNormalCompletion2 && _iterator2.return) {
                            _iterator2.return();
                        }
                    } finally {
                        if (_didIteratorError2) {
                            throw _iteratorError2;
                        }
                    }
                }

                if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) {
                    return flow;
                }
            }
            // Throw an error with a fairly generic description, but with more
            // information such that the app can give a better one if so desired.
        } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
        } finally {
            try {
                if (!_iteratorNormalCompletion && _iterator.return) {
                    _iterator.return();
                }
            } finally {
                if (_didIteratorError) {
                    throw _iteratorError;
                }
            }
        }

        var err = new Error("No appropriate authentication flow found");
        err.name = 'NoAuthFlowFoundError';
        err.required_stages = [];
        if (haveEmail) err.required_stages.push(EMAIL_STAGE_TYPE);
        if (haveMsisdn) err.required_stages.push(MSISDN_STAGE_TYPE);
        err.available_flows = flows;
        throw err;
    },

    /**
     * Get the first uncompleted stage in the given flow
     *
     * @private
     * @param {object} flow
     * @return {string} login type
     */
    _firstUncompletedStage: function _firstUncompletedStage(flow) {
        var completed = (this._data || {}).completed || [];
        for (var i = 0; i < flow.stages.length; ++i) {
            var stageType = flow.stages[i];
            if (completed.indexOf(stageType) === -1) {
                return stageType;
            }
        }
    }
};

/** */
module.exports = InteractiveAuth;
//# sourceMappingURL=interactive-auth.js.map