rainbox.email/src/LDAPServerComponent.ts

61 lines
2.2 KiB
TypeScript

import ApplicationComponent from "wms-core/ApplicationComponent";
import {Express} from "express";
import ldap, {InvalidCredentialsError, Server} from "ldapjs";
import Logger from "wms-core/Logger";
import UserPasswordComponent from "./models/UserPasswordComponent";
import Throttler from "wms-core/Throttler";
import User from "wms-core/auth/models/User";
export default class LDAPServerComponent extends ApplicationComponent<void> {
private server?: Server;
public async start(app: Express): Promise<void> {
this.server = ldap.createServer({
log: console
});
this.server.bind('ou=users,dc=toot,dc=party', async (req: any, res: any, next: any) => {
const rdns = req.dn.toString().split(', ').map((rdn: string) => rdn.split('='));
let username;
let email;
for (const rdn of rdns) {
if (rdn[0] === 'cn') {
username = rdn[1];
} else if (rdn[0] === 'email') {
email = rdn[1];
}
}
Logger.debug('Matrix authentication attempt:', username, email);
try {
Throttler.throttle('ldap_auth', 3, 30 * 1000, username);
} catch (e) {
Logger.debug('Too many auth requests');
next(new InvalidCredentialsError());
return;
}
const user = await User.select().where('name', username).first();
if (user) {
const email = await user.mainEmail.get();
if (email) {
if (await user.as(UserPasswordComponent).verifyPassword(req.credentials)) {
Logger.debug('Success');
res.end();
return;
}
}
}
Logger.debug('Fail');
next(new InvalidCredentialsError());
});
this.server.unbind((req: any, res: any, next: any) => {
Logger.debug('Unbind', req);
next();
});
this.server.listen(8389, '127.0.0.1', () => {
Logger.info(`LDAP server listening on ${this.server!.url}`);
});
}
}