ldapAuthenticationHandler.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { Client } from "ldapts";
  2. import { TotpChecker } from "./totpChecker.js";
  3. export class LdapAuthenticationHandler {
  4. configuration;
  5. constructor(configuration) {
  6. this.configuration = configuration;
  7. }
  8. fieldToString(data) {
  9. if (typeof data === "string")
  10. return data;
  11. if (Array.isArray(data))
  12. return this.fieldToString(data[0]);
  13. return data.toString("utf8");
  14. }
  15. async tryBind(username, password) {
  16. if (!username || !password)
  17. return null;
  18. const client = new Client({
  19. url: this.configuration.ldapUrl,
  20. timeout: 0,
  21. connectTimeout: 0,
  22. tlsOptions: {
  23. minVersion: 'TLSv1.2',
  24. },
  25. strictDN: true,
  26. });
  27. const bindDn = `${this.configuration.bindDnField}=${username},${this.configuration.bindBase}`;
  28. let totp = null;
  29. let finalUsername = null;
  30. let success = false;
  31. try {
  32. await client.bind(bindDn, password);
  33. const data = await client.search(bindDn, {
  34. filter: this.configuration.ldapFilter || undefined,
  35. attributes: [this.configuration.totpField, this.configuration.usernameField, this.configuration.bindDnField].filter(x => !!x)
  36. });
  37. if (data.searchEntries[0]) {
  38. success = true;
  39. totp = this.configuration.totpField ? this.fieldToString(data.searchEntries[0]?.[this.configuration.totpField]) : null;
  40. finalUsername = this.configuration.usernameField ? this.fieldToString(data.searchEntries[0]?.[this.configuration.usernameField]) : username;
  41. }
  42. }
  43. catch (ex) {
  44. console.error(ex);
  45. return null;
  46. }
  47. finally {
  48. client.unbind();
  49. }
  50. return success ? {
  51. username: finalUsername,
  52. totp: totp
  53. } : null;
  54. }
  55. async tryLogin(username, password, totp) {
  56. const account = await this.tryBind(username, password);
  57. console.log(account);
  58. if (!account)
  59. return null;
  60. return TotpChecker.ValidateTotp(account.totp, totp);
  61. }
  62. async needTotp(username, password) {
  63. const account = await this.tryBind(username, password);
  64. if (!account)
  65. return null;
  66. return !!account.totp;
  67. }
  68. }
  69. //# sourceMappingURL=ldapAuthenticationHandler.js.map