@iushev/react-rbac 1.0.17 → 1.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintignore ADDED
@@ -0,0 +1,2 @@
1
+ lib/
2
+ node_modules/
package/.eslintrc.js ADDED
@@ -0,0 +1,20 @@
1
+ module.exports = {
2
+ env: {
3
+ browser: true,
4
+ es2021: true,
5
+ },
6
+ extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:prettier/recommended"],
7
+ parser: "@typescript-eslint/parser",
8
+ parserOptions: {
9
+ ecmaVersion: 12,
10
+ sourceType: "module",
11
+ },
12
+ plugins: ["@typescript-eslint", "prettier"],
13
+ globals: {
14
+ module: false,
15
+ },
16
+ rules: {
17
+ "@typescript-eslint/no-namespace": "off",
18
+ "@typescript-eslint/no-explicit-any": "off",
19
+ },
20
+ };
package/.prettierrc ADDED
@@ -0,0 +1,3 @@
1
+ {
2
+ "printWidth": 120
3
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "editor.codeActionsOnSave": {
3
+ "source.fixAll.eslint": true
4
+ },
5
+ "editor.formatOnSave": true
6
+ }
package/jest.config.js ADDED
@@ -0,0 +1,188 @@
1
+ // For a detailed explanation regarding each configuration property, visit:
2
+ // https://jestjs.io/docs/en/configuration.html
3
+
4
+ module.exports = {
5
+ // All imported modules in your tests should be mocked automatically
6
+ // automock: false,
7
+
8
+ // Stop running tests after `n` failures
9
+ // bail: 0,
10
+
11
+ // Respect "browser" field in package.json when resolving modules
12
+ // browser: false,
13
+
14
+ // The directory where Jest should store its cached dependency information
15
+ // cacheDirectory: "/tmp/jest_rs",
16
+
17
+ // Automatically clear mock calls and instances between every test
18
+ // clearMocks: false,
19
+
20
+ // Indicates whether the coverage information should be collected while executing the test
21
+ // collectCoverage: false,
22
+
23
+ // An array of glob patterns indicating a set of files for which coverage information should be collected
24
+ // collectCoverageFrom: undefined,
25
+
26
+ // The directory where Jest should output its coverage files
27
+ // coverageDirectory: undefined,
28
+
29
+ // An array of regexp pattern strings used to skip coverage collection
30
+ // coveragePathIgnorePatterns: [
31
+ // "/node_modules/"
32
+ // ],
33
+
34
+ // A list of reporter names that Jest uses when writing coverage reports
35
+ // coverageReporters: [
36
+ // "json",
37
+ // "text",
38
+ // "lcov",
39
+ // "clover"
40
+ // ],
41
+
42
+ // An object that configures minimum threshold enforcement for coverage results
43
+ // coverageThreshold: undefined,
44
+
45
+ // A path to a custom dependency extractor
46
+ // dependencyExtractor: undefined,
47
+
48
+ // Make calling deprecated APIs throw helpful error messages
49
+ // errorOnDeprecated: false,
50
+
51
+ // Force coverage collection from ignored files using an array of glob patterns
52
+ // forceCoverageMatch: [],
53
+
54
+ // A path to a module which exports an async function that is triggered once before all test suites
55
+ // globalSetup: undefined,
56
+
57
+ // A path to a module which exports an async function that is triggered once after all test suites
58
+ // globalTeardown: undefined,
59
+
60
+ // A set of global variables that need to be available in all test environments
61
+ // globals: {},
62
+
63
+ // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
64
+ // maxWorkers: "50%",
65
+
66
+ // An array of directory names to be searched recursively up from the requiring module's location
67
+ // moduleDirectories: [
68
+ // "node_modules"
69
+ // ],
70
+
71
+ // An array of file extensions your modules use
72
+ // moduleFileExtensions: [
73
+ // "js",
74
+ // "json",
75
+ // "jsx",
76
+ // "ts",
77
+ // "tsx",
78
+ // "node"
79
+ // ],
80
+
81
+ // A map from regular expressions to module names that allow to stub out resources with a single module
82
+ // moduleNameMapper: {
83
+ // "^@iushev/rbac$": "<rootDir>/src",
84
+ // },
85
+
86
+ // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
87
+ // modulePathIgnorePatterns: [],
88
+
89
+ // Activates notifications for test results
90
+ // notify: false,
91
+
92
+ // An enum that specifies notification mode. Requires { notify: true }
93
+ // notifyMode: "failure-change",
94
+
95
+ // A preset that is used as a base for Jest's configuration
96
+ preset: "ts-jest",
97
+
98
+ // Run tests from one or more projects
99
+ // projects: undefined,
100
+
101
+ // Use this configuration option to add custom reporters to Jest
102
+ // reporters: undefined,
103
+
104
+ // Automatically reset mock state between every test
105
+ // resetMocks: false,
106
+
107
+ // Reset the module registry before running each individual test
108
+ // resetModules: false,
109
+
110
+ // A path to a custom resolver
111
+ // resolver: undefined,
112
+
113
+ // Automatically restore mock state between every test
114
+ // restoreMocks: false,
115
+
116
+ // The root directory that Jest should scan for tests and modules within
117
+ rootDir: "./src",
118
+
119
+ // A list of paths to directories that Jest should use to search for files in
120
+ // roots: [
121
+ // "./src",
122
+ // "./tests"
123
+ // ],
124
+
125
+ // Allows you to use a custom runner instead of Jest's default test runner
126
+ // runner: "jest-runner",
127
+
128
+ // The paths to modules that run some code to configure or set up the testing environment before each test
129
+ // setupFiles: [],
130
+
131
+ // A list of paths to modules that run some code to configure or set up the testing framework before each test
132
+ // setupFilesAfterEnv: [],
133
+
134
+ // A list of paths to snapshot serializer modules Jest should use for snapshot testing
135
+ // snapshotSerializers: [],
136
+
137
+ // The test environment that will be used for testing
138
+ testEnvironment: "node",
139
+
140
+ // Options that will be passed to the testEnvironment
141
+ // testEnvironmentOptions: {},
142
+
143
+ // Adds a location field to test results
144
+ // testLocationInResults: false,
145
+
146
+ // The glob patterns Jest uses to detect test files
147
+ testMatch: ["**/__tests__/**/?(*.)+(spec|test).[jt]s?(x)"],
148
+
149
+ // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
150
+ // testPathIgnorePatterns: [
151
+ // "/node_modules/"
152
+ // ],
153
+
154
+ // The regexp pattern or array of patterns that Jest uses to detect test files
155
+ // testRegex: [],
156
+
157
+ // This option allows the use of a custom results processor
158
+ // testResultsProcessor: undefined,
159
+
160
+ // This option allows use of a custom test runner
161
+ // testRunner: "jasmine2",
162
+
163
+ // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
164
+ // testURL: "http://localhost",
165
+
166
+ // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
167
+ // timers: "real",
168
+
169
+ // A map from regular expressions to paths to transformers
170
+ // transform: undefined,
171
+
172
+ // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
173
+ // transformIgnorePatterns: [
174
+ // "/node_modules/"
175
+ // ],
176
+
177
+ // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
178
+ // unmockedModulePathPatterns: undefined,
179
+
180
+ // Indicates whether each individual test should be reported during the run
181
+ // verbose: undefined,
182
+
183
+ // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
184
+ // watchPathIgnorePatterns: [],
185
+
186
+ // Whether to use watchman for file crawling
187
+ // watchman: true,
188
+ };
@@ -6,3 +6,4 @@ export declare type CheckAccessProps = CheckAccessOptions & {
6
6
  };
