Home Reference Source

src/generator/authorize/getRoles.js

  1. // @flow
  2.  
  3. import { CODE_MODES, USER_ROLE, DOC_ROLE } from '../../constants';
  4. import { extractRoles } from './extractRoles';
  5.  
  6. /**
  7. * get userRoles and docRoles
  8. * @private
  9. * @param {boolean} authorize - flag for authorization logic
  10. * @param {object} inputSchema - type's schema
  11. * @return {Object}
  12. * @property {object} userRoles - userRoles object with modes
  13. * @property {object} docRoles - docRoles object with modes
  14. * @property {string} roleFieldName - field containing the roles
  15. * }
  16. */
  17.  
  18. export function getRoles(authorize: boolean, inputSchema: any) {
  19. // create empty userRoles and docRoles objects
  20. // as default values, which are used
  21. // if there is no @authorize directive
  22. const userRoles = {};
  23. const docRoles = {};
  24. const roleFieldNamesFound = [];
  25.  
  26. // initialize
  27. CODE_MODES.forEach(mode => (userRoles[mode] = []));
  28. CODE_MODES.forEach(mode => (docRoles[mode] = []));
  29.  
  30. // check if there is an @authorize directive
  31. if (authorize) {
  32. // then re-determine the userRoles and docRoles
  33. // from the @authorize tag of the type definition
  34. const allRolesArguments =
  35. inputSchema.definitions[0].directives[0].arguments || {};
  36.  
  37. const allRoles = extractRoles(allRolesArguments, inputSchema);
  38.  
  39. allRoles.forEach(role => {
  40. switch (role.type) {
  41. case USER_ROLE:
  42. // check, if there is already another userRole field
  43. if (
  44. roleFieldNamesFound.length > 0 &&
  45. role.roleFieldName !== '' &&
  46. roleFieldNamesFound.indexOf(role.roleFieldName) < 0
  47. ) {
  48. // We allow only one field, which stores all userRoles
  49. throw new Error(`Please adjust type definition, that there is
  50. only ONE field, which keeps all user roles. You've tried to
  51. add a second userRole field: '${role.roleFieldName}',
  52. but there is already another userRole field:
  53. '${roleFieldNamesFound[0]}' defined.
  54. Please try instead: '${roleFieldNamesFound[0]}:
  55. String @authRole(for: ["otherRole", "${role.roleName}"])'`);
  56. }
  57. if (role.roleFieldName !== '') {
  58. roleFieldNamesFound.push(role.roleFieldName);
  59. }
  60.  
  61. Object.keys(role.modes).forEach(mode => {
  62. if (role.modes[mode]) {
  63. userRoles[mode].push(role.roleName);
  64. }
  65. });
  66. break;
  67.  
  68. case DOC_ROLE:
  69. Object.keys(role.modes).forEach(mode => {
  70. if (role.modes[mode]) {
  71. docRoles[mode].push(role.roleName);
  72. }
  73. });
  74. break;
  75. }
  76. });
  77. }
  78.  
  79. return {
  80. userRoles,
  81. docRoles,
  82. roleFieldName: roleFieldNamesFound.length > 0 ? roleFieldNamesFound[0] : ''
  83. };
  84. }