ldapAuthenticationHandler.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. try {
  31. await client.bind(bindDn, password);
  32. if (this.configuration.totpField) {
  33. const data = await client.search(bindDn);
  34. totp = this.fieldToString(data.searchEntries[0]?.[this.configuration.totpField]);
  35. finalUsername = this.fieldToString(data.searchEntries[0]?.[this.configuration.usernameField]);
  36. }
  37. }
  38. catch (ex) {
  39. console.error(ex);
  40. return null;
  41. }
  42. finally {
  43. client.unbind();
  44. }
  45. return {
  46. username: finalUsername,
  47. totp: totp
  48. };
  49. }
  50. async tryLogin(username, password, totp) {
  51. const account = await this.tryBind(username, password);
  52. if (!account)
  53. return null;
  54. return TotpChecker.ValidateTotp(account.totp, totp);
  55. }
  56. async needTotp(username, password) {
  57. const account = await this.tryBind(username, password);
  58. if (!account)
  59. return null;
  60. return !!account.totp;
  61. }
  62. }
  63. //# sourceMappingURL=ldapAuthenticationHandler.js.map