7
7
  declare const CheckAccess: React.FC<CheckAccessProps>;
8
8
  export default CheckAccess;
9
+ //# sourceMappingURL=CheckAccess.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CheckAccess.d.ts","sourceRoot":"","sources":["../src/CheckAccess.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAInD,oBAAY,gBAAgB,GAAG,kBAAkB,GAAG;IAClD,IAAI,CAAC,EAAE,KAAK,CAAC,aAAa,CAAC;IAC3B,QAAQ,CAAC,EAAE,KAAK,CAAC,aAAa,CAAC;CAChC,CAAC;AAEF,QAAA,MAAM,WAAW,EAAE,KAAK,CAAC,EAAE,CAAC,gBAAgB,CAgB3C,CAAC;AAEF,eAAe,WAAW,CAAC"}
File without changes
@@ -1,3 +1,4 @@
1
1
  import React from "react";
2
2
  declare const NoAccess: React.FC;
3
3
  export default NoAccess;
4
+ //# sourceMappingURL=NoAccess.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NoAccess.d.ts","sourceRoot":"","sources":["../src/NoAccess.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,QAAA,MAAM,QAAQ,EAAE,KAAK,CAAC,EAOrB,CAAC;AAEF,eAAe,QAAQ,CAAC"}
File without changes
@@ -14,3 +14,4 @@ export default class RbacCheckAccess extends BaseCheckAccess {
14
14
  private getRbacRules;
15
15
  private getRbacAssignments;
16
16
  }
