Home Reference Source

src/lib/fieldContainsUserId.js

  1. // @flow
  2. /* eslint-disable max-len */
  3.  
  4. import _ from 'lodash';
  5.  
  6. /**
  7. * extracts a UserId from an _id object
  8. * @private
  9. * @param {object} userIdObject - user object
  10. * @return {string} newUserId - id of the user
  11. */
  12.  
  13. function extractUserId(userIdObject: any): any {
  14. let newUserId = '';
  15. if (_.isObject(userIdObject)) {
  16. Object.keys(userIdObject).forEach(field => {
  17. newUserId = userIdObject[field];
  18. });
  19. } else {
  20. newUserId = userIdObject;
  21. }
  22. return newUserId;
  23. }
  24.  
  25. /**
  26. * checks, if a field contains a user's id
  27. * returns true, if a field of type array/object/string contains the userId
  28. * @public
  29. * @param {object} docRoleField - the field to be checked
  30. * @param {object} compressedUserId - the user id to test
  31. * @return {boolean} found - true if it contains the user id
  32. */
  33.  
  34. export function fieldContainsUserId(
  35. docRoleField: any,
  36. compressedUserId: any
  37. ): boolean {
  38. let found = false;
  39.  
  40. // empty docRoleField is not a valid docRoleField
  41. if (!docRoleField || docRoleField === '' || docRoleField.length === 0) {
  42. return false;
  43. }
  44.  
  45. // empty (compressed) userId is not a valid userId
  46. if (
  47. !compressedUserId ||
  48. compressedUserId === '' ||
  49. compressedUserId.toString() === ''
  50. ) {
  51. return false;
  52. }
  53.  
  54. // extract userId, if it is a mongoID field
  55. const userId = extractUserId(compressedUserId);
  56.  
  57. // empty (uncompressed) userId is not a valid userId
  58. if (!userId || userId === '') {
  59. return false;
  60. }
  61.  
  62. // docRoleField of type Array
  63. if (_.isArray(docRoleField)) {
  64. docRoleField.forEach(field => {
  65. if (fieldContainsUserId(field, userId)) {
  66. found = true;
  67. }
  68. });
  69. if (found) {
  70. return true;
  71. }
  72. return false;
  73. }
  74.  
  75. // docRoleField of type Object
  76. if (_.isObject(docRoleField)) {
  77. // For each field in the object
  78. Object.keys(docRoleField).forEach(field => {
  79. if (
  80. fieldContainsUserId(docRoleField[field], userId) ||
  81. fieldContainsUserId(field, userId)
  82. ) {
  83. found = true;
  84. }
  85. });
  86. if (found) {
  87. return true;
  88. }
  89. return false;
  90. }
  91.  
  92. // docRoleField of type field
  93. if (docRoleField.toString() === userId.toString()) {
  94. return true;
  95. }
  96.  
  97. return false;
  98. }