Source: component/login.js

/*! meta-client/modules/component/login */
/*jslint
    browser, long
*/
/*global
*/
import Logger from "js-logger";
import ko from "knockout";
import viewmodel from "meta-client/modules/viewmodel";
import webauthn from "meta-client/modules/webauthn";
import model from "meta-core/modules/model";
import protocol from "meta-core/modules/protocol";
import _ from "underscore";
import i18next from "util-web/modules/i18next";
import keyval from "util-web/modules/keyval";
import ui from "util-web/modules/ui";
import template from "./login.html";

const LOG = Logger.get("meta-client/component/login");
const TOKEN_STORAGE_KEY_PREFIX = "token-";

/**
 * login component.
 *
 * @module meta-client/modules/component/login
 */
export default Object.freeze({
    template,
    viewModel: {
        createViewModel: function ({
            client,
            clientName,
            clientVersion,
            customClasses = null,
            help = null,
            info = null,
            login,
            logout,
            onAuth,
            onConnectFailed,
            otpTypes = [],
            passwordRegex = null
        }) {
            const connect = function () {
                if (client.isConnected()) {
                    return Promise.resolve(undefined);
                }
                return client.connect();
            };
            const tokenStorageKey = TOKEN_STORAGE_KEY_PREFIX + clientName;
            const deleteToken = () => keyval.delete(tokenStorageKey).catch(
                (exc) => LOG.warn("deleteToken failed", exc)
            ).then(() => vm.hasUserFocus(true));
            const loadStoredToken = function () {
                return keyval.get(tokenStorageKey).then(function (token) {
                    if (token) {
                        return vm.loginInternal({token});
                    }
                    vm.hasUserFocus(true);
                    return Promise.resolve(undefined);
                }, function (exc) {
                    LOG.warn("loadStoredToken failed", exc);
                }).then(function () {
                    vm.isLoadingToken(false);
                });
            };
            const vm = {};

            vm.authRef = protocol.REST_PATH + "/" + protocol.getWebhookAuthPath("exampleAuthRef");
            vm.customClasses = customClasses;
            vm.metaUserOtpType = model.metaUserOtpType;
            vm.otpTypes = otpTypes;
            vm.otpTypeOptions = Object.keys(model.metaUserOtpType).map(function (key) {
                if (otpTypes.includes(key) === false) {
                    return;
                }
                return {name: i18next.computedT("otp_type_" + key), type: key};
            }).filter(_.isObject);

            vm.currentLocale = i18next.currentLocale;
            vm.changeLocale = (locale) => i18next.setLocale(locale);

            vm.user = ko.observable();
            vm.hasUserFocus = ko.observable(false);
            vm.password = ko.observable();
            vm.unmaskPasswords = ko.observable(false);
            vm.enableHelp = _.isFunction(help);
            vm.info = (
                _.isEmpty(info)
                    ? undefined
                    : info
            );

            vm.connectFailed = ko.observable(false);
            vm.hasOtpFocus = ko.observable(false);
            vm.isAuthActive = ko.observable(false);
            vm.isAuthValid = ko.observable(false);
            vm.isLoggingIn = ko.observable(false);
            vm.loginFailed = ko.observable(false);
            vm.onAuthFailed = ko.observable(false);
            vm.otp = ko.observable();
            vm.otp.subscribe(() => vm.isAuthValid(true));

            vm.togglePasswordMasking = () => vm.unmaskPasswords(!vm.unmaskPasswords());

            vm.onAuth = function () {
                return client.authToken(protocol.authTokenRequest()).then(function (reply) {
                    if (reply) {
                        return keyval.set(tokenStorageKey, reply.token);
                    }
                }).catch(
                    (exc) => LOG.warn("onAuth authToken failed", exc)
                ).then(function () {
                    vm.onAuthFailed(false);
                    if (_.isFunction(onAuth)) {
                        onAuth();
                    }
                    return Promise.resolve(undefined);
                }).catch(function (exc) {
                    vm.onAuthFailed(true);
                    LOG.error("onAuth call failed", exc);
                });
            };

            vm.loginInternal = function ({
                password = null,
                token = null,
                user = null
            }) {
                vm.isLoggingIn(true);
                return connect().then(function () {
                    vm.connectFailed(false);
                    return client.login(protocol.loginRequest({
                        client: clientName,
                        locale: i18next.currentLocale(),
                        password,
                        token,
                        user,
                        version: clientVersion
                    }));
                }, function (exc) {
                    LOG.warn("connect failed", exc);
                    if (_.isFunction(onConnectFailed)) {
                        onConnectFailed();
                    }
                    return Promise.reject(exc);
                }).then(function (reply) {
                    vm.loginFailed(false);
                    if (reply.isAuth) {
                        return vm.onAuth();
                    }
                    vm.isAuthActive(true);
                    vm.hasOtpFocus(true);
                    if (reply.webAuthnAssertionRequest) {
                        return vm.authInternal(reply.webAuthnAssertionRequest);
                    }
                    return Promise.resolve(undefined);
                }, function (exc) {
                    LOG.warn("loginInternal failed", exc);
                    if (exc && _.has(exc, protocol.REPLY_TYPE_PROPERTY)) {
                        if (_.isEmpty(token) === false) {
                            return deleteToken();
                        }
                        vm.loginFailed(true);
                        vm.hasUserFocus(true);
                    } else {
                        vm.connectFailed(true);
                    }
                }).then(function () {
                    vm.password(undefined);
                    vm.isLoggingIn(false);
                });
            };

            vm.login = function (form) {
                if (ui.validateForm(form) === false) {
                    return;
                }
                const user = vm.user();
                LOG.info(`login, user=${user}`);
                return vm.loginInternal({
                    password: vm.password(),
                    user
                }).then(function () {
                    ui.resetForm(form);
                });
            };

            if (ko.isWritableObservable(login)) {
                login.subscribe(function (doLogin) {
                    if (doLogin) {
                        vm.login();
                        login(false);
                    }
                });
            }

            vm.isWebAuthnActive = ko.observable(false);
            vm.webAuthnFailed = ko.observable(false);

            vm.authInternal = function (webAuthnAssertionRequest = null) {
                let webAuthnAssertionPromise = Promise.resolve(undefined);
                if (webAuthnAssertionRequest) {
                    vm.isWebAuthnActive(true);
                    webAuthnAssertionPromise = webauthn.getAssertion(webAuthnAssertionRequest.assertion);
                }
                LOG.debug(`authInternal, clientId=${client.clientId()}, user=${client.user()}`);
                return webAuthnAssertionPromise.then(function (webAuthnResponse) {
                    const request = (
                        webAuthnResponse
                            ? protocol.authRequest({
                                webAuthnAssertionReply: protocol.authRequestWebAuthnAssertionReply({credential: webAuthnResponse})
                            })
                            : protocol.authRequest({otp: vm.otp()})
                    );
                    return client.auth(protocol.authRequest(request));
                }, function (exc) {
                    LOG.warn("authInternal webAuthn failed", exc);
                    vm.webAuthnFailed(true);
                }).then(function () {
                    vm.otp(undefined);
                    vm.isWebAuthnActive(false);
                    vm.webAuthnFailed(false);
                    vm.isAuthValid(true);
                    vm.isAuthActive(false);
                    return vm.onAuth();
                }, function (exc) {
                    LOG.warn("authInternal failed", exc);
                    vm.isAuthValid(false);
                });
            };

            vm.isInAuth = ko.observable(false);

            vm.auth = function (form) {
                if (ui.validateForm(form) === false) {
                    return;
                }
                if (client.isConnected() === false || Boolean(client.clientId()) === false) {
                    vm.isAuthActive(false);
                    return;
                }
                LOG.debug("auth");
                vm.isInAuth(true);
                return vm.authInternal().then(function () {
                    vm.isInAuth(false);
                    if (vm.isAuthValid()) {
                        ui.resetForm(form);
                    }
                });
            };

            vm.cancelAuth = function () {
                ui.resetForm(document.getElementById("auth"));
                vm.otp(undefined);
                webauthn.abortAssertion();
                return vm.logout();
            };

            vm.logout = function () {
                LOG.debug("logout");
                vm.user(undefined);
                vm.password(undefined);
                vm.isLoggingIn(false);
                vm.isAuthActive(false);
                vm.isAuthValid(true);
                vm.isWebAuthnActive(false);
                vm.webAuthnFailed(false);
                return client.logout(protocol.logoutRequest()).catch(
                    (exc) => LOG.warn("logout failed", exc)
                ).then(deleteToken);
            };

            if (ko.isWritableObservable(logout)) {
                logout.subscribe(function (doLogout) {
                    if (doLogout) {
                        vm.logout();
                        logout(false);
                    }
                });
            }

            vm.isRecoverUserActive = ko.observable(false);
            vm.hasRecoverUserEmailFocus = ko.observable(false);
            vm.recoverUserEmail = ko.observable();
            vm.recoverUserPhone = ko.observable();
            vm.isRecoverUserValid = ko.pureComputed(function () {
                const email = vm.recoverUserEmail();
                const phone = vm.recoverUserPhone();
                return _.isEmpty(email) === false || _.isEmpty(phone) === false;
            });
            vm.recoverUserSuccess = ko.observable(false);

            vm.activateRecoverUser = function () {
                vm.isResetPasswordActive(false);
                vm.isRecoverUserActive(true);
                vm.hasRecoverUserEmailFocus(true);
            };

            vm.cancelRecoverUser = function () {
                vm.isRecoverUserActive(false);
                vm.recoverUserEmail(undefined);
                vm.recoverUserPhone(undefined);
            };

            vm.recoverUser = function (form) {
                if (ui.validateForm(form) === false) {
                    return;
                }
                LOG.debug("recoverUser");
                return connect().then(function () {
                    return client.recoverUser(protocol.recoverUserRequest({
                        email: vm.recoverUserEmail(),
                        locale: i18next.currentLocale(),
                        phone: vm.recoverUserPhone()
                    }));
                }).then(function () {
                    ui.resetForm(form);
                    vm.cancelRecoverUser();
                    vm.recoverUserSuccess(true);
                });
            };

            vm.hasResetPasswordOtpFocus = ko.observable(false);
            vm.hasResetPasswordUserFocus = ko.observable(false);
            vm.hasSentResetPasswordOtp = ko.observable(false);
            vm.isResetPasswordActive = ko.observable(false);
            vm.resetPasswordFailed = ko.observable(false);
            vm.resetPasswordNew = ko.observable();
            vm.resetPasswordNewConfirm = ko.observable();
            vm.resetPasswordOtp = ko.observable();
            vm.resetPasswordSuccess = ko.observable(false);
            vm.resetPasswordUser = ko.observable();

            vm.isResetPasswordNewValid = viewmodel.newPasswordValidator({
                passwordConfirm: vm.resetPasswordNewConfirm,
                passwordNew: vm.resetPasswordNew,
                regexString: passwordRegex,
                unmask: vm.unmaskPasswords
            });

            vm.activateResetPassword = function () {
                vm.isRecoverUserActive(false);
                vm.isResetPasswordActive(true);
                vm.hasResetPasswordUserFocus(true);
            };

            vm.cancelResetPassword = function () {
                vm.hasSentResetPasswordOtp(false);
                vm.isResetPasswordActive(false);
                vm.resetPasswordFailed(false);
                vm.resetPasswordNew(undefined);
                vm.resetPasswordNewConfirm(undefined);
                vm.resetPasswordOtp(undefined);
                vm.resetPasswordUser(undefined);
            };

            vm.resetPasswordStart = function (form) {
                if (ui.validateForm(form) === false) {
                    return;
                }
                const user = vm.resetPasswordUser();
                LOG.info(`resetPasswordStart, user=${user}`);
                return connect().then(function () {
                    return client.resetPassword(protocol.resetPasswordRequest({
                        locale: i18next.currentLocale(),
                        user
                    }));
                }).then(function () {
                    vm.resetPasswordFailed(false);
                    vm.hasSentResetPasswordOtp(true);
                    vm.hasResetPasswordOtpFocus(true);
                    ui.resetForm(form);
                });
            };

            vm.resetPasswordVerify = function (form) {
                if (ui.validateForm(form) === false) {
                    return;
                }
                const user = vm.resetPasswordUser();
                LOG.debug(`resetPasswordVerify, user=${user}`);
                return client.resetPassword(protocol.resetPasswordRequest({
                    locale: i18next.currentLocale(),
                    newPassword: vm.resetPasswordNew(),
                    otp: vm.resetPasswordOtp(),
                    user
                })).then(function (reply) {
                    ui.resetForm(form);
                    vm.cancelResetPassword();
                    if (reply.success) {
                        vm.resetPasswordSuccess(true);
                    } else {
                        vm.resetPasswordFailed(true);
                    }
                });
            };

            vm.activateHelp = function () {
                if (vm.enableHelp) {
                    help();
                }
            };

            vm.isLoadingToken = ko.observable(true);
            loadStoredToken();

            return Object.freeze(vm);
        }
    }
});