Skip to content
This repository has been archived by the owner on Jul 1, 2020. It is now read-only.

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
sandrinodimattia committed Feb 1, 2016
0 parents commit 44ff205
Show file tree
Hide file tree
Showing 16 changed files with 356 additions and 0 deletions.
9 changes: 9 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"presets": [
"es2015",
"stage-0"
],
"ignore": [
"./node_modules"
]
}
31 changes: 31 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"extends": "eslint:recommended",
"ecmaFeatures": {
"modules": true
},
"env": {
"browser": true,
"node": true,
"es6": true
},
"parser": "babel-eslint",
"rules": {
"array-bracket-spacing": [2, "always"],
"comma-dangle": [2, "never"],
"eol-last": 2,
"indent": [2, 2, {
"SwitchCase": 1
}],
"no-multiple-empty-lines": 2,
"no-unused-vars": 2,
"no-var": 2,
"object-curly-spacing": [2, "always"],
"quotes": [2, "single", "avoid-escape"],
"semi": [2, "always"],
"strict": 0,
"space-before-blocks": [2, "always"]
},
"plugins": [
"babel"
]
}
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
.DS_Store
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2015 Auth0, Inc. <[email protected]> (http://auth0.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
63 changes: 63 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Auth0 LDAP Endpoint

An LDAP server that allows you to connect your legacy applications with Auth0 using the LDAP protocol.

## Supported Features

* Bind
* Search (on email address only)

## Before Getting Started

In the `config.json` file set the following values:

- `AUTH0_DOMAIN`: Your Auth0 domain (fabrikam.auth0.com)
- `AUTH0_CLIENT_ID `: Your Auth0 Client Id
- `AUTH0_API_TOKEN `: Token for the Management API with `read:users` permission (used for search)
- `LDAP_PORT`: Port on which the LDAP server will listen
- `LDAP_ADMIN_USER`: The DN of the user that is allowed to do a search. Format: `CN=ADMIN_EMAIL_ADDRESS,OU=AUTH0_CONNECTION_NAME` (eg: `[email protected],OU=Username-Password-Authentication`)

## Usage

Install Node.js 5+, then start the server:

```
npm install
node index
```

This will start the LDAP server and allow users to bind and search.

## Example

The [example/test-client.js](example/test-client.js) script is a small sample that shows the supported features like `bind` and `search`:

```
node test-client.js
Bind success.
Searching for: {
"filter": "([email protected])",
"scope": "sub",
"attributes": [
"dn",
"sn",
"cn"
]
}
Found: {"dn":"[email protected], ou=Username-Password-Authentication","controls":[],"cn":"[email protected]"}
Found: {"dn":"[email protected], ou=google-oauth2","controls":[],"cn":"[email protected]"}
Search Done. Status: 0
```

## Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues.

## Author

[Auth0](auth0.com)

## License

This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info.
7 changes: 7 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"AUTH0_DOMAIN": "YOUR_AUTH0_DOMAIN",
"AUTH0_CLIENT_ID": "YOUR_AUTH0_CLIENT_ID",
"AUTH0_API_TOKEN": "YOUR_AUTH0_API_TOKEN",
"LDAP_PORT": 1389,
"LDAP_ADMIN_USER": "CN=ADMIN_EMAIL_ADDRESS,OU=AUTH0_CONNECTION_NAME"
}
40 changes: 40 additions & 0 deletions examples/test-client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
var ldap = require('ldapjs');
var client = ldap.createClient({
url: 'ldap://127.0.0.1:1389'
});

client.bind('[email protected],OU=Username-Password-Authentication', 'MyPassword', function(err) {
if (err) {
console.log('Bind Error:', JSON.stringify(err, null, 2));
return client.unbind(function(err) {
if (err) {
console.log(err);
}
});
}

console.log('Bind success.');

var opts = {
filter: '([email protected])',
scope: 'sub',
attributes: ['dn', 'sn', 'cn']
};

console.log(`Searching for: ${JSON.stringify(opts, null, 2)}`);

client.search('OU=Username-Password-Authentication', opts, function(err, res) {
res.on('searchEntry', function(entry) {
console.log('Found: ' + JSON.stringify(entry.object));
});
res.on('searchReference', function(referral) {
console.log('Referral: ' + referral.uris.join());
});
res.on('error', function(err) {
console.error('Error: ' + err.message);
});
res.on('end', function(result) {
console.log('Search Done. Status: ' + result.status);
});
});
});
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
require('babel-core/register')({
ignore: /node_modules/
});

// Start server.
require('./server');
15 changes: 15 additions & 0 deletions lib/logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import winston from 'winston';

const logger = new winston.Logger({
transports: [
new winston.transports.Console({
timestamp: true,
level: 'debug',
handleExceptions: true,
json: false,
colorize: true
})
],
exitOnError: false
});
export default logger;
5 changes: 5 additions & 0 deletions lib/middleware/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import requireAdministrator from './requireAdministrator';

export {
requireAdministrator
};
8 changes: 8 additions & 0 deletions lib/middleware/requireAdministrator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import ldap from 'ldapjs';
import nconf from 'nconf';

