"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const jsx_runtime_1 = require("react/jsx-runtime");
/*
 *  This file is part of CoCalc: Copyright © 2022 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
const icon_1 = require("@cocalc/frontend/components/icon");
const misc_1 = require("@cocalc/util/misc");
const antd_1 = require("antd");
const sso_1 = require("components/auth/sso");
const A_1 = __importDefault(require("components/misc/A"));
const loading_1 = __importDefault(require("components/share/loading"));
const site_name_1 = __importDefault(require("components/share/site-name"));
const post_1 = __importDefault(require("lib/api/post"));
const api_1 = __importDefault(require("lib/hooks/api"));
const edit_table_1 = __importDefault(require("lib/hooks/edit-table"));
const router_1 = require("next/router");
const react_1 = require("react");
const register_1 = __importDefault(require("../register"));
(0, register_1.default)({
    path: "account/sso",
    title: "Single Sign On",
    icon: "external-link",
    desc: "Link your account with configured single sign on (SSO) on providers.",
    Component: () => {
        const [error, setError] = (0, react_1.useState)(null);
        const [unlinking, setUnlinking] = (0, react_1.useState)(false);
        const { edited, original, Heading, setEdited } = (0, edit_table_1.default)({
            accounts: { passports: null },
        }, { noSave: true });
        const hasPassword = (0, api_1.default)("auth/has-password");
        const strategies = (0, api_1.default)("auth/sso-strategies");
        if (original == null ||
            edited == null ||
            strategies.result == null ||
            hasPassword.result == null) {
            return (0, jsx_runtime_1.jsx)(loading_1.default, {});
        }
        if (strategies.error || hasPassword.error) {
            return ((0, jsx_runtime_1.jsx)(antd_1.Alert, { showIcon: true, type: "error", message: strategies.error || hasPassword.error }));
        }
        if (strategies.result.length == 0) {
            return ((0, jsx_runtime_1.jsx)(antd_1.Alert, { showIcon: true, type: "info", message: (0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: ["No SSO providers are configured for ", (0, jsx_runtime_1.jsx)(site_name_1.default, {}), "."] }) }));
        }
        const passports = edited.passports ?? {};
        const linkedNames = Object.keys(passports).map((name) => name.split("-")[0]);
        return ((0, jsx_runtime_1.jsxs)("div", { style: { color: "#555" }, children: [error && (0, jsx_runtime_1.jsx)(antd_1.Alert, { showIcon: true, type: "error", message: error }), unlinking && ((0, jsx_runtime_1.jsx)(loading_1.default, { style: { fontSize: "16pt" }, children: "Unlinking your passport..." })), (0, misc_1.len)(passports) > 0 && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(Heading, { title: "Your account is linked with" }), (0, jsx_runtime_1.jsx)(Unlink, { passports: passports, strategies: strategies.result, onUnlink: async (name, strategy) => {
                                if (unlinking)
                                    return;
                                if ((0, misc_1.len)(passports) == 1 && !hasPassword.result.hasPassword) {
                                    setError((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: ["You cannot unlink sign on using ", strategy.display, ", since you would then have no way to sign into your account! Please add another SSO method first or", " ", (0, jsx_runtime_1.jsx)(A_1.default, { href: "/config/account/email", children: "set an email address" }), " ", "and ", (0, jsx_runtime_1.jsx)(A_1.default, { href: "/config/account/password", children: "a password" }), ", or", " ", (0, jsx_runtime_1.jsx)(A_1.default, { href: "/config/account/delete", children: "delete your account" }), "."] }));
                                    return;
                                }
                                try {
                                    setError(null);
                                    setUnlinking(true);
                                    await (0, post_1.default)("/auth/unlink-strategy", { name });
                                }
                                catch (err) {
                                    setError(err.message);
                                    return;
                                }
                                finally {
                                    setUnlinking(false);
                                }
                                const passports0 = edited?.passports;
                                if (!passports0)
                                    return;
                                for (const x in passports0) {
                                    if (x == name) {
                                        delete passports0[x];
                                        break;
                                    }
                                }
                                setEdited({ passports: passports0 });
                            } }), (0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsx)("br", {})] })), strategies.result.length > 0 && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(Heading, { title: "Click to link your account" }), (0, jsx_runtime_1.jsx)(Link, { strategies: strategies.result, linked: linkedNames })] }))] }));
    },
});
function Unlink({ passports, strategies, onUnlink, }) {
    const v = [];
    for (const name in passports) {
        const s = name.split("-")[0];
        for (const strategy of strategies) {
            if (s == strategy.name) {
                v.push((0, jsx_runtime_1.jsx)(Strategy, { strategy: strategy, onUnlink: () => onUnlink(name, strategy) }, name));
                break;
            }
        }
    }
    return (0, jsx_runtime_1.jsx)(SpacedStrategies, { children: v });
}
function Link({ strategies, linked, }) {
    const router = (0, router_1.useRouter)();
    let anyHidden = false;
    const v = [];
    for (const strategy of strategies) {
        if (linked.includes(strategy.name))
            continue;
        if (!(strategy.public ?? true) && !(strategy.doNotHide ?? false)) {
            anyHidden = true;
            continue;
        }
        v.push((0, jsx_runtime_1.jsx)(Strategy, { strategy: strategy }, strategy.name));
    }
    // link to the page for additional non-public institutional SSOs
    function hidden() {
        return ((0, jsx_runtime_1.jsxs)("div", { style: { marginTop: "1rem" }, children: ["or other", " ", (0, jsx_runtime_1.jsx)(antd_1.Button, { type: "link", style: { padding: 0 }, onClick: () => router.push(`/sso`), children: "institutional SSO options" }), "."] }));
    }
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(SpacedStrategies, { children: v }), anyHidden && hidden()] }));
}
function Strategy({ strategy, onUnlink, }) {
    function unlinkButton() {
        if (!onUnlink)
            return;
        return ((0, jsx_runtime_1.jsx)("div", { style: { marginTop: "5px" }, children: (0, jsx_runtime_1.jsxs)(antd_1.Popconfirm, { title: (0, jsx_runtime_1.jsxs)("div", { style: { maxWidth: "50ex" }, children: ["Are you sure you want to unlink signing in to ", (0, jsx_runtime_1.jsx)(site_name_1.default, {}), " using", " ", strategy.display, "?"] }), onConfirm: onUnlink, okText: "Yes, unlink", cancelText: "Cancel", children: [" ", (0, jsx_runtime_1.jsxs)(antd_1.Button, { type: "dashed", danger: true, children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "unlink" }), "Unlink"] })] }) }));
    }
    return ((0, jsx_runtime_1.jsxs)("div", { style: { textAlign: "center" }, children: [(0, jsx_runtime_1.jsx)(sso_1.StrategyAvatar, { strategy: strategy, size: 60, noLink: onUnlink != null, showName: true, toolTip: onUnlink
                    ? `Your account is currently linked to ${strategy.display}.`
                    : undefined }), unlinkButton()] }));
}
function SpacedStrategies({ children }) {
    return ((0, jsx_runtime_1.jsx)(antd_1.Space, { size: [20, 20], wrap: true, children: children }));
}
//# sourceMappingURL=sso.js.map