#!/usr/bin/env node // -*- mode: js -*- // Copyright 2011 Mark Cavage. All rights reserved. var fs = require('fs'); var path = require('path'); var dashdash = require('dashdash'); var ldap = require('../lib/index'); var Logger = require('bunyan'); ///--- Globals dashdash.addOptionType({ name: 'ldap.DN', takesArg: true, helpArg: 'LDAP_DN', parseArg: function (option, optstr, arg) { return ldap.parseDN(arg); } }); var opts = [ { names: ['url', 'u'], type: 'string', help: 'LDAP server URL', helpArg: 'URL', default: 'ldap://127.0.0.1:389' }, { names: ['binddn', 'D'], type: 'ldap.DN', help: 'Bind DN', default: '' }, { names: ['password', 'w'], type: 'string', help: 'Bind password', helpArg: 'PASSWD', default: '' }, { names: ['file', 'f'], type: 'string', help: 'Input file', helpArg: 'FILE' }, { names: ['insecure', 'i'], type: 'bool', env: 'LDAPJS_TLS_INSECURE', help: 'Disable SSL certificate verification', default: false }, { names: ['debug', 'd'], type: 'integer', help: 'Set debug level <0-2>', helpArg: 'LEVEL' }, { names: ['help', 'h'], type: 'bool', help: 'Print this help and exit.' } ]; var parser = dashdash.createParser({options: opts}); ///--- Helpers function usage(code, message) { var _opts = parser.help(); var msg = (message ? message + '\n' : '') + 'usage: ' + path.basename(process.argv[1]) + ' [JSON]\n' + _opts; process.stderr.write(msg + '\n'); process.exit(code); } function perror(err) { if (parsed.debug) { process.stderr.write(err.stack + '\n'); } else { process.stderr.write(err.message + '\n'); } process.exit(1); } ///--- Mainline var logLevel = 'info'; var parsed; try { parsed = parser.parse(process.argv); if (parsed.file) { parsed.file = JSON.parse(fs.readFileSync(parsed.file, 'utf8')); if (!Array.isArray(parsed.file)) parsed.file = [parsed.file]; } } catch (e) { usage(1, e.toString()); } if (parsed.help) usage(0); if (!parsed.file) { parsed.file = []; parsed._args.forEach(function (a) { var o = JSON.parse(a); if (Array.isArray(o)) { o.forEach(function (i) { parsed.file.push(o); }); return; } parsed.file.push(o); }); if (parsed.file.length === 0) parsed.file = null; } if (!parsed.file) usage(1, 'either -f or stdin must be used for adding objects'); if (parsed.debug) logLevel = (parsed.debug > 1 ? 'trace' : 'debug'); var log = new Logger({ name: 'ldapjs', component: 'client', stream: process.stderr, level: logLevel }); var client = ldap.createClient({ url: parsed.url, log: log, tlsOptions: { rejectUnauthorized: !parsed.insecure } }); client.on('error', function (err) { perror(err); }); client.bind(parsed.binddn, parsed.password, function (err, res) { if (err) perror(err); var finished = 0; function callback(err) { if (err) perror(err); if (++finished === parsed.file.length) client.unbind(function () { return; }); } parsed.file.forEach(function (entry) { var dn = entry.dn; delete entry.dn; client.add(dn, entry, callback); }); });