url.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict'
  2. const querystring = require('querystring')
  3. const url = require('url')
  4. const { DN } = require('@ldapjs/dn')
  5. const filter = require('@ldapjs/filter')
  6. module.exports = {
  7. parse: function (urlStr, parseDN) {
  8. let parsedURL
  9. try {
  10. parsedURL = new url.URL(urlStr)
  11. } catch (error) {
  12. throw new TypeError(urlStr + ' is an invalid LDAP url (scope)')
  13. }
  14. if (!parsedURL.protocol || !(parsedURL.protocol === 'ldap:' || parsedURL.protocol === 'ldaps:')) { throw new TypeError(urlStr + ' is an invalid LDAP url (protocol)') }
  15. const u = {
  16. protocol: parsedURL.protocol,
  17. hostname: parsedURL.hostname,
  18. port: parsedURL.port,
  19. pathname: parsedURL.pathname,
  20. search: parsedURL.search,
  21. href: parsedURL.href
  22. }
  23. u.secure = (u.protocol === 'ldaps:')
  24. if (!u.hostname) { u.hostname = 'localhost' }
  25. if (!u.port) {
  26. u.port = (u.secure ? 636 : 389)
  27. } else {
  28. u.port = parseInt(u.port, 10)
  29. }
  30. if (u.pathname) {
  31. u.pathname = querystring.unescape(u.pathname.substr(1))
  32. u.DN = parseDN ? DN.fromString(u.pathname) : u.pathname
  33. }
  34. if (u.search) {
  35. u.attributes = []
  36. const tmp = u.search.substr(1).split('?')
  37. if (tmp && tmp.length) {
  38. if (tmp[0]) {
  39. tmp[0].split(',').forEach(function (a) {
  40. u.attributes.push(querystring.unescape(a.trim()))
  41. })
  42. }
  43. }
  44. if (tmp[1]) {
  45. if (tmp[1] !== 'base' && tmp[1] !== 'one' && tmp[1] !== 'sub') { throw new TypeError(urlStr + ' is an invalid LDAP url (scope)') }
  46. u.scope = tmp[1]
  47. }
  48. if (tmp[2]) {
  49. u.filter = querystring.unescape(tmp[2])
  50. }
  51. if (tmp[3]) {
  52. u.extensions = querystring.unescape(tmp[3])
  53. }
  54. if (!u.scope) { u.scope = 'base' }
  55. if (!u.filter) { u.filter = filter.parseString('(objectclass=*)') } else { u.filter = filter.parseString(u.filter) }
  56. }
  57. return u
  58. }
  59. }