@iushev/rbac-web-manager 1.0.0

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/.prettierrc ADDED
@@ -0,0 +1,3 @@
1
+ {
2
+ "printWidth": 120
3
+ }
@@ -0,0 +1,57 @@
1
+ import typescriptEslint from "@typescript-eslint/eslint-plugin";
2
+ import prettier from "eslint-plugin-prettier";
3
+ import globals from "globals";
4
+ import tsParser from "@typescript-eslint/parser";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import js from "@eslint/js";
8
+ import { FlatCompat } from "@eslint/eslintrc";
9
+
10
+ const __filename = fileURLToPath(import.meta.url);
11
+ const __dirname = path.dirname(__filename);
12
+ const compat = new FlatCompat({
13
+ baseDirectory: __dirname,
14
+ recommendedConfig: js.configs.recommended,
15
+ allConfig: js.configs.all,
16
+ });
17
+
18
+ export default [
19
+ {
20
+ ignores: ["**/docs/", "**/lib/", "**/node_modules/"],
21
+ },
22
+ ...compat.extends("eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:prettier/recommended"),
23
+ {
24
+ plugins: {
25
+ "@typescript-eslint": typescriptEslint,
26
+ prettier,
27
+ },
28
+
29
+ languageOptions: {
30
+ globals: {
31
+ ...globals.browser,
32
+ module: false,
33
+ },
34
+
35
+ parser: tsParser,
36
+ ecmaVersion: 12,
37
+ sourceType: "module",
38
+ },
39
+
40
+ rules: {
41
+ "@typescript-eslint/no-namespace": "off",
42
+ "@typescript-eslint/no-explicit-any": "off",
43
+ "@typescript-eslint/no-unused-vars": [
44
+ "error",
45
+ {
46
+ args: "all",
47
+ argsIgnorePattern: "^_",
48
+ caughtErrors: "all",
49
+ caughtErrorsIgnorePattern: "^_",
50
+ destructuredArrayIgnorePattern: "^_",
51
+ varsIgnorePattern: "^_",
52
+ ignoreRestSiblings: true,
53
+ },
54
+ ],
55
+ },
56
+ },
57
+ ];
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
+ };
@@ -0,0 +1,48 @@
1
+ import { AxiosRequestConfig } from "axios";
2
+ import { Assignment, BaseManager, BaseManagerOptions, IItem, ItemType, Permission, Role, Rule } from "@iushev/rbac";
3
+ export type WebManagerOptions = BaseManagerOptions & {
4
+ path: string;
5
+ authorization: () => string;
6
+ };
7
+ export default class WebManager extends BaseManager {
8
+ private readonly axiosInstance;
9
+ protected assignments: Map<string, Map<string, Assignment>>;
10
+ constructor(options: WebManagerOptions);
11
+ load(config?: AxiosRequestConfig): Promise<void>;
12
+ private getRbacItems;
13
+ private getRbacParents;
14
+ private getRbacRules;
15
+ private getRbacAssignments;
16
+ getRolesByUser(_username: string): Promise<Map<string, Role>>;
17
+ getChildRoles(_roleName: string): Promise<Map<string, Role>>;
18
+ getPermissionsByRole(_roleName: string): Promise<Map<string, Permission>>;
19
+ getPermissionsByUser(_username: string): Promise<Map<string, Permission>>;
20
+ getRule(_name: string): Promise<Rule | null>;
21
+ getRules(): Promise<Map<string, Rule>>;
22
+ canAddChild(_parent: IItem, _child: IItem): Promise<boolean>;
23
+ addChild(_parent: IItem, _child: IItem): Promise<boolean>;
24
+ removeChild(_parent: IItem, _child: IItem): Promise<boolean>;
25
+ removeChildren(_parent: IItem): Promise<boolean>;
26
+ hasChild(_parent: IItem, _child: IItem): Promise<boolean>;
27
+ getChildren(_name: string): Promise<Map<string, IItem>>;
28
+ assign(_role: Role | Permission, _username: string): Promise<Assignment>;
29
+ revoke(_role: Role | Permission, _username: string): Promise<boolean>;
30
+ revokeAll(_username: string): Promise<boolean>;
31
+ getAssignment(roleName: string, username: string): Promise<Assignment | null>;
32
+ getAssignments(username: string): Promise<Map<string, Assignment>>;
33
+ getUsernamesByRole(_roleName: string): Promise<string[]>;
34
+ removeAll(): Promise<void>;
35
+ removeAllPermissions(): Promise<void>;
36
+ removeAllRoles(): Promise<void>;
37
+ removeAllRules(): Promise<void>;
38
+ removeAllAssignments(): Promise<void>;
39
+ getItem(_name: string): Promise<IItem | null>;
40
+ getItems(_type: ItemType): Promise<Map<string, IItem>>;
41
+ addItem(_item: IItem): Promise<boolean>;
42
+ addRule(_rule: Rule): Promise<boolean>;
43
+ removeItem(_item: IItem): Promise<boolean>;
44
+ removeRule(_rule: Rule): Promise<boolean>;
45
+ updateItem(_name: string, _item: IItem): Promise<boolean>;
46
+ updateRule(_name: string, _rule: Rule): Promise<boolean>;
47
+ }
48
+ //# sourceMappingURL=WebManager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WebManager.d.ts","sourceRo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AAC,IAAI,CAAC;IAGrC,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC;IAG/B,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC;IAG/B,oBAAoB,IAAI,OAAO,CAAC,IAAI,CAAC;IAGrC,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC;IAG7C,QAAQ,CAAC,KAAK,EAAE,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAGtD,OAAO,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC;IAGvC,OAAO,CAAC,KAAK,EAAE,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC;IAGtC,UAAU,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC;IAG1C,UAAU,CAAC,KAAK,EAAE,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC;IAGzC,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC;IAGzD,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC;CAGzD"}
@@ -0,0 +1,236 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __rest = (this && this.__rest) || function (s, e) {
12
+ var t = {};
13
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
+ t[p] = s[p];
15
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
+ t[p[i]] = s[p[i]];
19
+ }
20
+ return t;
21
+ };
22
+ var __importDefault = (this && this.__importDefault) || function (mod) {
23
+ return (mod && mod.__esModule) ? mod : { "default": mod };
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ const axios_1 = __importDefault(require("axios"));
27
+ const http_status_codes_1 = __importDefault(require("http-status-codes"));
28
+ const rbac_1 = require("@iushev/rbac");
29
+ class WebManager extends rbac_1.BaseManager {
30
+ constructor(options) {
31
+ const { path, authorization } = options, restOptions = __rest(options, ["path", "authorization"]);
32
+ super(restOptions);
33
+ this.assignments = new Map();
34
+ this.axiosInstance = axios_1.default.create({
35
+ baseURL: path,
36
+ });
37
+ this.axiosInstance.interceptors.request.use((config) => {
38
+ if (authorization) {
39
+ const token = authorization();
40
+ config.headers.Authorization = "Bearer " + token;
41
+ }
42
+ else {
43
+ config.headers.Authorization = undefined;
44
+ }
45
+ return config;
46
+ });
47
+ }
48
+ load(config) {
49
+ return __awaiter(this, void 0, void 0, function* () {
50
+ var _a;
51
+ let _rbac;
52
+ try {
53
+ console.log("Load RBAC");
54
+ const response = yield this.axiosInstance.get("/rbac", config);
55
+ _rbac = response.data;
56
+ }
57
+ catch (err) {
58
+ if (axios_1.default.isAxiosError(err) && ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === http_status_codes_1.default.NOT_FOUND) {
59
+ _rbac = {
60
+ assignments: {},
61
+ items: {},
62
+ rules: {},
63
+ };
64
+ }
65
+ else {
66
+ throw err;
67
+ }
68
+ }
69
+ this.items = this.getRbacItems(_rbac);
70
+ this.parents = this.getRbacParents(_rbac);
71
+ this.rules = this.getRbacRules(_rbac);
72
+ this.assignments = this.getRbacAssignments(_rbac);
73
+ });
74
+ }
75
+ getRbacItems({ items }) {
76
+ return Object.keys(items).reduce((prevValue, name) => {
77
+ var _a, _b;
78
+ const item = items[name];
79
+ const ItemClass = item.type === rbac_1.ItemType.permission ? rbac_1.Permission : rbac_1.Role;
80
+ prevValue.set(name, new ItemClass({
81
+ name,
82
+ description: (_a = item.description) !== null && _a !== void 0 ? _a : null,
83
+ ruleName: (_b = item.ruleName) !== null && _b !== void 0 ? _b : null,
84
+ }));
85
+ return prevValue;
86
+ }, new Map());
87
+ }
88
+ getRbacParents({ items }) {
89
+ return Object.keys(items).reduce((prevValue, name) => {
90
+ const item = items[name];
91
+ if (!item.children || item.children.length === 0) {
92
+ return prevValue;
93
+ }
94
+ item.children.forEach((childName) => {
95
+ if (!this.items.has(childName)) {
96
+ return;
97
+ }
98
+ let child = prevValue.get(childName);
99
+ if (!child) {
100
+ child = new Map();
101
+ prevValue.set(childName, child);
102
+ }
103
+ const item = this.items.get(name);
104
+ if (item) {
105
+ child.set(name, item);
106
+ }
107
+ });
108
+ return prevValue;
109
+ }, new Map());
110
+ }
111
+ getRbacRules({ rules }) {
112
+ return Object.keys(rules).reduce((prevValue, name) => {
113
+ var _a;
114
+ const ruleData = rules[name];
115
+ const RuleClass = (_a = this.ruleClasses.get(ruleData.data.typeName)) !== null && _a !== void 0 ? _a : rbac_1.Rule;
116
+ const rule = new RuleClass(name, JSON.parse(ruleData.data.ruleData));
117
+ prevValue.set(name, rule);
118
+ return prevValue;
119
+ }, new Map());
120
+ }
121
+ getRbacAssignments({ assignments }) {
122
+ return Object.keys(assignments).reduce((prevValue, username) => {
123
+ const _assignments = assignments[username];
124
+ _assignments.forEach((itemName) => {
125
+ var _a;
126
+ if (prevValue.has(username)) {
127
+ (_a = prevValue.get(username)) === null || _a === void 0 ? void 0 : _a.set(itemName, new rbac_1.Assignment(username, itemName));
128
+ }
129
+ else {
130
+ prevValue.set(username, new Map([[itemName, new rbac_1.Assignment(username, itemName)]]));
131
+ }
132
+ });
133
+ return prevValue;
134
+ }, new Map());
135
+ }
136
+ getRolesByUser(_username) {
137
+ throw new Error("Method not implemented.");
138
+ }
139
+ getChildRoles(_roleName) {
140
+ throw new Error("Method not implemented.");
141
+ }
142
+ getPermissionsByRole(_roleName) {
143
+ throw new Error("Method not implemented.");
144
+ }
145
+ getPermissionsByUser(_username) {
146
+ throw new Error("Method not implemented.");
147
+ }
148
+ getRule(_name) {
149
+ throw new Error("Method not implemented.");
150
+ }
151
+ getRules() {
152
+ throw new Error("Method not implemented.");
153
+ }
154
+ canAddChild(_parent, _child) {
155
+ throw new Error("Method not implemented.");
156
+ }
157
+ addChild(_parent, _child) {
158
+ throw new Error("Method not implemented.");
159
+ }
160
+ removeChild(_parent, _child) {
161
+ throw new Error("Method not implemented.");
162
+ }
163
+ removeChildren(_parent) {
164
+ throw new Error("Method not implemented.");
165
+ }
166
+ hasChild(_parent, _child) {
167
+ throw new Error("Method not implemented.");
168
+ }
169
+ getChildren(_name) {
170
+ throw new Error("Method not implemented.");
171
+ }
172
+ assign(_role, _username) {
173
+ throw new Error("Method not implemented.");
174
+ }
175
+ revoke(_role, _username) {
176
+ throw new Error("Method not implemented.");
177
+ }
178
+ revokeAll(_username) {
179
+ throw new Error("Method not implemented.");
180
+ }
181
+ getAssignment(roleName, username) {
182
+ return __awaiter(this, void 0, void 0, function* () {
183
+ var _a, _b;
184
+ return (_b = (_a = this.assignments.get(username)) === null || _a === void 0 ? void 0 : _a.get(roleName)) !== null && _b !== void 0 ? _b : null;
185
+ });
186
+ }
187
+ getAssignments(username) {
188
+ return __awaiter(this, void 0, void 0, function* () {
189
+ var _a;
190
+ return (_a = this.assignments.get(username)) !== null && _a !== void 0 ? _a : new Map();
191
+ });
192
+ }
193
+ getUsernamesByRole(_roleName) {
194
+ throw new Error("Method not implemented.");
195
+ }
196
+ removeAll() {
197
+ throw new Error("Method not implemented.");
198
+ }
199
+ removeAllPermissions() {
200
+ throw new Error("Method not implemented.");
201
+ }
202
+ removeAllRoles() {
203
+ throw new Error("Method not implemented.");
204
+ }
205
+ removeAllRules() {
206
+ throw new Error("Method not implemented.");
207
+ }
208
+ removeAllAssignments() {
209
+ throw new Error("Method not implemented.");
210
+ }
211
+ getItem(_name) {
212
+ throw new Error("Method not implemented.");
213
+ }
214
+ getItems(_type) {
215
+ throw new Error("Method not implemented.");
216
+ }
217
+ addItem(_item) {
218
+ throw new Error("Method not implemented.");
219
+ }
220
+ addRule(_rule) {
221
+ throw new Error("Method not implemented.");
222
+ }
223
+ removeItem(_item) {
224
+ throw new Error("Method not implemented.");
225
+ }
226
+ removeRule(_rule) {
227
+ throw new Error("Method not implemented.");
228
+ }
229
+ updateItem(_name, _item) {
230
+ throw new Error("Method not implemented.");
231
+ }
232
+ updateRule(_name, _rule) {
233
+ throw new Error("Method not implemented.");
234
+ }
235
+ }
236
+ exports.default = WebManager;
package/lib/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}
package/lib/index.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@iushev/rbac-web-manager",
3
+ "version": "1.0.0",
4
+ "private": false,
5
+ "author": "Ivaylo Ushev",
6
+ "description": "RBAC Web Manager",
7
+ "license": "ISC",
8
+ "keywords": [],
9
+ "main": "lib/index",
10
+ "types": "lib/index",
11
+ "scripts": {
12
+ "build": "tsc",
13
+ "watch": "tsc -w --preserveWatchOutput",
14
+ "test": "jest --runInBand",
15
+ "test:watch": "jest --watch --runInBand",
16
+ "coverage": "jest --coverage --runInBand",
17
+ "lint": "eslint src",
18
+ "preversion": "rimraf ./lib && npm run build"
19
+ },
20
+ "devDependencies": {
21
+ "@types/jest": "^30.0.0",
22
+ "@types/node": "^24.10.4",
23
+ "@typescript-eslint/eslint-plugin": "^8.49.0",
24
+ "@typescript-eslint/parser": "^8.49.0",
25
+ "eslint": "^9.39.2",
26
+ "eslint-config-prettier": "^10.1.8",
27
+ "eslint-plugin-prettier": "^5.5.4",
28
+ "jest": "^30.2.0",
29
+ "prettier": "^3.7.4",
30
+ "rimraf": "^6.1.2",
31
+ "ts-jest": "^29.4.6",
32
+ "typescript": "^5.9.3"
33
+ },
34
+ "peerDependencies": {
35
+ "@iushev/rbac": "^1.0.53",
36
+ "axios": "^1.13.2",
37
+ "http-status-codes": "^2.3.0"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ }
42
+ }
@@ -0,0 +1,230 @@
1
+ import axios, { AxiosInstance, AxiosRequestConfig } from "axios";
2
+ import statusCodes from "http-status-codes";
3
+
4
+ import {
5
+ Assignment,
6
+ BaseManager,
7
+ BaseManagerOptions,
8
+ IItem,
9
+ ItemType,
10
+ Permission,
11
+ RBACResponse,
12
+ Role,
13
+ Rule,
14
+ } from "@iushev/rbac";
15
+
16
+ export type WebManagerOptions = BaseManagerOptions & {
17
+ path: string;
18
+ authorization: () => string;
19
+ };
20
+
21
+ export default class WebManager extends BaseManager {
22
+ private readonly axiosInstance: AxiosInstance;
23
+
24
+ protected assignments: Map<string, Map<string, Assignment>> = new Map();
25
+
26
+ constructor(options: WebManagerOptions) {
27
+ const { path, authorization, ...restOptions } = options;
28
+ super(restOptions);
29
+
30
+ this.axiosInstance = axios.create({
31
+ baseURL: path,
32
+ });
33
+
34
+ this.axiosInstance.interceptors.request.use((config) => {
35
+ if (authorization) {
36
+ const token = authorization();
37
+ config.headers.Authorization = "Bearer " + token;
38
+ } else {
39
+ config.headers.Authorization = undefined;
40
+ }
41
+ return config;
42
+ });
43
+ }
44
+
45
+ async load(config?: AxiosRequestConfig): Promise<void> {
46
+ let _rbac: RBACResponse;
47
+ try {
48
+ console.log("Load RBAC");
49
+ const response = await this.axiosInstance.get<RBACResponse>("/rbac", config);
50
+ _rbac = response.data;
51
+ } catch (err) {
52
+ if (axios.isAxiosError(err) && err.response?.status === statusCodes.NOT_FOUND) {
53
+ _rbac = {
54
+ assignments: {},
55
+ items: {},
56
+ rules: {},
57
+ };
58
+ } else {
59
+ throw err;
60
+ }
61
+ }
62
+
63
+ this.items = this.getRbacItems(_rbac);
64
+ this.parents = this.getRbacParents(_rbac);
65
+ this.rules = this.getRbacRules(_rbac);
66
+ this.assignments = this.getRbacAssignments(_rbac);
67
+ }
68
+
69
+ private getRbacItems({ items }: RBACResponse) {
70
+ return Object.keys(items).reduce<Map<string, IItem>>((prevValue, name) => {
71
+ const item = items[name];
72
+ const ItemClass = item.type === ItemType.permission ? Permission : Role;
73
+ prevValue.set(
74
+ name,
75
+ new ItemClass({
76
+ name,
77
+ description: item.description ?? null,
78
+ ruleName: item.ruleName ?? null,
79
+ }),
80
+ );
81
+ return prevValue;
82
+ }, new Map());
83
+ }
84
+
85
+ private getRbacParents({ items }: RBACResponse) {
86
+ return Object.keys(items).reduce<Map<string, Map<string, IItem>>>((prevValue, name) => {
87
+ const item = items[name];
88
+ if (!item.children || item.children.length === 0) {
89
+ return prevValue;
90
+ }
91
+ item.children.forEach((childName: string) => {
92
+ if (!this.items.has(childName)) {
93
+ return;
94
+ }
95
+
96
+ let child = prevValue.get(childName);
97
+
98
+ if (!child) {
99
+ child = new Map();
100
+ prevValue.set(childName, child);
101
+ }
102
+
103
+ const item = this.items.get(name);
104
+ if (item) {
105
+ child.set(name, item);
106
+ }
107
+ });
108
+
109
+ return prevValue;
110
+ }, new Map());
111
+ }
112
+
113
+ private getRbacRules({ rules }: RBACResponse) {
114
+ return Object.keys(rules).reduce<Map<string, Rule>>((prevValue, name) => {
115
+ const ruleData = rules[name];
116
+ const RuleClass = this.ruleClasses.get(ruleData.data.typeName) ?? Rule;
117
+ const rule = new RuleClass(name, JSON.parse(ruleData.data.ruleData));
118
+ prevValue.set(name, rule);
119
+ return prevValue;
120
+ }, new Map());
121
+ }
122
+
123
+ private getRbacAssignments({ assignments }: RBACResponse) {
124
+ return Object.keys(assignments).reduce<Map<string, Map<string, Assignment>>>((prevValue, username) => {
125
+ const _assignments = assignments[username];
126
+ _assignments.forEach((itemName) => {
127
+ if (prevValue.has(username)) {
128
+ prevValue.get(username)?.set(itemName, new Assignment(username, itemName));
129
+ } else {
130
+ prevValue.set(username, new Map([[itemName, new Assignment(username, itemName)]]));
131
+ }
132
+ });
133
+ return prevValue;
134
+ }, new Map());
135
+ }
136
+
137
+ getRolesByUser(_username: string): Promise<Map<string, Role>> {
138
+ throw new Error("Method not implemented.");
139
+ }
140
+ getChildRoles(_roleName: string): Promise<Map<string, Role>> {
141
+ throw new Error("Method not implemented.");
142
+ }
143
+ getPermissionsByRole(_roleName: string): Promise<Map<string, Permission>> {
144
+ throw new Error("Method not implemented.");
145
+ }
146
+ getPermissionsByUser(_username: string): Promise<Map<string, Permission>> {
147
+ throw new Error("Method not implemented.");
148
+ }
149
+ getRule(_name: string): Promise<Rule | null> {
150
+ throw new Error("Method not implemented.");
151
+ }
152
+ getRules(): Promise<Map<string, Rule>> {
153
+ throw new Error("Method not implemented.");
154
+ }
155
+ canAddChild(_parent: IItem, _child: IItem): Promise<boolean> {
156
+ throw new Error("Method not implemented.");
157
+ }
158
+ addChild(_parent: IItem, _child: IItem): Promise<boolean> {
159
+ throw new Error("Method not implemented.");
160
+ }
161
+ removeChild(_parent: IItem, _child: IItem): Promise<boolean> {
162
+ throw new Error("Method not implemented.");
163
+ }
164
+ removeChildren(_parent: IItem): Promise<boolean> {
165
+ throw new Error("Method not implemented.");
166
+ }
167
+ hasChild(_parent: IItem, _child: IItem): Promise<boolean> {
168
+ throw new Error("Method not implemented.");
169
+ }
170
+ getChildren(_name: string): Promise<Map<string, IItem>> {
171
+ throw new Error("Method not implemented.");
172
+ }
173
+ assign(_role: Role | Permission, _username: string): Promise<Assignment> {
174
+ throw new Error("Method not implemented.");
175
+ }
176
+ revoke(_role: Role | Permission, _username: string): Promise<boolean> {
177
+ throw new Error("Method not implemented.");
178
+ }
179
+ revokeAll(_username: string): Promise<boolean> {
180
+ throw new Error("Method not implemented.");
181
+ }
182
+ async getAssignment(roleName: string, username: string): Promise<Assignment | null> {
183
+ return this.assignments.get(username)?.get(roleName) ?? null;
184
+ }
185
+ async getAssignments(username: string): Promise<Map<string, Assignment>> {
186
+ return this.assignments.get(username) ?? new Map();
187
+ }
188
+ getUsernamesByRole(_roleName: string): Promise<string[]> {
189
+ throw new Error("Method not implemented.");
190
+ }
191
+ removeAll(): Promise<void> {
192
+ throw new Error("Method not implemented.");
193
+ }
194
+ removeAllPermissions(): Promise<void> {
195
+ throw new Error("Method not implemented.");
196
+ }
197
+ removeAllRoles(): Promise<void> {
198
+ throw new Error("Method not implemented.");
199
+ }
200
+ removeAllRules(): Promise<void> {
201
+ throw new Error("Method not implemented.");
202
+ }
203
+ removeAllAssignments(): Promise<void> {
204
+ throw new Error("Method not implemented.");
205
+ }
206
+ getItem(_name: string): Promise<IItem | null> {
207
+ throw new Error("Method not implemented.");
208
+ }
209
+ getItems(_type: ItemType): Promise<Map<string, IItem>> {
210
+ throw new Error("Method not implemented.");
211
+ }
212
+ addItem(_item: IItem): Promise<boolean> {
213
+ throw new Error("Method not implemented.");
214
+ }
215
+ addRule(_rule: Rule): Promise<boolean> {
216
+ throw new Error("Method not implemented.");
217
+ }
218
+ removeItem(_item: IItem): Promise<boolean> {
219
+ throw new Error("Method not implemented.");
220
+ }
221
+ removeRule(_rule: Rule): Promise<boolean> {
222
+ throw new Error("Method not implemented.");
223
+ }
224
+ updateItem(_name: string, _item: IItem): Promise<boolean> {
225
+ throw new Error("Method not implemented.");
226
+ }
227
+ updateRule(_name: string, _rule: Rule): Promise<boolean> {
228
+ throw new Error("Method not implemented.");
229
+ }
230
+ }
package/src/index.ts ADDED
File without changes
package/tsconfig.json ADDED
@@ -0,0 +1,103 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig.json to read more about this file */
4
+
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. */
12
+
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": "preserve", /* 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. */
25
+
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. */
38
+
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`. */
43
+
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. */
68
+
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. */,
75
+
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. */
100
+ },
101
+ "include": ["src"],
102
+ "exclude": ["lib", "node_modules", "src/__tests__"]
103
+ }