17
+ //# sourceMappingURL=RbacCheckAccess.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RbacCheckAccess.d.ts","sourceRoot":"","sources":["../src/RbacCheckAccess.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,UAAU,EACV,eAAe,EACf,sBAAsB,EAOtB,UAAU,EACX,MAAM,cAAc,CAAC;AAEtB,oBAAY,sBAAsB,GAAG,sBAAsB,GAAG;IAC5D,IAAI,EAAE,MAAM,CAAC;IACb,aAAa,EAAE,MAAM,MAAM,CAAC;CAC7B,CAAC;AAEF,MAAM,CAAC,OAAO,OAAO,eAAgB,SAAQ,eAAe;IAC1D,OAAO,CAAC,aAAa,CAAgB;IAErC,SAAS,CAAC,WAAW,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,CAAa;gBAE5D,OAAO,EAAE,sBAAsB;IAsB9B,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC;IAQrF,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAwBlC,OAAO,CAAC,YAAY;IAgBpB,OAAO,CAAC,cAAc;IAsBtB,OAAO,CAAC,YAAY;IAUpB,OAAO,CAAC,kBAAkB;CAa3B"}
@@ -65,7 +65,9 @@ class RbacCheckAccess extends rbac_1.BaseCheckAccess {
65
65
  rules: {},
66
66
  };
67
67
  }
68
- throw err;
68
+ else {
69
+ throw err;
70
+ }
69
71
  }
70
72
  this.items = this.getRbacItems(_rbac);
71
73
  this.parents = this.getRbacParents(_rbac);
