"use strict";
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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SamlProvider = void 0;
var samlp = require("samlp");
var Config_1 = require("./Config");
var Audit_1 = require("./Audit");
var LoginProvider_1 = require("./LoginProvider");
var openflow_api_1 = require("@openiap/openflow-api");
var Logger_1 = require("./Logger");
var WebServer_1 = require("./WebServer");
var SamlProvider = /** @class */ (function () {
    function SamlProvider() {
    }
    SamlProvider.profileMapper = function (pu) {
        return {
            pu: pu,
            getClaims: function () {
                var _this = this;
                var claims = {};
                var k = Object.keys(this.pu);
                k.forEach(function (key) {
                    if (key.indexOf("http://") === 0) {
                        claims[key] = _this.pu[key];
                    }
                    else {
                        switch (key) {
                            case "id":
                                claims["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"] = _this.pu[key];
                                break;
                            case "displayName":
                                claims["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"] = _this.pu[key];
                                break;
                            case "name":
                                claims["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"] = _this.pu[key];
                                break;
                            case "mobile":
                                claims["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/mobile"] = _this.pu[key];
                                break;
                            case "username":
                                claims["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"] = _this.pu[key];
                                break;
                            case "emails":
                                claims["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"] = _this.pu[key][0];
                                claims["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"] = _this.pu[key][0];
                                break;
                            case "roles":
                                var roles_1 = [];
                                _this.pu[key].forEach(function (role) {
                                    roles_1.push(role.name);
                                });
                                claims["http://schemas.xmlsoap.org/claims/Group"] = roles_1;
                        }
                    }
                });
                return claims;
            },
            getNameIdentifier: function () {
                var claims = this.getClaims();
                return {
                    nameIdentifier: claims["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"] ||
                        claims["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"] ||
                        claims["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"]
                };
            }
        };
    };
    SamlProvider.configure = function (app, baseurl) {
        var _this = this;
        var cert = Buffer.from(Config_1.Config.signing_crt, "base64").toString("ascii");
        var key = Buffer.from(Config_1.Config.singing_key, "base64").toString("ascii");
        var samlpoptions = {
            issuer: Config_1.Config.saml_issuer,
            cert: cert,
            key: key,
            getPostURL: function (wtrealm, wreply, req, callback) {
                (function () { return __awaiter(_this, void 0, void 0, function () {
                    return __generator(this, function (_a) {
                        if (typeof wreply === "object") {
                            wreply = wreply.documentElement.getAttribute("AssertionConsumerServiceURL");
                        }
                        return [2 /*return*/, callback(null, wreply)];
                    });
                }); })();
            },
            getUserFromRequest: function (req) {
                var span = Logger_1.Logger.otel.startSpan("SAML.getUserFromRequest");
                try {
                    var tuser = openflow_api_1.TokenUser.From(req.user);
                    var remoteip = WebServer_1.WebServer.remoteip(req);
                    span.setAttribute("remoteip", remoteip);
                    Audit_1.Audit.LoginSuccess(tuser, "tokenissued", "saml", remoteip, "getUserFromRequest", "unknown", span);
                }
                catch (error) {
                    span.recordException(error);
                }
                Logger_1.Logger.otel.endSpan(span);
                return req.user;
            },
            profileMapper: SamlProvider.profileMapper,
            lifetimeInSeconds: (3600 * 24)
        };
        app.get("/issue/", function (req, res, next) {
            if (req.query.SAMLRequest !== undefined && req.query.SAMLRequest !== null) {
                if ((req.user === undefined || req.user === null)) {
                    try {
                        // tslint:disable-next-line: max-line-length
                        samlp.parseRequest(req, samlpoptions, function (_err, samlRequestDom) { return __awaiter(_this, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                res.cookie("originalUrl", req.originalUrl, { maxAge: 900000, httpOnly: true });
                                res.redirect("/");
                                return [2 /*return*/];
                            });
                        }); });
                    }
                    catch (error) {
                        res.body(error.message ? error.message : error);
                        res.end();
                        console.error(error.message ? error.message : error);
                    }
                }
                else {
                    // continue with issuing token using samlp
                    next();
                }
            }
            else {
                res.send("Please login again");
                res.end();
            }
        });
        app.get("/issue/", samlp.auth(samlpoptions));
        app.get("/issue/FederationMetadata/2007-06/FederationMetadata.xml", samlp.metadata({
            issuer: Config_1.Config.saml_issuer,
            cert: cert,
        }));
        // const SessionParticipants = require('samlp/lib/sessionParticipants');
        // https://github.com/mcguinness/saml-idp/blob/master/app.js
        // https://www.diycode.cc/projects/auth0/node-samlp
        // https://github.com/auth0/node-samlp/blob/master/lib/sessionParticipants/index.js
        // app.get('/logout', samlp.logout({
        //     deflate:            true,
        //     issuer:             'the-issuer',
        //     protocolBinding:    'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
        //     cert:               cert,
        //     key:                key
        // }));
        // TODO: FIX !!!!
        app.get('/wssignout', function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
            var html;
            return __generator(this, function (_a) {
                req.logout();
                html = "<html><head></head><body>";
                html += "<h1>Du er nu logget ud</h1><br>";
                // html += "<br/><p><a href='/'>Til login</ifarame></p>";
                html += "</body></html>";
                res.send(html);
                return [2 /*return*/];
            });
        }); });
        app.post('/wssignout', function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
            var html;
            return __generator(this, function (_a) {
                req.logout();
                html = "<html><head></head><body>";
                html += "<h1>Du er nu logget ud</h1><br>";
                // html += "<br/><p><a href='/'>Til login</ifarame></p>";
                html += "</body></html>";
                res.send(html);
                return [2 /*return*/];
            });
        }); });
        app.get('/logout', function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
            var referer, providerid, p, provider, html;
            return __generator(this, function (_a) {
                referer = req.headers.referer;
                providerid = req.cookies.provider;
                req.logout();
                if (!openflow_api_1.NoderedUtil.IsNullEmpty(providerid)) {
                    p = LoginProvider_1.LoginProvider.login_providers.filter(function (x) { return x.id == providerid; });
                    if (p.length > 0) {
                        provider = p[0];
                        if (!openflow_api_1.NoderedUtil.IsNullEmpty(provider.saml_signout_url)) {
                            html = "<html><head></head><body>";
                            html += "<h1>Logud</h1><br>";
                            if (!openflow_api_1.NoderedUtil.IsNullEmpty(referer)) {
                                html += "<br/><p><a href='" + encodeURI(referer) + "'>Til login</a></p>";
                            }
                            else {
                                html += "<br/><p><a href='/'>Til login</a></p>";
                            }
                            html += "<iframe src='" + encodeURI(provider.saml_signout_url) + "'></iframe>";
                            if (!openflow_api_1.NoderedUtil.IsNullEmpty(referer)) {
                                html += "<br/><p><a href='" + encodeURI(referer) + "'>Til login</a></p>";
                            }
                            else {
                                html += "<br/><p><a href='/'>Til login</a></p>";
                            }
                            html += "</body></html>";
                            res.send(html);
                            return [2 /*return*/];
                        }
                    }
                }
                if (!openflow_api_1.NoderedUtil.IsNullEmpty(referer)) {
                    res.redirect(referer);
                }
                else {
                    res.redirect("/");
                }
                return [2 /*return*/];
            });
        }); });
        app.post('/logout', function (req, res, next) {
            samlp.logout({
                issuer: Config_1.Config.saml_issuer,
                protocolBinding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
                cert: cert,
                key: key
            })(req, res, next);
        });
    };
    return SamlProvider;
}());
exports.SamlProvider = SamlProvider;
//# sourceMappingURL=SamlProvider.js.map