node-ldapjs/docs/examples.md

626 lines
14 KiB
Markdown
Raw Normal View History

---
2011-08-26 18:00:21 +00:00
title: Examples | ldapjs
---
2011-08-26 18:00:21 +00:00
# ldapjs Examples
2011-08-24 19:38:23 +00:00
2020-12-13 08:06:45 +00:00
<div class="intro">
2011-08-24 19:38:23 +00:00
This page contains a (hopefully) growing list of sample code to get you started
with ldapjs.
2020-12-13 08:06:45 +00:00
</div>
# In-memory server
2021-02-24 22:03:35 +00:00
```js
const ldap = require('ldapjs');
2021-02-24 22:03:35 +00:00
///--- Shared handlers
2021-02-24 22:03:35 +00:00
function authorize(req, res, next) {
/* Any user may search after bind, only cn=root has full power */
const isSearch = (req instanceof ldap.SearchRequest);
if (!req.connection.ldap.bindDN.equals('cn=root') && !isSearch)
return next(new ldap.InsufficientAccessRightsError());
2021-02-24 22:03:35 +00:00
return next();
}
2021-02-24 22:03:35 +00:00
///--- Globals
2021-02-24 22:03:35 +00:00
const SUFFIX = 'o=joyent';
const db = {};
const server = ldap.createServer();
2021-02-24 22:03:35 +00:00
server.bind('cn=root', (req, res, next) => {
if (req.dn.toString() !== 'cn=root' || req.credentials !== 'secret')
return next(new ldap.InvalidCredentialsError());
2021-02-24 22:03:35 +00:00
res.end();
return next();
});
2021-02-24 22:03:35 +00:00
server.add(SUFFIX, authorize, (req, res, next) => {
const dn = req.dn.toString();
2021-02-24 22:03:35 +00:00
if (db[dn])
return next(new ldap.EntryAlreadyExistsError(dn));
2021-02-24 22:03:35 +00:00
db[dn] = req.toObject().attributes;
res.end();
return next();
});
2021-02-24 22:03:35 +00:00
server.bind(SUFFIX, (req, res, next) => {
const dn = req.dn.toString();
if (!db[dn])
return next(new ldap.NoSuchObjectError(dn));
2021-02-24 22:03:35 +00:00
if (!db[dn].userpassword)
return next(new ldap.NoSuchAttributeError('userPassword'));
2021-02-24 22:03:35 +00:00
if (db[dn].userpassword.indexOf(req.credentials) === -1)
return next(new ldap.InvalidCredentialsError());
2021-02-24 22:03:35 +00:00
res.end();
return next();
});
2021-02-24 22:03:35 +00:00
server.compare(SUFFIX, authorize, (req, res, next) => {
const dn = req.dn.toString();
if (!db[dn])
return next(new ldap.NoSuchObjectError(dn));
2021-02-24 22:03:35 +00:00
if (!db[dn][req.attribute])
return next(new ldap.NoSuchAttributeError(req.attribute));
2021-02-24 22:03:35 +00:00
const matches = false;
const vals = db[dn][req.attribute];
for (const value of vals) {
if (value === req.value) {
matches = true;
break;
}
}
res.end(matches);
return next();
});
server.del(SUFFIX, authorize, (req, res, next) => {
const dn = req.dn.toString();
if (!db[dn])
return next(new ldap.NoSuchObjectError(dn));
delete db[dn];
res.end();
return next();
});
server.modify(SUFFIX, authorize, (req, res, next) => {
const dn = req.dn.toString();
if (!req.changes.length)
return next(new ldap.ProtocolError('changes required'));
if (!db[dn])
return next(new ldap.NoSuchObjectError(dn));
const entry = db[dn];
for (const change of req.changes) {
mod = change.modification;
switch (change.operation) {
case 'replace':
if (!entry[mod.type])
return next(new ldap.NoSuchAttributeError(mod.type));
if (!mod.vals || !mod.vals.length) {
delete entry[mod.type];
} else {
entry[mod.type] = mod.vals;
}
2021-02-24 22:03:35 +00:00
break;
2021-02-24 22:03:35 +00:00
case 'add':
if (!entry[mod.type]) {
entry[mod.type] = mod.vals;
} else {
for (const v of mod.vals) {
if (entry[mod.type].indexOf(v) === -1)
entry[mod.type].push(v);
}
}
2021-02-24 22:03:35 +00:00
break;
2021-02-24 22:03:35 +00:00
case 'delete':
if (!entry[mod.type])
return next(new ldap.NoSuchAttributeError(mod.type));
2021-02-24 22:03:35 +00:00
delete entry[mod.type];
2021-02-24 22:03:35 +00:00
break;
}
}
2021-02-24 22:03:35 +00:00
res.end();
return next();
});
2021-02-24 22:03:35 +00:00
server.search(SUFFIX, authorize, (req, res, next) => {
const dn = req.dn.toString();
if (!db[dn])
return next(new ldap.NoSuchObjectError(dn));
2021-02-24 22:03:35 +00:00
let scopeCheck;
2021-02-24 22:03:35 +00:00
switch (req.scope) {
case 'base':
if (req.filter.matches(db[dn])) {
res.send({
dn: dn,
attributes: db[dn]
});
}
2021-02-24 22:03:35 +00:00
res.end();
return next();
2021-02-24 22:03:35 +00:00
case 'one':
scopeCheck = (k) => {
if (req.dn.equals(k))
return true;
2021-02-24 22:03:35 +00:00
const parent = ldap.parseDN(k).parent();
return (parent ? parent.equals(req.dn) : false);
};
break;
2021-02-24 22:03:35 +00:00
case 'sub':
scopeCheck = (k) => {
return (req.dn.equals(k) || req.dn.parentOf(k));
};
2021-02-24 22:03:35 +00:00
break;
}
2021-02-24 22:03:35 +00:00
const keys = Object.keys(db);
for (const key of keys) {
if (!scopeCheck(key))
return;
if (req.filter.matches(db[key])) {
res.send({
dn: key,
attributes: db[key]
});
2021-02-24 22:03:35 +00:00
}
}
2021-02-24 22:03:35 +00:00
res.end();
return next();
});
2021-02-24 22:03:35 +00:00
///--- Fire it up
2021-02-24 22:03:35 +00:00
server.listen(1389, () => {
console.log('LDAP server up at: %s', server.url);
});
```
# /etc/passwd server
2021-02-24 22:03:35 +00:00
```js
const fs = require('fs');
const ldap = require('ldapjs');
const { spawn } = require('child_process');
2021-02-24 22:03:35 +00:00
///--- Shared handlers
2021-02-24 22:03:35 +00:00
function authorize(req, res, next) {
if (!req.connection.ldap.bindDN.equals('cn=root'))
return next(new ldap.InsufficientAccessRightsError());
2021-02-24 22:03:35 +00:00
return next();
}
2021-02-24 22:03:35 +00:00
function loadPasswdFile(req, res, next) {
fs.readFile('/etc/passwd', 'utf8', (err, data) => {
if (err)
return next(new ldap.OperationsError(err.message));
2021-02-24 22:03:35 +00:00
req.users = {};
2021-02-24 22:03:35 +00:00
const lines = data.split('\n');
for (const line of lines) {
if (!line || /^#/.test(line))
continue;
2021-02-24 22:03:35 +00:00
const record = line.split(':');
if (!record || !record.length)
continue;
2021-02-24 22:03:35 +00:00
req.users[record[0]] = {
dn: 'cn=' + record[0] + ', ou=users, o=myhost',
attributes: {
cn: record[0],
uid: record[2],
gid: record[3],
description: record[4],
homedirectory: record[5],
shell: record[6] || '',
objectclass: 'unixUser'
}
};
}
2021-02-24 22:03:35 +00:00
return next();
});
}
2021-02-24 22:03:35 +00:00
const pre = [authorize, loadPasswdFile];
2021-02-24 22:03:35 +00:00
///--- Mainline
2021-02-24 22:03:35 +00:00
const server = ldap.createServer();
2021-02-24 22:03:35 +00:00
server.bind('cn=root', (req, res, next) => {
if (req.dn.toString() !== 'cn=root' || req.credentials !== 'secret')
return next(new ldap.InvalidCredentialsError());
2021-02-24 22:03:35 +00:00
res.end();
return next();
});
2021-02-24 22:03:35 +00:00
server.add('ou=users, o=myhost', pre, (req, res, next) => {
if (!req.dn.rdns[0].cn)
return next(new ldap.ConstraintViolationError('cn required'));
2021-02-24 22:03:35 +00:00
if (req.users[req.dn.rdns[0].cn])
return next(new ldap.EntryAlreadyExistsError(req.dn.toString()));
2021-02-24 22:03:35 +00:00
const entry = req.toObject().attributes;
2021-02-24 22:03:35 +00:00
if (entry.objectclass.indexOf('unixUser') === -1)
return next(new ldap.ConstraintViolationError('entry must be a unixUser'));
2021-02-24 22:03:35 +00:00
const opts = ['-m'];
if (entry.description) {
opts.push('-c');
opts.push(entry.description[0]);
}
if (entry.homedirectory) {
opts.push('-d');
opts.push(entry.homedirectory[0]);
}
if (entry.gid) {
opts.push('-g');
opts.push(entry.gid[0]);
}
if (entry.shell) {
opts.push('-s');
opts.push(entry.shell[0]);
}
if (entry.uid) {
opts.push('-u');
opts.push(entry.uid[0]);
}
opts.push(entry.cn[0]);
const useradd = spawn('useradd', opts);
2021-02-24 22:03:35 +00:00
const messages = [];
2021-02-24 22:03:35 +00:00
useradd.stdout.on('data', (data) => {
messages.push(data.toString());
});
useradd.stderr.on('data', (data) => {
messages.push(data.toString());
});
2021-02-24 22:03:35 +00:00
useradd.on('exit', (code) => {
if (code !== 0) {
let msg = '' + code;
if (messages.length)
msg += ': ' + messages.join();
return next(new ldap.OperationsError(msg));
}
2021-02-24 22:03:35 +00:00
res.end();
return next();
});
});
server.modify('ou=users, o=myhost', pre, (req, res, next) => {
if (!req.dn.rdns[0].cn || !req.users[req.dn.rdns[0].cn])
return next(new ldap.NoSuchObjectError(req.dn.toString()));
if (!req.changes.length)
return next(new ldap.ProtocolError('changes required'));
const user = req.users[req.dn.rdns[0].cn].attributes;
let mod;
for (const change of req.changes) {
mod = change.modification;
switch (change.operation) {
case 'replace':
if (mod.type !== 'userpassword' || !mod.vals || !mod.vals.length)
return next(new ldap.UnwillingToPerformError('only password updates ' +
'allowed'));
break;
case 'add':
case 'delete':
return next(new ldap.UnwillingToPerformError('only replace allowed'));
}
}
2021-02-24 22:03:35 +00:00
const passwd = spawn('chpasswd', ['-c', 'MD5']);
passwd.stdin.end(user.cn + ':' + mod.vals[0], 'utf8');
2021-02-24 22:03:35 +00:00
passwd.on('exit', (code) => {
if (code !== 0)
return next(new ldap.OperationsError('' + code));
2021-02-24 22:03:35 +00:00
res.end();
return next();
});
});
2021-02-24 22:03:35 +00:00
server.del('ou=users, o=myhost', pre, (req, res, next) => {
if (!req.dn.rdns[0].cn || !req.users[req.dn.rdns[0].cn])
return next(new ldap.NoSuchObjectError(req.dn.toString()));
2021-02-24 22:03:35 +00:00
const userdel = spawn('userdel', ['-f', req.dn.rdns[0].cn]);
2021-02-24 22:03:35 +00:00
const messages = [];
userdel.stdout.on('data', (data) => {
messages.push(data.toString());
});
userdel.stderr.on('data', (data) => {
messages.push(data.toString());
});
2021-02-24 22:03:35 +00:00
userdel.on('exit', (code) => {
if (code !== 0) {
let msg = '' + code;
if (messages.length)
msg += ': ' + messages.join();
return next(new ldap.OperationsError(msg));
}
2021-02-24 22:03:35 +00:00
res.end();
return next();
});
});
2021-02-24 22:03:35 +00:00
server.search('o=myhost', pre, (req, res, next) => {
const keys = Object.keys(req.users);
for (const k of keys) {
if (req.filter.matches(req.users[k].attributes))
res.send(req.users[k]);
}
2021-02-24 22:03:35 +00:00
res.end();
return next();
});
2021-02-24 22:03:35 +00:00
// LDAP "standard" listens on 389, but whatever.
server.listen(1389, '127.0.0.1', () => {
console.log('/etc/passwd LDAP server up at: %s', server.url);
});
```
# Address Book
2011-09-13 17:46:17 +00:00
This example is courtesy of [Diogo Resende](https://github.com/dresende) and
illustrates setting up an address book for typical mail clients such as
Thunderbird or Evolution over a MySQL database.
2021-02-24 22:03:35 +00:00
```js
// MySQL test: (create on database 'abook' with username 'abook' and password 'abook')
//
// CREATE TABLE IF NOT EXISTS `users` (
// `id` int(5) unsigned NOT NULL AUTO_INCREMENT,
// `username` varchar(50) NOT NULL,
// `password` varchar(50) NOT NULL,
// PRIMARY KEY (`id`),
// KEY `username` (`username`)
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
// INSERT INTO `users` (`username`, `password`) VALUES
// ('demo', 'demo');
// CREATE TABLE IF NOT EXISTS `contacts` (
// `id` int(5) unsigned NOT NULL AUTO_INCREMENT,
// `user_id` int(5) unsigned NOT NULL,
// `name` varchar(100) NOT NULL,
// `email` varchar(255) NOT NULL,
// PRIMARY KEY (`id`),
// KEY `user_id` (`user_id`)
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
// INSERT INTO `contacts` (`user_id`, `name`, `email`) VALUES
// (1, 'John Doe', 'john.doe@example.com'),
// (1, 'Jane Doe', 'jane.doe@example.com');
//
const ldap = require('ldapjs');
const mysql = require("mysql");
const server = ldap.createServer();
const addrbooks = {};
const userinfo = {};
const ldap_port = 389;
const basedn = "dc=example, dc=com";
const company = "Example";
const db = mysql.createClient({
user: "abook",
password: "abook",
database: "abook"
});
db.query("SELECT c.*,u.username,u.password " +
"FROM contacts c JOIN users u ON c.user_id=u.id",
(err, contacts) => {
if (err) {
console.log("Error fetching contacts", err);
process.exit(1);
}
for (const contact of contacts) {
if (!addrbooks.hasOwnProperty(contact.username)) {
addrbooks[contact.username] = [];
userinfo["cn=" + contact.username + ", " + basedn] = {
abook: addrbooks[contact.username],
pwd: contact.password
};
}
2021-02-24 22:03:35 +00:00
const p = contact.name.indexOf(" ");
if (p != -1)
contact.firstname = contact.name.substr(0, p);
p = contact.name.lastIndexOf(" ");
if (p != -1)
contact.surname = contact.name.substr(p + 1);
addrbooks[contact.username].push({
dn: "cn=" + contact.name + ", " + basedn,
attributes: {
objectclass: [ "top" ],
cn: contact.name,
mail: contact.email,
givenname: contact.firstname,
sn: contact.surname,
ou: company
}
2021-02-24 22:03:35 +00:00
});
}
2021-02-24 22:03:35 +00:00
server.bind(basedn, (req, res, next) => {
const username = req.dn.toString();
const password = req.credentials;
2021-02-24 22:03:35 +00:00
if (!userinfo.hasOwnProperty(username) ||
userinfo[username].pwd != password) {
return next(new ldap.InvalidCredentialsError());
}
2021-02-24 22:03:35 +00:00
res.end();
return next();
});
2021-02-24 22:03:35 +00:00
server.search(basedn, (req, res, next) => {
const binddn = req.connection.ldap.bindDN.toString();
2021-02-24 22:03:35 +00:00
if (userinfo.hasOwnProperty(binddn)) {
for (const abook of userinfo[binddn].abook) {
if (req.filter.matches(abook.attributes))
res.send(abook);
}
}
res.end();
});
2021-02-24 22:03:35 +00:00
server.listen(ldap_port, () => {
console.log("Addressbook started at %s", server.url);
});
});
```
To test out this example, try:
2021-02-24 23:02:30 +00:00
```shell
2021-02-24 22:03:35 +00:00
$ ldapsearch -H ldap://localhost:389 -x -D cn=demo,dc=example,dc=com \
-w demo -b "dc=example,dc=com" objectclass=*
```
# Multi-threaded Server
This example demonstrates multi-threading via the `cluster` module utilizing a `net` server for initial socket receipt. An alternate example demonstrating use of the `connectionRouter` `serverOptions` hook is available in the `examples` directory.
2021-05-21 12:04:41 +00:00
```js
const cluster = require('cluster');
const ldap = require('ldapjs');
const net = require('net');
const os = require('os');
const threads = [];
threads.getNext = function () {
return (Math.floor(Math.random() * this.length));
};
const serverOptions = {
port: 1389
};
if (cluster.isMaster) {
const server = net.createServer(serverOptions, (socket) => {
socket.pause();
console.log('ldapjs client requesting connection');
let routeTo = threads.getNext();
threads[routeTo].send({ type: 'connection' }, socket);
});
for (let i = 0; i < os.cpus().length; i++) {
let thread = cluster.fork({
'id': i
});
thread.id = i;
thread.on('message', function (msg) {
});
threads.push(thread);
}
server.listen(serverOptions.port, function () {
console.log('ldapjs listening at ldap://127.0.0.1:' + serverOptions.port);
});
} else {
const server = ldap.createServer(serverOptions);
let threadId = process.env.id;
process.on('message', (msg, socket) => {
switch (msg.type) {
case 'connection':
server.newConnection(socket);
socket.resume();
console.log('ldapjs client connection accepted on ' + threadId.toString());
}
});
server.search('dc=example', function (req, res, next) {
console.log('ldapjs search initiated on ' + threadId.toString());
var obj = {
dn: req.dn.toString(),
attributes: {
objectclass: ['organization', 'top'],
o: 'example'
}
};
if (req.filter.matches(obj.attributes))
res.send(obj);
res.end();
});
}
```