<commit_before>var Mentat = require('mentat');
var Boom = require('boom');
var bcrypt = require('bcrypt');
var jwt = require('jsonwebtoken');
var redis = require('redis');
var ldap = require('ldapjs');

var client = redis.createClient();

var ldapServer = ldap.createServer();

// TODO: this all needs to be refactored O_o

function ldapAuth(username, password, callback) {
    var client = ldap.createClient({
        url: 'ldaps://' + Mentat.settings.auth.ldap.server + ':' + Mentat.settings.auth.ldap.port,
        tlsOptions: {
            rejectUnauthorized: !!Mentat.settings.auth.ldap.rejectUnauthorized
        }
    });

    var ldapFilterAttribute = Mentat.settings.auth.ldap.ldapFilterAttribute || 'sAMAccountName';
    var opts = {
        filter: '(&(objectclass=user)('+ ldapFilterAttribute + '=' + username + '))',
        scope: 'sub'
    };

    var rootDN = Mentat.settings.auth.ldap.rootDN || '';
    
    var targetDN;
    var serviceAccountDN = Mentat.settings.auth.ldap.serviceAccountDN;
    var serviceAccountPassword = Mentat.settings.auth.ldap.serviceAccountPassword;

    client.bind(serviceAccountDN, serviceAccountPassword, function initialBindDone (err) {
        if (err) {
            return callback(false, err);
        }

        client.search(rootDN, opts, function ldapSearchDone (err, result) {
            if (err) {
                return callback(false, err);
            }

            result.on('error', function onSearchError (err) {
                return callback(false, err);
            });

            result.on('searchEntry', function onSearchEntry (entry) {
                targetDN = entry.objectName;
            });

            result.on('end', function onSearchEnd (entry) {

                if (!targetDN) {
                    return callback(false, 'invalid user');
                }

                client.bind(targetDN, password, function ldapBindDone (err) {
                    client.unbind();

                    if (err) {
                        return callback(false, 'invalid password');
                    }

                    return callback(true);
                });
            });
        });
    });
}

function ldapAuthResponder(username, password, callback) {
    ldapAuth(username, password, function ldapAuthDone (result, err) {
        if (result) {
            return callback(createJwtToken(username));
        }

        console.log('XXX: ' + err);
        return callback(Boom.unauthorized(err));
    });
}

function createJwtToken(username) {
    var tokenPayload = {
        username: username
    };

    var token = jwt.sign(tokenPayload, Mentat.settings.auth.key, {
        expiresIn: Mentat.settings.auth.tokenTTL
    });
    
    return { token: token };
}

module.exports = new Mentat.Handler('Auth', {
    routes: [
        { method: 'POST', path: '/api/login', auth: false, handler: 'login' },
        { method: 'GET', path: '/api/logout', handler: 'logout' }<commit_msg>removed debug message<commit_after>var Mentat = require('mentat');
var Boom = require('boom');
var bcrypt = require('bcrypt');
var jwt = require('jsonwebtoken');
var redis = require('redis');
var ldap = require('ldapjs');

var client = redis.createClient();

var ldapServer = ldap.createServer();

// TODO: this all needs to be refactored O_o

function ldapAuth(username, password, callback) {
    var client = ldap.createClient({
        url: 'ldaps://' + Mentat.settings.auth.ldap.server + ':' + Mentat.settings.auth.ldap.port,
        tlsOptions: {
            rejectUnauthorized: !!Mentat.settings.auth.ldap.rejectUnauthorized
        }
    });

    var ldapFilterAttribute = Mentat.settings.auth.ldap.ldapFilterAttribute || 'sAMAccountName';
    var opts = {
        filter: '(&(objectclass=user)('+ ldapFilterAttribute + '=' + username + '))',
        scope: 'sub'
    };

    var rootDN = Mentat.settings.auth.ldap.rootDN || '';
    
    var targetDN;
    var serviceAccountDN = Mentat.settings.auth.ldap.serviceAccountDN;
    var serviceAccountPassword = Mentat.settings.auth.ldap.serviceAccountPassword;

    client.bind(serviceAccountDN, serviceAccountPassword, function initialBindDone (err) {
        if (err) {
            return callback(false, err);
        }

        client.search(rootDN, opts, function ldapSearchDone (err, result) {
            if (err) {
                return callback(false, err);
            }

            result.on('error', function onSearchError (err) {
                return callback(false, err);
            });

            result.on('searchEntry', function onSearchEntry (entry) {
                targetDN = entry.objectName;
            });

            result.on('end', function onSearchEnd (entry) {

                if (!targetDN) {
                    return callback(false, 'invalid user');
                }

                client.bind(targetDN, password, function ldapBindDone (err) {
                    client.unbind();

                    if (err) {
                        return callback(false, 'invalid password');
                    }

                    return callback(true);
                });
            });
        });
    });
}

function ldapAuthResponder(username, password, callback) {
    ldapAuth(username, password, function ldapAuthDone (result, err) {
        if (result) {
            return callback(createJwtToken(username));
        }

        return callback(Boom.unauthorized(err));
    });
}

function createJwtToken(username) {
    var tokenPayload = {
        username: username
    };

    var token = jwt.sign(tokenPayload, Mentat.settings.auth.key, {
        expiresIn: Mentat.settings.auth.tokenTTL
    });
    
    return { token: token };
}

module.exports = new Mentat.Handler('Auth', {
    routes: [
        { method: 'POST', path: '/api/login', auth: false, handler: 'login' },
        { method: 'GET', path: '/api/logout', handler: 'logout' }
{'fraction_non_alphanumeric': 0.12817044301657085, 'fraction_numerical': 0.0, 'mean_word_length': 2.214673913043478, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3728690', 'n_tokens_mistral': 1734, 'n_tokens_neox': 1655, 'n_words': 356}