control.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. 'use strict'
  2. const { BerWriter } = require('@ldapjs/asn1')
  3. /**
  4. * Baseline LDAP control object. Implements
  5. * https://tools.ietf.org/html/rfc4511#section-4.1.11
  6. *
  7. * @class
  8. */
  9. class Control {
  10. /**
  11. * @typedef {object} ControlParams
  12. * @property {string} [type=''] The dotted decimal control type value.
  13. * @property {boolean} [criticality=false] Criticality value for the control.
  14. * @property {string|Buffer} [value] The value for the control. If this is
  15. * a `string` then it will be written as-is. If it is an instance of `Buffer`
  16. * then it will be written by `value.toString()` when generating a BER
  17. * instance.
  18. */
  19. /**
  20. * Create a new baseline LDAP control.
  21. *
  22. * @param {ControlParams} [options]
  23. */
  24. constructor (options = {}) {
  25. const opts = Object.assign({ type: '', criticality: false, value: null }, options)
  26. this.type = opts.type
  27. this.criticality = opts.criticality
  28. this.value = opts.value
  29. }
  30. get [Symbol.toStringTag] () {
  31. return 'LdapControl'
  32. }
  33. /**
  34. * Serializes the control into a plain JavaScript object that can be passed
  35. * to the constructor as an options object. If an instance has a `_pojo(obj)`
  36. * method then the built object will be sent to that method and the resulting
  37. * mutated object returned.
  38. *
  39. * @returns {object} A plain JavaScript object that represents an LDAP control.
  40. */
  41. get pojo () {
  42. const obj = {
  43. type: this.type,
  44. value: this.value,
  45. criticality: this.criticality
  46. }
  47. if (typeof this._pojo === 'function') {
  48. this._pojo(obj)
  49. }
  50. return obj
  51. }
  52. /**
  53. * Converts the instance into a [BER](http://luca.ntop.org/Teaching/Appunti/asn1.html)
  54. * representation.
  55. *
  56. * @param {BerWriter} [ber] An empty `BerWriter` instance to populate.
  57. *
  58. * @returns {object} A BER object.
  59. */
  60. toBer (ber = new BerWriter()) {
  61. ber.startSequence()
  62. ber.writeString(this.type || '')
  63. ber.writeBoolean(this.criticality)
  64. /* istanbul ignore else */
  65. if (typeof (this._toBer) === 'function') {
  66. this._toBer(ber)
  67. } else if (this.value !== undefined) {
  68. if (typeof this.value === 'string') {
  69. ber.writeString(this.value)
  70. } else if (Buffer.isBuffer(this.value)) {
  71. ber.writeString(this.value.toString())
  72. }
  73. }
  74. ber.endSequence()
  75. return ber
  76. }
  77. }
  78. module.exports = Control