"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var 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
 */
var icon_1 = require("@cocalc/frontend/components/icon");
var misc_1 = require("@cocalc/util/misc");
var antd_1 = require("antd");
var sso_1 = require("components/auth/sso");
var A_1 = __importDefault(require("components/misc/A"));
var loading_1 = __importDefault(require("components/share/loading"));
var site_name_1 = __importDefault(require("components/share/site-name"));
var post_1 = __importDefault(require("lib/api/post"));
var api_1 = __importDefault(require("lib/hooks/api"));
var edit_table_1 = __importDefault(require("lib/hooks/edit-table"));
var router_1 = require("next/router");
var react_1 = require("react");
var 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: function () {
        var _a;
        var _b = __read((0, react_1.useState)(null), 2), error = _b[0], setError = _b[1];
        var _c = __read((0, react_1.useState)(false), 2), unlinking = _c[0], setUnlinking = _c[1];
        var _d = (0, edit_table_1.default)({
            accounts: { passports: null },
        }, { noSave: true }), edited = _d.edited, original = _d.original, Heading = _d.Heading, setEdited = _d.setEdited;
        var hasPassword = (0, api_1.default)("auth/has-password");
        var 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, {}), "."] }) }));
        }
        var passports = (_a = edited.passports) !== null && _a !== void 0 ? _a : {};
        var linkedNames = Object.keys(passports).map(function (name) { return name.split("-")[0]; });
        return ((0, jsx_runtime_1.jsxs)("div", __assign({ 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, __assign({ 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: function (name, strategy) { return __awaiter(void 0, void 0, void 0, function () {
                                var err_1, passports0, x;
                                return __generator(this, function (_a) {
                                    switch (_a.label) {
                                        case 0:
                                            if (unlinking)
                                                return [2 /*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, __assign({ href: "/config/account/email" }, { children: "set an email address" })), " ", "and ", (0, jsx_runtime_1.jsx)(A_1.default, __assign({ href: "/config/account/password" }, { children: "a password" })), ", or", " ", (0, jsx_runtime_1.jsx)(A_1.default, __assign({ href: "/config/account/delete" }, { children: "delete your account" })), "."] }));
                                                return [2 /*return*/];
                                            }
                                            _a.label = 1;
                                        case 1:
                                            _a.trys.push([1, 3, 4, 5]);
                                            setError(null);
                                            setUnlinking(true);
                                            return [4 /*yield*/, (0, post_1.default)("/auth/unlink-strategy", { name: name })];
                                        case 2:
                                            _a.sent();
                                            return [3 /*break*/, 5];
                                        case 3:
                                            err_1 = _a.sent();
                                            setError(err_1.message);
                                            return [2 /*return*/];
                                        case 4:
                                            setUnlinking(false);
                                            return [7 /*endfinally*/];
                                        case 5:
                                            passports0 = edited === null || edited === void 0 ? void 0 : edited.passports;
                                            if (!passports0)
                                                return [2 /*return*/];
                                            for (x in passports0) {
                                                if (x == name) {
                                                    delete passports0[x];
                                                    break;
                                                }
                                            }
                                            setEdited({ passports: passports0 });
                                            return [2 /*return*/];
                                    }
                                });
                            }); } }), (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(_a) {
    var passports = _a.passports, strategies = _a.strategies, onUnlink = _a.onUnlink;
    var v = [];
    var _loop_1 = function (name_1) {
        var e_1, _b;
        var s = name_1.split("-")[0];
        var _loop_2 = function (strategy) {
            if (s == strategy.name) {
                v.push((0, jsx_runtime_1.jsx)(Strategy, { strategy: strategy, onUnlink: function () { return onUnlink(name_1, strategy); } }, name_1));
                return "break";
            }
        };
        try {
            for (var strategies_1 = (e_1 = void 0, __values(strategies)), strategies_1_1 = strategies_1.next(); !strategies_1_1.done; strategies_1_1 = strategies_1.next()) {
                var strategy = strategies_1_1.value;
                var state_1 = _loop_2(strategy);
                if (state_1 === "break")
                    break;
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (strategies_1_1 && !strategies_1_1.done && (_b = strategies_1.return)) _b.call(strategies_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
    };
    for (var name_1 in passports) {
        _loop_1(name_1);
    }
    return (0, jsx_runtime_1.jsx)(SpacedStrategies, { children: v });
}
function Link(_a) {
    var e_2, _b;
    var _c, _d;
    var strategies = _a.strategies, linked = _a.linked;
    var router = (0, router_1.useRouter)();
    var anyHidden = false;
    var v = [];
    try {
        for (var strategies_2 = __values(strategies), strategies_2_1 = strategies_2.next(); !strategies_2_1.done; strategies_2_1 = strategies_2.next()) {
            var strategy = strategies_2_1.value;
            if (linked.includes(strategy.name))
                continue;
            if (!((_c = strategy.public) !== null && _c !== void 0 ? _c : true) && !((_d = strategy.doNotHide) !== null && _d !== void 0 ? _d : false)) {
                anyHidden = true;
                continue;
            }
            v.push((0, jsx_runtime_1.jsx)(Strategy, { strategy: strategy }, strategy.name));
        }
    }
    catch (e_2_1) { e_2 = { error: e_2_1 }; }
    finally {
        try {
            if (strategies_2_1 && !strategies_2_1.done && (_b = strategies_2.return)) _b.call(strategies_2);
        }
        finally { if (e_2) throw e_2.error; }
    }
    // link to the page for additional non-public institutional SSOs
    function hidden() {
        return ((0, jsx_runtime_1.jsxs)("div", __assign({ style: { marginTop: "1rem" } }, { children: ["or other", " ", (0, jsx_runtime_1.jsx)(antd_1.Button, __assign({ type: "link", style: { padding: 0 }, onClick: function () { return 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(_a) {
    var strategy = _a.strategy, onUnlink = _a.onUnlink;
    function unlinkButton() {
        if (!onUnlink)
            return;
        return ((0, jsx_runtime_1.jsx)("div", __assign({ style: { marginTop: "5px" } }, { children: (0, jsx_runtime_1.jsxs)(antd_1.Popconfirm, __assign({ title: (0, jsx_runtime_1.jsxs)("div", __assign({ 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, __assign({ type: "dashed", danger: true }, { children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "unlink" }), "Unlink"] }))] })) })));
    }
    return ((0, jsx_runtime_1.jsxs)("div", __assign({ 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 ".concat(strategy.display, ".")
                    : undefined }), unlinkButton()] })));
}
function SpacedStrategies(_a) {
    var children = _a.children;
    return ((0, jsx_runtime_1.jsx)(antd_1.Space, __assign({ size: [20, 20], wrap: true }, { children: children })));
}
//# sourceMappingURL=sso.js.map