ldapAuthenticationHandler.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. async tryBind(username, password) {
  9. if (!username || !password)
  10. return null;
  11. const client = new Client({
  12. url: this.configuration.ldapUrl,
  13. timeout: 0,
  14. connectTimeout: 0,
  15. tlsOptions: {
  16. minVersion: 'TLSv1.2',
  17. },
  18. strictDN: true,
  19. });
  20. const bindDn = `${this.configuration.bindDnField}=${username},${this.configuration.bindRoot}`;
  21. let totp = null;
  22. try {
  23. await client.bind(bindDn, password);
  24. if (this.configuration.totpField) {
  25. const data = await client.search(bindDn);
  26. let totpData = data.searchEntries[0]?.[this.configuration.totpField];
  27. if (typeof totpData === "string")
  28. totp = totpData;
  29. if (Array.isArray(totpData))
  30. totp = totpData.join("");
  31. else
  32. totp = totpData.toString("utf8");
  33. }
  34. }
  35. catch (ex) {
  36. console.error(ex);
  37. return null;
  38. }
  39. finally {
  40. client.unbind();
  41. }
  42. return {
  43. username: username,
  44. totp: totp
  45. };
  46. }
  47. async tryLogin(username, password, totp) {
  48. const account = await this.tryBind(username, password);
  49. if (!account)
  50. return null;
  51. return TotpChecker.ValidateTotp(account.totp, totp);
  52. }
  53. async needTotp(username, password) {
  54. const account = await this.tryBind(username, password);
  55. if (!account)
  56. return null;
  57. return !!account.totp;
  58. }
  59. }
  60. //# sourceMappingURL=ldapAuthenticationHandler.js.map