@@ -80,7 +82,6 @@ class RbacCheckAccess extends rbac_1.BaseCheckAccess {
80
82
  const ItemClass = item.type === rbac_1.ItemType.permission ? rbac_1.Permission : rbac_1.Role;
81
83
  prevValue.set(name, new ItemClass({
82
84
  name,
83
- type: item.type,
84
85
  description: (_a = item.description) !== null && _a !== void 0 ? _a : null,
85
86
  ruleName: (_b = item.ruleName) !== null && _b !== void 0 ? _b : null,
86
87
  }));
@@ -121,21 +122,10 @@ class RbacCheckAccess extends rbac_1.BaseCheckAccess {
121
122
  _assignments.forEach((itemName) => {
122
123
  var _a;
123
124
  if (prevValue.has(username)) {
124
- (_a = prevValue.get(username)) === null || _a === void 0 ? void 0 : _a.set(itemName, new rbac_1.Assignment({
125
- itemName,
126
- username,
127
- }));
125
+ (_a = prevValue.get(username)) === null || _a === void 0 ? void 0 : _a.set(itemName, new rbac_1.Assignment(username, itemName));
128
126
  }
129
127
  else {
130
- prevValue.set(username, new Map([
131
- [
132
- itemName,
133
- new rbac_1.Assignment({
134
- itemName,
135
- username,
136
- }),
137
- ],
138
- ]));
128
+ prevValue.set(username, new Map([[itemName, new rbac_1.Assignment(username, itemName)]]));
139
129
  }
140
130
  });
141
131
  return prevValue;
@@ -22,4 +22,6 @@ export declare type RbacProviderProps = {
22
22
  };
23
23
  export declare const RbacProvider: React.FC<RbacProviderProps>;
24
24
  export declare const RbacConsumer: React.Consumer<RbacContextProps>;
25
+ export declare const useRbac: () => RbacContextProps;
25
26
  export default RbacContext;
27
+ //# sourceMappingURL=RbacContext.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RbacContext.d.ts","sourceRoot":"","sources":["../src/RbacContext.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAgE,MAAM,OAAO,CAAC;AAErF,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAG1D,oBAAY,kBAAkB,GAAG,MAAM,UAAU,CAAC;AAClD,oBAAY,aAAa,GAAG,MAAM,OAAO,CAAC;AAC1C,oBAAY,kBAAkB,GAAG;IAC/B,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,MAAM,CAAC,EAAE,UAAU,GAAG,kBAAkB,CAAC;IACzC,KAAK,CAAC,EAAE,aAAa,CAAC;CACvB,CAAC;AAEF,oBAAY,gBAAgB,GAAG;IAC7B,WAAW,EAAE,CAAC,OAAO,EAAE,kBAAkB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;CAChE,CAAC;AAEF,QAAA,MAAM,WAAW,iCAEf,CAAC;AAEH,oBAAY,iBAAiB,GAAG;IAC9B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,OAAO,CAAC;IACrB,OAAO,EAAE,OAAO,CAAC;IACjB,WAAW,EAAE,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;CAC1C,CAAC;AAEF,eAAO,MAAM,YAAY,EAAE,KAAK,CAAC,EAAE,CAAC,iBAAiB,CAkEpD,CAAC;AAEF,eAAO,MAAM,YAAY,kCAAuB,CAAC;AAEjD,eAAO,MAAM,OAAO,QAAO,gBAM1B,CAAC;AAEF,eAAe,WAAW,CAAC"}
@@ -35,7 +35,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
35
35
  return (mod && mod.__esModule) ? mod : { "default": mod };
36
36
  };
37
37
  Object.defineProperty(exports, "__esModule", { value: true });
38
- exports.RbacConsumer = exports.RbacProvider = void 0;
38
+ exports.useRbac = exports.RbacConsumer = exports.RbacProvider = void 0;
39
39
  const jsx_runtime_1 = require("react/jsx-runtime");
40
40
  const react_1 = __importStar(require("react"));
41
41
  const RbacCheckAccess_1 = __importDefault(require("./RbacCheckAccess"));
@@ -58,46 +58,39 @@ const RbacProvider = ({ username, rbacUrl, token, isSuperuser, isGuest, ruleClas
58
58
  _rbac.load().then(() => setRbac(_rbac));
59
59
  }
60
60
  }, [rbacUrl, token]);
