"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LdapClient = require("ldapjs");
var config_1 = require("../config");
var UserCtrl = (function () {
    function UserCtrl(router) {
        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);
    }
    UserCtrl.prototype.authorize = function (req, res) {
        // you can rewrite this function to support your own authorization logic
        // by default, doing nothing but redirection
        if (req.query.url) {
            res.redirect(req.query.url);
        }
        else {
            res.redirect('/');
        }
    };
    UserCtrl.prototype.current = function (req, res) {
        res.json(req.session.username || 'Sign In');
    };
    UserCtrl.prototype.can = function (req, res) {
        res.json(req.session.isAdmin ? true : false);
    };
    UserCtrl.prototype.login = function (request, response) {
        var credential = request.body;
        if (!credential.username || !credential.password) {
            response.status(401).json(false);
            return;
        }
        // check LDAP
        var ldap = LdapClient.createClient({ url: config_1.LDAP.uri });
        ldap.bind(credential.username + config_1.LDAP.principalSuffix, credential.password, function (err) {
            if (err) {
                response.status(401).json(false);
            }
            else {
                // login success
                var opts = {
                    filter: '(&(sAMAccountName=' + credential.username + ')(objectcategory=person))',
                    scope: 'sub'
                };
                ldap.search(config_1.LDAP.base, opts, function (err, result) {
                    var isInAdminGroup = false;
                    result.on('searchEntry', function (entry) {
                        if (entry.object && !err) {
                            var groups = entry.object["memberOf"];
                            for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) {
                                var group = groups_1[_i];
                                var groupName = group.split(",", 1)[0].split("=")[1];
                                if (groupName == config_1.LDAP.adminGroup) {
                                    isInAdminGroup = true;
                                    break;
                                }
                            }
                        }
                        request.session.username = credential.username;
                        request.session.isAdmin = isInAdminGroup;
                        response.json(isInAdminGroup);
                    });
                });
            }
        });
    };
    return UserCtrl;
}());
exports.UserCtrl = UserCtrl;
//# sourceMappingURL=user.js.map
