"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UserCtrl = void 0;
const LdapClient = __importStar(require("ldapjs"));
const request = __importStar(require("request"));
const fs_1 = require("fs");
const config_1 = require("../config");
const config_2 = require("../config");
class UserCtrl {
    constructor(router) {
        // uncomment the following line to use customized login
        // router.route('/user/authorize').get(this.authorize);
        router.route('/user/login').post(this.login.bind(this));
        router.route('/user/current').get(this.current);
        router.route('/user/can').get(this.can);
    }
    //
    // You may rewrite this function to support your own authorization logic.
    // Usually it would be helpful to integrate with 3rd party login.
    // For example:
    //
    /*
    protected authorize(req: HelixRequest, res: Response) {
      const { isAdmin, username, token } = get_auth_state();
      req.session.isAdmin = isAdmin;
      req.session.username = username;
      req.session.identityToken = token;
      res.redirect('/');
    }
    */
    current(req, res) {
        res.json(req.session.username || 'Sign In');
    }
    //
    // Check the server-side session store,
    // see if this helix-front ExpressJS server
    // already knows that the current user is an admin.
    //
    can(req, res) {
        try {
            return res.json(req.session.isAdmin ? true : false);
        }
        catch (err) {
            throw new Error(`Error from /can logged in admin user session status endpoint: ${err}`);
            return false;
        }
    }
    login(req, res) {
        const credential = req.body;
        if (!credential.username || !credential.password) {
            res.status(401).json(false);
            return;
        }
        // check LDAP
        const ldap = LdapClient.createClient({ url: config_1.LDAP.uri });
        ldap.bind(credential.username + config_1.LDAP.principalSuffix, credential.password, (err) => {
            if (err) {
                res.status(401).json(false);
            }
            else {
                // LDAP login success
                const opts = {
                    filter: '(&(sAMAccountName=' +
                        credential.username +
                        ')(objectcategory=person))',
                    scope: 'sub',
                };
                req.session.username = credential.username;
                res.set('Username', credential.username);
                ldap.search(config_1.LDAP.base, opts, function (err, result) {
                    let isInAdminGroup = false;
                    result.on('searchEntry', function (entry) {
                        if (entry.object && !err) {
                            const groups = entry.object['memberOf'];
                            for (const group of groups) {
                                const groupName = group.split(',', 1)[0].split('=')[1];
                                if (groupName == config_1.LDAP.adminGroup) {
                                    isInAdminGroup = true;
                                    //
                                    // Get an Identity-Token
                                    // if an IDENTITY_TOKEN_SOURCE
                                    // is specified in the config
                                    //
                                    if (config_1.IDENTITY_TOKEN_SOURCE) {
                                        const body = JSON.stringify(Object.assign({ username: credential.username, password: credential.password }, config_1.CUSTOM_IDENTITY_TOKEN_REQUEST_BODY));
                                        const options = {
                                            url: config_1.IDENTITY_TOKEN_SOURCE,
                                            json: '',
                                            body,
                                            headers: {
                                                'Content-Type': 'application/json',
                                            },
                                            agentOptions: {
                                                rejectUnauthorized: false,
                                            },
                                        };
                                        if (config_1.SSL.cafiles.length > 0) {
                                            options.agentOptions.ca = (0, fs_1.readFileSync)(config_1.SSL.cafiles[0], {
                                                encoding: 'utf-8',
                                            });
                                        }
                                        function callback(error, _res, body) {
                                            if (error) {
                                                throw new Error(`Failed to get ${config_1.IDENTITY_TOKEN_SOURCE} Token: ${error}`);
                                            }
                                            else if (body === null || body === void 0 ? void 0 : body.error) {
                                                throw new Error(body === null || body === void 0 ? void 0 : body.error);
                                            }
                                            else {
                                                const parsedBody = JSON.parse(body);
                                                req.session.isAdmin = isInAdminGroup;
                                                req.session.identityToken = parsedBody;
                                                const cookieName = 'helixui_identity.token';
                                                const cookieValue = parsedBody.value[config_2.TOKEN_RESPONSE_KEY];
                                                const cookieExpiresDate = new Date(parsedBody.value[config_2.TOKEN_EXPIRATION_KEY]);
                                                const cookieOptions = {
                                                    expires: cookieExpiresDate,
                                                };
                                                res.cookie(cookieName, cookieValue, cookieOptions);
                                                res.json(isInAdminGroup);
                                                return parsedBody;
                                            }
                                        }
                                        request.post(options, callback);
                                    }
                                    else {
                                        req.session.isAdmin = isInAdminGroup;
                                        res.json(isInAdminGroup);
                                    }
                                    //
                                    // END Get an Identity-Token
                                    //
                                }
                            }
                        }
                        else {
                            req.session.isAdmin = isInAdminGroup;
                            res.json(isInAdminGroup);
                        }
                    });
                });
            }
        });
    }
}
exports.UserCtrl = UserCtrl;
//# sourceMappingURL=user.js.map