module.exports = (req, res, next) => {
if (!req.connection.ldap.bindDN.equals(`${nconf.get('LDAP_ADMIN_USER')}`))
return next(new ldap.InsufficientAccessRightsError());
return next();
};
30 changes: 30 additions & 0 deletions lib/routes/authenticate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import ldap from 'ldapjs';
import auth0 from 'auth0';
import logger from '../logger';

export default function(domain, clientId) {
const client = new auth0.AuthenticationClient({
domain: domain,
clientId: clientId
});

return (req, res, next) => {
logger.debug(`Bind attempt with ${req.dn.toString()}`);

const parsedName = req.dn.toString().match(/cn=(.*), ou=(.*)/);
if (!parsedName || parsedName.length != 3) {
logger.error(`The username '${req.dn.toString()}' does not match 'CN=username,OU=connection'`);
return next(new ldap.InvalidDnSyntaxError(`The username '${req.dn.toString()}' does not match 'CN=username,OU=connection'`));
}

client.oauth.signIn({ username: parsedName[1], password: req.credentials, connection: parsedName[2] })
.then(() => {
logger.info(`Bind success for ${req.dn.toString()}`);
res.end();
return next();
}).catch(err => {
logger.error(`Bind failed for ${req.dn.toString()}: "${err.name}"`);
return next(new ldap.InvalidCredentialsError());
});
};
}
7 changes: 7 additions & 0 deletions lib/routes/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import search from './search';
import authenticate from './authenticate';

export {
search,
authenticate
};
58 changes: 58 additions & 0 deletions lib/routes/search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import ldap from 'ldapjs';
import auth0 from 'auth0';
import logger from '../logger';

export default function(domain, token) {
const client = new auth0.ManagementClient({
domain: domain,
token: token
});

return function(req, res, next) {
logger.info(`Searching '${req.dn.toString()}' (scope: ${req.scope || 'N/A'}, attributes: ${req.attributes || 'N/A'}): ${JSON.stringify(req.filter.json, null, 2)}`);

const parsedUnit = req.dn.toString().match(/ou=(.*)/);
if (!parsedUnit || parsedUnit.length != 2) {
logger.error(`The distinguished name '${req.dn.toString()}' does not match 'OU=Auth0-Connection-Name'`);
return next(new ldap.InvalidDnSyntaxError(`The distinguished name '${req.dn.toString()}' does not match 'OU=Auth0-Connection-Name'`));
}

if (!req.filter.json || req.filter.json.type != 'EqualityMatch' || req.filter.json.attribute != 'email') {
logger.error(`This server only allows you to search for users by email.`);
return next(new ldap.UnwillingToPerformError(`This server only allows you to search for users by email.`));
}

const params = {
per_page: 10,
search_engine: 'v2',
connection: parsedUnit[1],
q: `email:"${req.filter.json.value}"`
};

logger.debug(`Searching for: ${JSON.stringify(params, null, 2)}`);

client.getUsers(params, (err, users) => {
if (err) {
logger.error(`Search error: ${JSON.stringify(err, null, 2)}`);
return next(new ldap.OperationsError('Search failed.'));
}

users.forEach(user => {
logger.debug(`Found user: ${JSON.stringify(user, null, 2)}`);

res.send({
dn: `CN=${user.email}, OU=${user.identities[0].connection}`,
attributes: {
userPrincipalName: user.email,
cn: user.email,
objectClass: [ 'user' ],
objectCategory: [ 'user' ]
}
});
});

res.end();
return next();
});
};
}
30 changes: 30 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "node-ldapjs-auth0",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"auth0": "^2.0.0",
"babel-core": "^6.4.0",
"babel-preset-es2015": "^6.3.13",
"babel-preset-es2015-loose": "^6.1.4",
"babel-preset-stage-0": "^6.3.13",
"ldapjs": "^1.0.0",
"nconf": "^0.8.2",
"superagent": "^1.7.2",
"winston": "^2.1.1"
},
"engines": {
"node": "5.3.0"
},
"devDependencies": {
"babel-eslint": "^4.1.6",
"eslint": "^1.10.3",
"eslint-plugin-babel": "^3.0.0"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
24 changes: 24 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import path from 'path';
import ldap from 'ldapjs';
import nconf from 'nconf';

import logger from './lib/logger';
import { authenticate, search } from './lib/routes';
import { requireAdministrator } from './lib/middleware';

nconf
.argv()
.env()
.file(path.join(__dirname, 'config.json'))
.defaults({
LDAP_PORT: 389
});

logger.info('Starting LDAP endpoint for Auth...');

const server = ldap.createServer();
server.bind('', authenticate(nconf.get('AUTH0_DOMAIN'), nconf.get('AUTH0_CLIENT_ID')));
server.search('', requireAdministrator, search(nconf.get('AUTH0_DOMAIN'), nconf.get('AUTH0_API_TOKEN')));
server.listen(nconf.get('LDAP_PORT'), () => {
logger.info(`LDAP server listening on: ${server.url}`);
});

0 comments on commit 44ff205

Please sign in to comment.