61
- const value = (0, react_1.useMemo)(() => {
62
- const checkAccess = ({ roles, allow = true, match, params = {} }) => __awaiter(void 0, void 0, void 0, function* () {
63
- const matchRole = () => __awaiter(void 0, void 0, void 0, function* () {
64
- if (!roles || roles.length === 0) {
65
- return true;
66
- }
67
- let _params = params;
68
- if (typeof params === "function") {
69
- _params = params();
70
- }
71
- for (const role of roles) {
72
- if (role === "?") {
73
- if (isGuest) {
74
- return true;
75
- }
76
- }
77
- else if (role === "@") {
78
- if (!isGuest) {
79
- return true;
80
- }
81
- }
82
- else {
83
- if (yield (rbac === null || rbac === void 0 ? void 0 : rbac.checkAccess(username, role, _params))) {
84
- return true;
85
- }
86
- }
87
- }
88
- return false;
89
- });
90
- const matchCustom = () => {
91
- if (!match) {
92
- return true;
93
- }
94
- return match();
95
- };
96
- if (isSuperuser || ((yield matchRole()) && matchCustom() && allow)) {
61
+ const matchRole = (0, react_1.useCallback)((roles, params) => __awaiter(void 0, void 0, void 0, function* () {
62
+ if (!roles || roles.length === 0) {
63
+ return true;
64
+ }
65
+ for (const role of roles) {
66
+ if (role === "?" && isGuest) {
67
+ // only guest users
68
+ return true;
69
+ }
70
+ else if (role === "@" && !isGuest) {
71
+ // only authenticated users
72
+ return true;
73
+ }
74
+ else if (yield (rbac === null || rbac === void 0 ? void 0 : rbac.checkAccess(username, role, typeof params === "function" ? params() : params))) {
75
+ // only authenticated users that has permission
97
76
  return true;
98
77
  }
99
- return false;
100
- });
78
+ else {
79
+ continue;
80
+ }
81
+ }
82
+ return false;
83
+ }), []);
84
+ const matchCustom = (0, react_1.useCallback)((match) => {
85
+ if (!match) {
86
+ return true;
87
+ }
88
+ return match();
89
+ }, []);
90
+ const checkAccess = (0, react_1.useCallback)(({ roles, allow = true, match, params = {} }) => __awaiter(void 0, void 0, void 0, function* () {
91
+ return isSuperuser || ((yield matchRole(roles, params)) && matchCustom(match) && allow);
92
+ }), []);
93
+ const value = (0, react_1.useMemo)(() => {
101
94
  return {
102
95
  checkAccess,
103
96
  };
@@ -106,4 +99,12 @@ const RbacProvider = ({ username, rbacUrl, token, isSuperuser, isGuest, ruleClas
106
99
  };
107
100
  exports.RbacProvider = RbacProvider;
108
101
  exports.RbacConsumer = RbacContext.Consumer;
102
+ const useRbac = () => {
103
+ const ctx = (0, react_1.useContext)(RbacContext);
104
+ if (!ctx) {
105
+ throw new Error("useRbac must be rendered under RbacProvider");
106
+ }
107
+ return ctx;
108
+ };
109
+ exports.useRbac = useRbac;
109
110
  exports.default = RbacContext;
@@ -2,3 +2,4 @@ export { default as RbacContext, RbacConsumer, RbacProvider } from "./RbacContex
2
2
  export { default as CheckAccess, CheckAccessProps } from "./CheckAccess";
3
3
  export { default as NoAccess } from "./NoAccess";
4
4
  export { default as useCheckAccess } from "./useCheckAccess";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AACnF,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACzE,OAAO,EAAE,OAAO,IAAI,QAAQ,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,kBAAkB,CAAC"}
File without changes
@@ -5,3 +5,4 @@ export declare type CheckAssessState = {
5
5
  };
6
6
  declare function useCheckAccess({ roles, allow, params, match }: CheckAccessOptions): CheckAssessState;
7
7
  export default useCheckAccess;
8
+ //# sourceMappingURL=useCheckAccess.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useCheckAccess.d.ts","sourceRoot":"","sources":["../src/useCheckAccess.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAW,MAAM,eAAe,CAAC;AAE5D,oBAAY,gBAAgB,GAAG;IAC7B,QAAQ,EAAE,OAAO,CAAC;IAClB,SAAS,EAAE,OAAO,CAAC;CACpB,CAAC;AAEF,iBAAS,cAAc,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,kBAAkB,oBAyC1E;AAED,eAAe,cAAc,CAAC"}
@@ -1,12 +1,9 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  const react_1 = require("react");
7
- const RbacContext_1 = __importDefault(require("./RbacContext"));
4
+ const RbacContext_1 = require("./RbacContext");
8
5
  function useCheckAccess({ roles, allow, params, match }) {
9
- const rbac = (0, react_1.useContext)(RbacContext_1.default);
6
+ const rbac = (0, RbacContext_1.useRbac)();
10
7
  const [state, setState] = (0, react_1.useState)({
11
8
  checking: true,
12
9
  hasAccess: false,
package/package.json CHANGED
@@ -1,31 +1,44 @@
1
1
  {
2
2
  "name": "@iushev/react-rbac",
3
- "version": "1.0.17",
3
+ "version": "1.0.20",
4
4
  "private": false,
5
5
  "author": "Ivaylo Ushev",
6
6
  "description": "",
7
7
  "license": "ISC",
8
8
  "main": "./build",
9
9
  "scripts": {
10
- "build": "tsc -p ./src",
11
- "watch": "tsc -w -p ./src",
12
- "test": "jest"
10
+ "build": "tsc",
11
+ "watch": "tsc -w --preserveWatchOutput",
12
+ "test": "jest --runInBand",
13
+ "test:watch": "jest ----watchAll --runInBand",
14
+ "coverage": "jest --coverage --runInBand",
15
+ "lint": "eslint --ext .js,.jsx,.ts,.tsx src",
16
+ "preversion": "rimraf ./lib && npm run build"
13
17
  },
14
- "devDependencies": {
15
- "typescript": "^4.6.2"
18
+ "dependencies": {
19
+ "http-status-codes": "^2.2.0"
16
20
  },
17
- "peerDependencies": {
18
- "@iushev/rbac": "^1.0.22",
21
+ "devDependencies": {
19
22
  "@types/react": "^16.14.5 || ^17.0.40",
20
23
  "@types/react-dom": "^17.0.13",
21
- "axios": ">= 0.26.1",
24
+ "@typescript-eslint/eslint-plugin": "^5.21.0",
25
+ "@typescript-eslint/parser": "^5.21.0",
26
+ "eslint": "^8.14.0",
27
+ "eslint-config-prettier": "^8.5.0",
28
+ "eslint-plugin-prettier": "^4.0.0",
29
+ "jest": "^27.5.1",
30
+ "prettier": "^2.6.2",
31
+ "rimraf": "^3.0.2",
32
+ "ts-jest": "^27.1.4",
33
+ "typescript": "^4.6.3"
34
+ },
35
+ "peerDependencies": {
36
+ "@iushev/rbac": "^1.0.31",
37
+ "axios": "0.27.2",
22
38
  "react": "^16.14.0 || ^17.0.2",
23
39
  "react-dom": "^16.14.0 || ^17.0.2"
24
40
  },
25
41
  "publishConfig": {
26
42
  "access": "public"
27
- },
28
- "dependencies": {
29
- "http-status-codes": "^2.2.0"
30
43
  }
31
44
  }
@@ -5,7 +5,7 @@ import {
5
5
  Assignment,
6
6
  BaseCheckAccess,
7
7
  BaseCheckAccessOptions,
8
- Item,
8
+ IItem,
9
9
  ItemType,
10
10
  Permission,
11
11
  RBACResponse,
@@ -67,8 +67,9 @@ export default class RbacCheckAccess extends BaseCheckAccess {
67
67
  items: {},
68
68
  rules: {},
69
69
  };
70
+ } else {
71
+ throw err;
70
72
  }
71
- throw err;
72
73
  }
73
74
 
74
75
  this.items = this.getRbacItems(_rbac);
@@ -78,14 +79,13 @@ export default class RbacCheckAccess extends BaseCheckAccess {
78
79
  }
79
80
 
80
81
  private getRbacItems({ items }: RBACResponse) {
81
- return Object.keys(items).reduce<Map<string, Item>>((prevValue, name) => {
82
+ return Object.keys(items).reduce<Map<string, IItem>>((prevValue, name) => {
82
83
  const item = items[name];
83
84
  const ItemClass = item.type === ItemType.permission ? Permission : Role;
84
85
  prevValue.set(
85
86
  name,
86
87
  new ItemClass({
87
88
  name,
88
- type: item.type,
89
89
  description: item.description ?? null,
90
90
  ruleName: item.ruleName ?? null,
91
91
  })
@@ -95,7 +95,7 @@ export default class RbacCheckAccess extends BaseCheckAccess {
95
95
  }
96
96
 
97
97
  private getRbacParents({ items }: RBACResponse) {
98
- return Object.keys(items).reduce<Map<string, Map<string, Item>>>((prevValue, name) => {
98
+ return Object.keys(items).reduce<Map<string, Map<string, IItem>>>((prevValue, name) => {
99
99
  const item = items[name];
100
100
  if (!item.children || item.children.length === 0) {
101
101
  return prevValue;
@@ -131,26 +131,9 @@ export default class RbacCheckAccess extends BaseCheckAccess {
131
131
  const _assignments = assignments[username];
132
132
  _assignments.forEach((itemName) => {
133
133
  if (prevValue.has(username)) {
134
- prevValue.get(username)?.set(
135
- itemName,
136
- new Assignment({
137
- itemName,
138
- username,
139
- })
140
- );
134
+ prevValue.get(username)?.set(itemName, new Assignment(username, itemName));
141
135
  } else {
142
- prevValue.set(
143
- username,
144
- new Map([
145
- [
146
- itemName,
147
- new Assignment({
148
- itemName,
149
- username,
150
- }),
151
- ],
152
- ])
153
- );
136
+ prevValue.set(username, new Map([[itemName, new Assignment(username, itemName)]]));
154
137
  }
155
138
  });
156
139
  return prevValue;
@@ -1,4 +1,4 @@
1
- import React, { useEffect, useMemo, useState } from "react";
1
+ import React, { useCallback, useContext, useEffect, useMemo, useState } from "react";
2
2
 
3
3
  import { RuleParams, Rule, RuleCtor } from "@iushev/rbac";
4
4
  import RbacCheckAccess from "./RbacCheckAccess";
@@ -54,51 +54,41 @@ export const RbacProvider: React.FC<RbacProviderProps> = ({
54
54
  }
55
55
  }, [rbacUrl, token]);
56
56
 
57
- const value = useMemo(() => {
58
- const checkAccess = async ({ roles, allow = true, match, params = {} }: CheckAccessOptions) => {
59
- const matchRole = async () => {
60
- if (!roles || roles.length === 0) {
61
- return true;
62
- }
63
-
64
- let _params = params;
65
- if (typeof params === "function") {
66
- _params = params();
67
- }
68
-
69
- for (const role of roles) {
70
- if (role === "?") {
71
- if (isGuest) {
72
- return true;
73
- }
74
- } else if (role === "@") {
75
- if (!isGuest) {
76
- return true;
77
- }
78
- } else {
79
- if (await rbac?.checkAccess(username, role, _params)) {
80
- return true;
81
- }
82
- }
83
- }
84
-
85
- return false;
86
- };
87
-
88
- const matchCustom = () => {
89
- if (!match) {
90
- return true;
91
- }
92
- return match();
93
- };
94
-
95
- if (isSuperuser || ((await matchRole()) && matchCustom() && allow)) {
57
+ const matchRole = useCallback(async (roles, params) => {
58
+ if (!roles || roles.length === 0) {
59
+ return true;
60
+ }
61
+
62
+ for (const role of roles) {
63
+ if (role === "?" && isGuest) {
64
+ // only guest users
65
+ return true;
66
+ } else if (role === "@" && !isGuest) {
67
+ // only authenticated users
96
68
  return true;
69
+ } else if (await rbac?.checkAccess(username, role, typeof params === "function" ? params() : params)) {
70
+ // only authenticated users that has permission
71
+ return true;
72
+ } else {
73
+ continue;
97
74
  }
75
+ }
98
76
 
99
- return false;
100
- };
77
+ return false;
78
+ }, []);
101
79
 
80
+ const matchCustom = useCallback((match) => {
81
+ if (!match) {
82
+ return true;
83
+ }
84
+ return match();
85
+ }, []);
86
+
87
+ const checkAccess = useCallback(async ({ roles, allow = true, match, params = {} }: CheckAccessOptions) => {
88
+ return isSuperuser || ((await matchRole(roles, params)) && matchCustom(match) && allow);
89
+ }, []);
90
+
91
+ const value = useMemo(() => {
102
92
  return {
103
93
  checkAccess,
104
94
  };
@@ -108,4 +98,13 @@ export const RbacProvider: React.FC<RbacProviderProps> = ({
108
98
  };
109
99
 
110
100
  export const RbacConsumer = RbacContext.Consumer;
101
+
102
+ export const useRbac = (): RbacContextProps => {
103
+ const ctx = useContext(RbacContext);
104
+ if (!ctx) {
105
+ throw new Error("useRbac must be rendered under RbacProvider");
106
+ }
107
+ return ctx;
108
+ };
109
+
111
110
  export default RbacContext;
File without changes
@@ -1,5 +1,5 @@
1
- import { useContext, useEffect, useRef, useState } from "react";
2
- import RbacContext, { CheckAccessOptions } from "./RbacContext";
1
+ import { useEffect, useState } from "react";
2
+ import { CheckAccessOptions, useRbac } from "./RbacContext";
3
3
 
4
4
  export type CheckAssessState = {
5
5
  checking: boolean;
@@ -7,7 +7,7 @@ export type CheckAssessState = {
7
7
  };
8
8
 
9
9
  function useCheckAccess({ roles, allow, params, match }: CheckAccessOptions) {
10
- const rbac = useContext(RbacContext);
10
+ const rbac = useRbac();
11
11
 
12
12
  const [state, setState] = useState<CheckAssessState>({
13
13
  checking: true,
package/tsconfig.json CHANGED
@@ -2,71 +2,102 @@
2
2
  "compilerOptions": {
3
3
  /* Visit https://aka.ms/tsconfig.json to read more about this file */
4
4
 
5
- /* Basic Options */
6
- // "incremental": true, /* Enable incremental compilation */
7
- "target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
8
- "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
9
- // "lib": [], /* Specify library files to be included in the compilation. */
10
- // "allowJs": true, /* Allow javascript files to be compiled. */
11
- // "checkJs": true, /* Report errors in .js files. */
12
- "jsx": "react-jsx", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
13
- "declaration": true, /* Generates corresponding '.d.ts' file. */
14
- // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
15
- // "sourceMap": true, /* Generates corresponding '.map' file. */
16
- // "outFile": "./", /* Concatenate and emit output to single file. */
17
- "outDir": "./build" /* Redirect output structure to the directory. */,
18
- // "rootDir": "./src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
19
- // "composite": true, /* Enable project compilation */
20
- // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
21
- // "removeComments": true, /* Do not emit comments to output. */
22
- // "noEmit": true, /* Do not emit outputs. */
23
- // "importHelpers": true, /* Import emit helpers from 'tslib'. */
24
- // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
25
- // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
5
+ /* Projects */
6
+ // "incremental": true, /* Enable incremental compilation */
7
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
+ // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
9
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
10
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
26
12
 
27
- /* Strict Type-Checking Options */
28
- "strict": true /* Enable all strict type-checking options. */,
29
- // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
30
- // "strictNullChecks": true, /* Enable strict null checks. */
31
- // "strictFunctionTypes": true, /* Enable strict checking of function types. */
32
- // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
33
- // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
34
- // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
35
- // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
13
+ /* Language and Environment */
14
+ "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
15
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
+ "jsx": "react-jsx" /* Specify what JSX code is generated. */,
17
+ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
20
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
22
+ // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
23
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
36
25
 
37
- /* Additional Checks */
38
- // "noUnusedLocals": true, /* Report errors on unused locals. */
39
- // "noUnusedParameters": true, /* Report errors on unused parameters. */
40
- // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
41
- // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
42
- // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
43
- // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
26
+ /* Modules */
27
+ "module": "commonjs" /* Specify what module code is generated. */,
28
+ // "rootDir": "./", /* Specify the root folder within your source files. */
29
+ // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
30
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
31
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
32
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
33
+ // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
34
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
35
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
36
+ // "resolveJsonModule": true, /* Enable importing .json files */
37
+ // "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
44
38
 
45
- /* Module Resolution Options */
46
- "moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
47
- "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
48
- // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
49
- // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
50
- // "typeRoots": [], /* List of folders to include type definitions from. */
51
- // "types": [], /* Type declaration files to be included in compilation. */
52
- // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
53
- "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
54
- // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
55
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
39
+ /* JavaScript Support */
40
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
41
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
42
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
56
43
 
57
- /* Source Map Options */
58
- // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
59
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
60
- // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
61
- // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
44
+ /* Emit */
45
+ "declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
46
+ "declarationMap": true /* Create sourcemaps for d.ts files. */,
47
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
48
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
49
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
50
+ "outDir": "./lib" /* Specify an output folder for all emitted files. */,
51
+ // "removeComments": true, /* Disable emitting comments. */
52
+ // "noEmit": true, /* Disable emitting files from a compilation. */
53
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
54
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
55
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
56
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
57
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
58
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
59
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
60
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
61
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
62
+ // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
63
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
64
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
65
+ // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
66
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
67
+ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
62
68
 
63
- /* Experimental Options */
64
- // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
65
- // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
69
+ /* Interop Constraints */
70
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
71
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
72
+ "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
73
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
74
+ "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
66
75
 
67
- /* Advanced Options */
68
- "skipLibCheck": true /* Skip type checking of declaration files. */,
69
- "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
76
+ /* Type Checking */
77
+ "strict": true /* Enable all strict type-checking options. */,
78
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
79
+ // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
80
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
81
+ // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
82
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
83
+ // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
84
+ // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
85
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
86
+ // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
87
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
88
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
89
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
90
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
91
+ // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
92
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
93
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
94
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
95
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
96
+
97
+ /* Completeness */
98
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
99
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
70
100
  },
71
- "exclude": ["build", "node_modules"],
101
+ "include": ["src"],
102
+ "exclude": ["lib", "node_modules", "src/__tests__"]
72
103
  }
package/src/tsconfig.json DELETED
@@ -1,3 +0,0 @@
1
- {
2
- "extends": "../tsconfig.json",
3
- }