nest-access-control 2.0.0 → 2.0.4

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/README.md CHANGED
@@ -1,6 +1,5 @@
1
1
  # Nest Access Control
2
2
 
3
-
4
3
  ![MIT](https://img.shields.io/cocoapods/l/AFNetworking.svg?style=flat-square)
5
4
  [![npm version](https://badge.fury.io/js/nest-access-control.svg)](https://badge.fury.io/js/nest-access-control)
6
5
  ![Open Source Love](https://badges.frapsoft.com/os/v1/open-source.svg?v=102)
@@ -12,39 +11,39 @@
12
11
 
13
12
  > TL;DR: recently our system was needing to have a Control Panel, so you can control, and monitor every thing from there, and it was really really needing some Role based access control system, so i build this module for that, it is really cool, so i'd love to share it with you, and any PR are more than welcome :heart:
14
13
 
15
- this module is built on top of [onury's](https://github.com/onury) [accesscontrol](https://github.com/onury/accesscontrol) library
14
+ This module is built on top of [onury's](https://github.com/onury) [accesscontrol](https://github.com/onury/accesscontrol) library
16
15
  here is some of it's Core Features
17
16
 
18
- * Chainable, friendly API.
17
+ - Chainable, friendly API.
19
18
  e.g. `ac.can(role).create(resource)`
20
- * Role hierarchical **inheritance**.
21
- * Define grants **at once** (e.g. from database result) or **one by one**.
22
- * Grant/deny permissions by attributes defined by **glob notation** (with nested object support).
23
- * Ability to **filter** data (model) instance by allowed attributes.
24
- * Ability to control access on **own** or **any** resources.
25
- * Ability to **lock** underlying grants model.
26
- * No **silent** errors.
27
- * **Fast**. (Grants are stored in memory, no database queries.)
28
- * Brutally **tested**.
29
- * TypeScript support.
19
+ - Role hierarchical **inheritance**.
20
+ - Define grants **at once** (e.g. from database result) or **one by one**.
21
+ - Grant/deny permissions by attributes defined by **glob notation** (with nested object support).
22
+ - Ability to **filter** data (model) instance by allowed attributes.
23
+ - Ability to control access on **own** or **any** resources.
24
+ - Ability to **lock** underlying grants model.
25
+ - No **silent** errors.
26
+ - **Fast**. (Grants are stored in memory, no database queries.)
27
+ - Brutally **tested**.
28
+ - TypeScript support.
30
29
 
31
- #### + What this Module Provide ?
30
+ #### What does this Module Provide?
32
31
 
33
- in this module you will have all these features out of the box, but in nest-ish way.
32
+ In this module you will have all these features out of the box, but in nest-ish way.
34
33
 
35
- * It's **Decorator-based** so most of the time you will use decorators in your routes.
36
- * Built-in **ACGuard** so you can go and use it directly.
37
- * Access to the underlying **AccessControl** object from everywhere.
34
+ - It's **Decorator-based** so most of the time you will use decorators in your routes.
35
+ - Built-in **ACGuard** so you can go and use it directly.
36
+ - Access to the underlying **AccessControl** object from everywhere.
38
37
 
39
38
  ## Installation
40
39
 
41
- * NPM:
40
+ - NPM:
42
41
 
43
42
  ```bash
44
43
  npm install nest-access-control --save
45
44
  ```
46
45
 
47
- * Yarn:
46
+ - Yarn:
48
47
 
49
48
  ```bash
50
49
  yarn add nest-access-control
@@ -54,101 +53,140 @@ yarn add nest-access-control
54
53
 
55
54
  #### Example
56
55
 
57
- > see example folder for the more code;
56
+ > See example folder for the more code
58
57
 
59
58
  We need to build a Video service so users can share there videos with others, but we need some `admins` to control these videos.
60
59
 
61
- 1. let's first define our roles:
60
+ 1. Let's first define our roles:
62
61
 
63
- to build our roles we will need the `RolesBuilder` class, it extends the `AccessControl` class from `accesscontrol` package.
62
+ To build our roles we will need the `RolesBuilder` class, it extends the `AccessControl` class from `accesscontrol` package.
64
63
 
65
- ```ts
66
- // app.roles.ts
64
+ ```ts
65
+ // app.roles.ts
67
66
 
68
- export enum AppRoles {
69
- USER_CREATE_ANY_VIDEO = 'USER_CREATE_ANY_VIDEO',
70
- ADMIN_UPDATE_OWN_VIDEO = 'ADMIN_UPDATE_OWN_VIDEO',
71
- }
67
+ export enum AppRoles {
68
+ USER_CREATE_ANY_VIDEO = 'USER_CREATE_ANY_VIDEO',
69
+ ADMIN_UPDATE_OWN_VIDEO = 'ADMIN_UPDATE_OWN_VIDEO',
70
+ }
72
71
 
73
- export const roles: RolesBuilder = new RolesBuilder();
74
-
75
- roles
76
- .grant(AppRoles.USER_CREATE_ANY_VIDEO) // define new or modify existing role. also takes an array.
77
- .createOwn('video') // equivalent to .createOwn('video', ['*'])
78
- .deleteOwn('video')
79
- .readAny('video')
80
- .grant(AppRoles.ADMIN_UPDATE_OWN_VIDEO) // switch to another role without breaking the chain
81
- .extend(AppRoles.USER_CREATE_ANY_VIDEO) // inherit role capabilities. also takes an array
82
- .updateAny('video', ['title']) // explicitly defined attributes
83
- .deleteAny('video');
84
- ```
72
+ export const roles: RolesBuilder = new RolesBuilder();
73
+
74
+ roles
75
+ .grant(AppRoles.USER_CREATE_ANY_VIDEO) // define new or modify existing role. also takes an array.
76
+ .createOwn('video') // equivalent to .createOwn('video', ['*'])
77
+ .deleteOwn('video')
78
+ .readAny('video')
79
+ .grant(AppRoles.ADMIN_UPDATE_OWN_VIDEO) // switch to another role without breaking the chain
80
+ .extend(AppRoles.USER_CREATE_ANY_VIDEO) // inherit role capabilities. also takes an array
81
+ .updateAny('video', ['title']) // explicitly defined attributes
82
+ .deleteAny('video');
83
+ ```
85
84
 
86
85
  > Pro Tip :+1: : Keep all roles organized and in one file e,g: `app.roles.ts`
87
86
 
88
- 2. next let's use `AccessControlModule` in our Root module:
87
+ 2. Next let's use `AccessControlModule` in our Root module:
89
88
 
90
89
  ```ts
91
- // app.module.ts
90
+ // app.module.ts
92
91
 
93
- import { roles } from './app.roles';
92
+ import { roles } from './app.roles';
94
93
 
95
- @Module({
96
- imports: [AccessControlModule.forRoles(roles)],
97
- controllers: [AppController],
98
- providers: [AppService],
99
- })
100
- export class AppModule {}
94
+ @Module({
95
+ imports: [AccessControlModule.forRoles(roles)],
96
+ controllers: [AppController],
97
+ providers: [AppService],
98
+ })
99
+ export class AppModule {}
100
+ ```
101
+
102
+ Until now everything is fine, but let's make our application,
103
+ assume that we have list of video names, user can - _according to our roles_ - `create:own` new video, and `read:any` video, so let's build it:
104
+ ```
105
+
106
+ ```ts
107
+ // app.controller.ts
108
+ ...
109
+ @Controller()
110
+ export class AppController {
111
+ constructor(private readonly appService: AppService) {}
112
+ @UseGuards(AuthGuard, ACGuard)
113
+ @UseRoles({
114
+ resource: 'video',
115
+ action: 'read',
116
+ possession: 'any',
117
+ })
118
+ @Get()
119
+ root(@UserRoles() userRoles: any) {
120
+ return this.appService.root(userRoles);
121
+ }
122
+ }
101
123
  ```
102
124
 
103
- until now everything is fine, but let's make our application,
104
- assume that we have list of video names, user can - _according to our roles_ - `create:own` new video, and `read:any` video, so let's build it
125
+ ### ForRootAsync
126
+
127
+ Injecting providers for a RoleBuilder Factory (using a database to populate roles)
105
128
 
106
129
  ```ts
107
- // app.controller.ts
108
- ...
109
- @Controller()
110
- export class AppController {
111
- constructor(private readonly appService: AppService) {}
112
- @UseGuards(AuthGuard, ACGuard)
113
- @UseRoles({
114
- resource: 'video',
115
- action: 'read',
116
- possession: 'any',
117
- })
118
- @Get()
119
- root(@UserRoles() userRoles: any) {
120
- return this.appService.root(userRoles);
121
- }
130
+ @Injectable()
131
+ class RoleProvider {
132
+
133
+ getRoles(): Promise<string[]> {
134
+ return Promise.resolve([
135
+ 'my-custom-role',
136
+ ]);
137
+ }
138
+ }
139
+
140
+ @Module({
141
+ providers: [RoleProvider],
142
+ exports: [RoleProvider],
143
+ })
144
+ class RoleModule {
145
+
122
146
  }
147
+
148
+ @Module({
149
+ imports: [
150
+ AccessControlModule.forRootAsync({
151
+ imports: [TestModule],
152
+ inject: [RoleService],
153
+ useFactory: async (roleService: RoleService): Promise<RolesBuilder> => {
154
+ return new RolesBuilder(await roleService.getRoles());
155
+ },
156
+ }),
157
+ ],
158
+ })
159
+ export class AccessModule {}
123
160
  ```
161
+ Notice the use of `imports` in the forRootAsync method. This will allow you to inject exported providers from the imported module. Injecting providers, provided in the same module as the imported AccessControlModule will result in the provider not being found. This is because the module is created before the providers.
124
162
 
125
- so let's discuss what's going on !
163
+ So let's discuss what's going on!
126
164
 
127
165
  First we introduced two new decorators, actually they are three, but let's see what they can do:
128
166
 
129
- * `@UseRoles({ ... })`: this the most used decorator, it define what roles should user have to access this route.
130
- it may take one or more role, but keep in mind that all roles **must** be satisfied.
131
- the structure of the role is really simple, for example, here we define what resources we have, and the **ACGuard\*** - _Damn, it's a good name for a guard :joy:_ - will check for the user roles, then if the user roles have the permissions to access this resource the guard will return `true`, else it will throw a `ForbiddenException`.
132
- for more information about the structure of roles see `roles.interface.ts` file or read the original [documentation](https://onury.io/accesscontrol/) form `accesscontrol` library [here](https://onury.io/accesscontrol/?api=ac#AccessControl~IQueryInfo) .
167
+ - `@UseRoles({ ... })`: this the most used decorator, it define what roles should user have to access this route.
168
+ It may take one or more role, but keep in mind that all roles **must** be satisfied.
169
+ The structure of the role is really simple, for example, here we define what resources we have, and the **ACGuard\*** - _Damn, it's a good name for a guard :joy:_ - will check for the user roles, then if the user roles have the permissions to access this resource the guard will return `true`, else it will throw a `ForbiddenException`.
170
+ For more information about the structure of roles see `roles.interface.ts` file or read the original [documentation](https://onury.io/accesscontrol/) form `accesscontrol` library [here](https://onury.io/accesscontrol/?api=ac#AccessControl~IQueryInfo).
133
171
  > \*note: for those who are asking what ACGuard stands for, it of course stands for Access Control Guard :smile:
134
172
 
135
- - `UserRoles(<prop>)`: if you want to get access to the user roles directly, maybe you want to check it's roles manually instead of `ACGuard` doing it for you, then that decorator what you are looking for.
136
- the decorator it really simple, it just return the `req.user.roles` value from the `request` object, but wait, what if the user roles isn't exist in `prop: role` , we know that you will ask this question, so that You can pass an optional property key to the decorator to get it from the user object e.g `@UserRoles('permissions')` will return the `req.user.permissions` instead.
173
+ * `UserRoles(<prop>)`: if you want to get access to the user roles directly, maybe you want to check it's roles manually instead of `ACGuard` doing it for you, then that decorator is what you are looking for.
174
+ The decorator is really simple, it just return the `req.user.roles` value from the `request` object, but wait, what if the user roles doesn't exist in `prop: role`? We knew that you would ask this question, so you can pass an optional property key to the decorator to get it from the user object e.g `@UserRoles('permissions')` will return the `req.user.permissions` instead.
137
175
 
138
- - `@InjectRolesBuilder()`: If you hate the `ACGuard` - _imo it's a good guard_ - and want to build your own Guard instead, you will likely need to access to the underlying `RolesBuilder` Object , then that decorator for you, it will inject the `Roles` you have defined before, i.e the object passed to the `AccessControlModule.forRoles(roles)`.
176
+ * `@InjectRolesBuilder()`: if you hate the `ACGuard` - _imo it's a good guard_ - and want to build your own Guard instead, you will likely need to access to the underlying `RolesBuilder` Object , then that decorator is for you; it will inject the `Roles` you have defined before, i.e the object passed to the `AccessControlModule.forRoles(roles)`.
139
177
 
140
- 4. are you still there ? Ok, that's it, you can go and run the application now, but wait, did someone asked for the `AuthGuard` ?
141
- Ok let's discuss the **LIMITATIONS**
178
+ 4. Are you still there? Ok, that's it, you can go and run the application now, but wait, did someone asked for the `AuthGuard`?
179
+ Ok let's discuss the **LIMITATIONS**.
142
180
 
143
181
  #### Limitations
144
182
 
145
183
  First of all, this module built with some assumptions
146
184
 
147
- 1. the user object will be exist in `req.user`
148
- 2. it is up to you to build your own `AuthGuard` that will attach the `user` object to the `req` object, [read more](https://docs.nestjs.com/guards)
149
- 3. the `AuthGuard` must be registered before roles guard, in this case it's `ACGuard`, and of course you can combine the `AuthGuard` and `ACGuard` in one guard, and use it everywhere.
185
+ 1. The user object will exist in `req.user`
186
+ 2. It is up to you to build your own `AuthGuard` that will attach the `user` object to the `req` object, [read more](https://docs.nestjs.com/guards)
187
+ 3. The `AuthGuard` must be registered before roles guard, in this case it's `ACGuard`, and of course you can combine the `AuthGuard` and `ACGuard` in one guard, and use it everywhere.
150
188
 
151
- secondly, i don't think these are limitations, since you can easily build your own guard and you don't need the built-in ones anymore.
189
+ Secondly, i don't think these are limitations, since you can easily build your own guard and you don't need the built-in ones anymore.
152
190
 
153
191
  ## CHANGELOG
154
192
 
@@ -156,14 +194,14 @@ See [CHANGELOG](CHANGELOG.md) for more information.
156
194
 
157
195
  ## Contributing
158
196
 
159
- you are welcome with this project for contributing, just make a PR
197
+ You are welcome with this project for contributing, just make a PR.
160
198
 
161
199
  ## Authors
162
200
 
163
- * **Shady Khalifa** - _Initial work_
201
+ - **Shady Khalifa** - _Initial work_
164
202
 
165
- See also the list of [contributors](https://github.com/shekohex/nest-access-control/contributors) who participated in this project.
203
+ See also the list of [contributors](https://github.com/nestjsx/nest-access-control/contributors) who participated in this project.
166
204
 
167
205
  ## License
168
206
 
169
- This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
207
+ This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details.
@@ -0,0 +1,6 @@
1
+ export interface ACOptions {
2
+ /**
3
+ * A name of endpoint which serves grants
4
+ */
5
+ grantsEndpoint?: string;
6
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -5,7 +5,7 @@ export declare class ACGuard<User extends any = any> implements CanActivate {
5
5
  private readonly reflector;
6
6
  private readonly roleBuilder;
7
7
  constructor(reflector: Reflector, roleBuilder: RolesBuilder);
8
- private getUser;
9
- private getUserRoles;
8
+ protected getUser(context: ExecutionContext): Promise<User>;
9
+ protected getUserRoles(context: ExecutionContext): Promise<string | string[]>;
10
10
  canActivate(context: ExecutionContext): Promise<boolean>;
11
11
  }
@@ -12,6 +12,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
12
  return function (target, key) { decorator(target, key, paramIndex); }
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.ACGuard = void 0;
15
16
  const common_1 = require("@nestjs/common");
16
17
  const core_1 = require("@nestjs/core");
17
18
  const inject_roles_builder_decorator_1 = require("./decorators/inject-roles-builder.decorator");
@@ -29,7 +30,7 @@ let ACGuard = class ACGuard {
29
30
  const user = await this.getUser(context);
30
31
  if (!user)
31
32
  throw new common_1.UnauthorizedException();
32
- return user.roles;
33
+ return user['roles'];
33
34
  }
34
35
  async canActivate(context) {
35
36
  const roles = this.reflector.get('roles', context.getHandler());
@@ -37,7 +38,7 @@ let ACGuard = class ACGuard {
37
38
  return true;
38
39
  }
39
40
  const userRoles = await this.getUserRoles(context);
40
- const hasRoles = roles.every(role => {
41
+ const hasRoles = roles.every((role) => {
41
42
  const queryInfo = role;
42
43
  queryInfo.role = userRoles;
43
44
  const permission = this.roleBuilder.permission(queryInfo);
@@ -47,8 +48,8 @@ let ACGuard = class ACGuard {
47
48
  }
48
49
  };
49
50
  ACGuard = __decorate([
50
- common_1.Injectable(),
51
- __param(1, inject_roles_builder_decorator_1.InjectRolesBuilder()),
51
+ (0, common_1.Injectable)(),
52
+ __param(1, (0, inject_roles_builder_decorator_1.InjectRolesBuilder)()),
52
53
  __metadata("design:paramtypes", [core_1.Reflector,
53
54
  roles_builder_class_1.RolesBuilder])
54
55
  ], ACGuard);
@@ -1,10 +1,18 @@
1
- import { DynamicModule } from '@nestjs/common';
1
+ import { DynamicModule, Abstract, Type, ForwardReference } from '@nestjs/common';
2
2
  import { RolesBuilder } from './roles-builder.class';
3
+ import { ACOptions } from './ac-options.interface';
3
4
  export declare class AccessControlModule {
4
5
  /**
5
6
  * Register a pre-defined roles
6
7
  * @param {RolesBuilder} roles A list containing the access grant
7
8
  * definitions. See the structure of this object in the examples.
9
+ * @param {ACOptions} options A list of configurable options (currently just one)
8
10
  */
9
- static forRoles(roles: RolesBuilder): DynamicModule;
11
+ static forRoles(roles: RolesBuilder, options?: ACOptions): DynamicModule;
12
+ static forRootAsync(options: {
13
+ imports?: Array<Type<any> | DynamicModule | Promise<DynamicModule> | ForwardReference>;
14
+ inject?: Array<Type<any> | string | symbol | Abstract<any> | Function>;
15
+ useFactory: (...args: any) => RolesBuilder | Promise<RolesBuilder>;
16
+ grantsEndpoint?: string;
17
+ }): DynamicModule;
10
18
  }
@@ -5,36 +5,69 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
5
5
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
6
  return c > 3 && r && Object.defineProperty(target, key, r), r;
7
7
  };
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
8
  var AccessControlModule_1;
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.AccessControlModule = void 0;
10
11
  const common_1 = require("@nestjs/common");
11
- const constants_1 = require("./constants");
12
+ const constants_1 = require("@nestjs/common/constants");
13
+ const constants_2 = require("./constants");
14
+ const grants_controller_1 = require("./grants.controller");
12
15
  let AccessControlModule = AccessControlModule_1 = class AccessControlModule {
13
16
  /**
14
17
  * Register a pre-defined roles
15
18
  * @param {RolesBuilder} roles A list containing the access grant
16
19
  * definitions. See the structure of this object in the examples.
20
+ * @param {ACOptions} options A list of configurable options (currently just one)
17
21
  */
18
- static forRoles(roles) {
22
+ static forRoles(roles, options) {
23
+ let controllers = [];
24
+ if (options) {
25
+ Reflect.defineMetadata(constants_1.PATH_METADATA, options.grantsEndpoint, grants_controller_1.GrantsController);
26
+ controllers = [...(options.grantsEndpoint ? [grants_controller_1.GrantsController] : [])];
27
+ }
19
28
  return {
20
29
  module: AccessControlModule_1,
30
+ controllers: [...controllers],
21
31
  providers: [
22
32
  {
23
- provide: constants_1.ROLES_BUILDER_TOKEN,
33
+ provide: constants_2.ROLES_BUILDER_TOKEN,
24
34
  useValue: roles,
25
35
  },
26
36
  ],
27
37
  exports: [
28
38
  {
29
- provide: constants_1.ROLES_BUILDER_TOKEN,
39
+ provide: constants_2.ROLES_BUILDER_TOKEN,
30
40
  useValue: roles,
31
41
  },
32
42
  ],
33
43
  };
34
44
  }
45
+ static forRootAsync(options) {
46
+ const provider = {
47
+ provide: constants_2.ROLES_BUILDER_TOKEN,
48
+ useFactory: options.useFactory,
49
+ inject: options.inject || [],
50
+ };
51
+ let controllers = [];
52
+ if (options && options.grantsEndpoint) {
53
+ Reflect.defineMetadata(constants_1.PATH_METADATA, options.grantsEndpoint, grants_controller_1.GrantsController);
54
+ controllers = [
55
+ ...options.grantsEndpoint ? [grants_controller_1.GrantsController] : [],
56
+ ];
57
+ }
58
+ return {
59
+ imports: [...(options.imports || [])],
60
+ controllers: [
61
+ ...controllers,
62
+ ],
63
+ module: AccessControlModule_1,
64
+ providers: [provider],
65
+ exports: [provider],
66
+ };
67
+ }
35
68
  };
36
69
  AccessControlModule = AccessControlModule_1 = __decorate([
37
- common_1.Global(),
38
- common_1.Module({})
70
+ (0, common_1.Global)(),
71
+ (0, common_1.Module)({})
39
72
  ], AccessControlModule);
40
73
  exports.AccessControlModule = AccessControlModule;
package/constants.js CHANGED
@@ -1,3 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ROLES_BUILDER_TOKEN = void 0;
3
4
  exports.ROLES_BUILDER_TOKEN = '__roles_builder__';
@@ -1,8 +1,15 @@
1
1
  "use strict";
2
- function __export(m) {
3
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
4
- }
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
+ };
5
12
  Object.defineProperty(exports, "__esModule", { value: true });
6
- __export(require("./inject-roles-builder.decorator"));
7
- __export(require("./use-roles.decorator"));
8
- __export(require("./user-roles.decorators"));
13
+ __exportStar(require("./inject-roles-builder.decorator"), exports);
14
+ __exportStar(require("./use-roles.decorator"), exports);
15
+ __exportStar(require("./user-roles.decorators"), exports);
@@ -1,4 +1,4 @@
1
1
  /**
2
2
  * Get access to the underlying `RolesBuilder` Object
3
3
  */
4
- export declare const InjectRolesBuilder: () => (target: Object, key: string | symbol, index?: number) => void;
4
+ export declare const InjectRolesBuilder: () => (target: object, key: string | symbol, index?: number) => void;
@@ -1,8 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InjectRolesBuilder = void 0;
3
4
  const common_1 = require("@nestjs/common");
4
5
  const constants_1 = require("../constants");
5
6
  /**
6
7
  * Get access to the underlying `RolesBuilder` Object
7
8
  */
8
- exports.InjectRolesBuilder = () => common_1.Inject(constants_1.ROLES_BUILDER_TOKEN);
9
+ const InjectRolesBuilder = () => (0, common_1.Inject)(constants_1.ROLES_BUILDER_TOKEN);
10
+ exports.InjectRolesBuilder = InjectRolesBuilder;
@@ -1,6 +1,6 @@
1
1
  import { Role } from '../role.interface';
2
2
  /**
3
3
  * Define an access information required for this route.
4
- * Notic that all Roles must be satisfied/Passed
4
+ * Notice that all Roles must be satisfied/passed
5
5
  */
6
- export declare const UseRoles: (...roles: Role[]) => (target: object, key?: any, descriptor?: any) => any;
6
+ export declare const UseRoles: (...roles: Role[]) => import("@nestjs/common").CustomDecorator<string>;
@@ -1,8 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UseRoles = void 0;
3
4
  const common_1 = require("@nestjs/common");
4
5
  /**
5
6
  * Define an access information required for this route.
6
- * Notic that all Roles must be satisfied/Passed
7
+ * Notice that all Roles must be satisfied/passed
7
8
  */
8
- exports.UseRoles = (...roles) => common_1.SetMetadata('roles', roles);
9
+ const UseRoles = (...roles) => (0, common_1.SetMetadata)('roles', roles);
10
+ exports.UseRoles = UseRoles;
@@ -2,6 +2,6 @@
2
2
  * Access the user roles from the request object i.e `req.user.roles`.
3
3
  *
4
4
  * You can pass an optional property key to the decorator to get it from the user object
5
- * e.g `@UserRoles('premissions')` will return the `req.user.premissions` instead.
5
+ * e.g `@UserRoles('permissions')` will return the `req.user.permissions` instead.
6
6
  */
7
- export declare const UserRoles: (...dataOrPipes: any[]) => ParameterDecorator;
7
+ export declare const UserRoles: (...dataOrPipes: (string | import("@nestjs/common").PipeTransform<any, any> | import("@nestjs/common").Type<import("@nestjs/common").PipeTransform<any, any>>)[]) => ParameterDecorator;
@@ -1,12 +1,38 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UserRoles = void 0;
3
4
  const common_1 = require("@nestjs/common");
5
+ function userFactory(ctx) {
6
+ const contextType = ctx.getType();
7
+ if (contextType === 'http') {
8
+ // do something that is only important in the context of regular HTTP requests (REST)
9
+ const { user } = ctx.switchToHttp().getRequest();
10
+ return user;
11
+ }
12
+ else if (contextType === 'rpc') {
13
+ // do something that is only important in the context of Microservice requests
14
+ throw new Error('Rpc context is not implemented yet');
15
+ }
16
+ else if (contextType === 'ws') {
17
+ // do something that is only important in the context of Websockets requests
18
+ throw new Error('Websockets context is not implemented yet');
19
+ }
20
+ else if (ctx.getType() === 'graphql') {
21
+ // inline require here, since we don't want to require the graphql module in the pacakge.
22
+ const { GqlExecutionContext } = require('@nestjs/graphql');
23
+ // do something that is only important in the context of GraphQL requests
24
+ const gqlExecutionContext = GqlExecutionContext.create(ctx);
25
+ return gqlExecutionContext.getContext().req.user;
26
+ }
27
+ throw new Error('Invalid context');
28
+ }
4
29
  /**
5
30
  * Access the user roles from the request object i.e `req.user.roles`.
6
31
  *
7
32
  * You can pass an optional property key to the decorator to get it from the user object
8
- * e.g `@UserRoles('premissions')` will return the `req.user.premissions` instead.
33
+ * e.g `@UserRoles('permissions')` will return the `req.user.permissions` instead.
9
34
  */
10
- exports.UserRoles = common_1.createParamDecorator((data, req) => {
11
- return data ? req.user[data] : req.user.roles;
35
+ exports.UserRoles = (0, common_1.createParamDecorator)((data, ctx) => {
36
+ const user = userFactory(ctx);
37
+ return data ? user[data] : user.roles;
12
38
  });
@@ -0,0 +1,6 @@
1
+ import { RolesBuilder } from './roles-builder.class';
2
+ export declare class GrantsController {
3
+ private readonly roleBuilder;
4
+ constructor(roleBuilder: RolesBuilder);
5
+ getGrants(): any;
6
+ }
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.GrantsController = void 0;
16
+ const common_1 = require("@nestjs/common");
17
+ const inject_roles_builder_decorator_1 = require("./decorators/inject-roles-builder.decorator");
18
+ const roles_builder_class_1 = require("./roles-builder.class");
19
+ let GrantsController = class GrantsController {
20
+ constructor(roleBuilder) {
21
+ this.roleBuilder = roleBuilder;
22
+ }
23
+ getGrants() {
24
+ return this.roleBuilder.getGrants();
25
+ }
26
+ };
27
+ __decorate([
28
+ (0, common_1.Get)(),
29
+ __metadata("design:type", Function),
30
+ __metadata("design:paramtypes", []),
31
+ __metadata("design:returntype", void 0)
32
+ ], GrantsController.prototype, "getGrants", null);
33
+ GrantsController = __decorate([
34
+ (0, common_1.Controller)(),
35
+ __param(0, (0, inject_roles_builder_decorator_1.InjectRolesBuilder)()),
36
+ __metadata("design:paramtypes", [roles_builder_class_1.RolesBuilder])
37
+ ], GrantsController);
38
+ exports.GrantsController = GrantsController;
package/index.d.ts CHANGED
@@ -3,4 +3,5 @@ export * from './access-control.module';
3
3
  export * from './roles-builder.class';
4
4
  export * from './role.interface';
5
5
  export * from './access-control.guard';
6
+ export type { Access, IAccessInfo, Query, IQueryInfo, Permission, AccessControlError, } from 'accesscontrol';
6
7
  export { ROLES_BUILDER_TOKEN } from './constants';
package/index.js CHANGED
@@ -4,13 +4,22 @@
4
4
  * Licensed under the MIT License.
5
5
  * All rights reserved.
6
6
  *-------------------------------------------------------------*/
7
- function __export(m) {
8
- for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
9
- }
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
16
+ };
10
17
  Object.defineProperty(exports, "__esModule", { value: true });
11
- __export(require("./decorators"));
12
- __export(require("./access-control.module"));
13
- __export(require("./roles-builder.class"));
14
- __export(require("./access-control.guard"));
18
+ exports.ROLES_BUILDER_TOKEN = void 0;
19
+ __exportStar(require("./decorators"), exports);
20
+ __exportStar(require("./access-control.module"), exports);
21
+ __exportStar(require("./roles-builder.class"), exports);
22
+ __exportStar(require("./role.interface"), exports);
23
+ __exportStar(require("./access-control.guard"), exports);
15
24
  var constants_1 = require("./constants");
16
- exports.ROLES_BUILDER_TOKEN = constants_1.ROLES_BUILDER_TOKEN;
25
+ Object.defineProperty(exports, "ROLES_BUILDER_TOKEN", { enumerable: true, get: function () { return constants_1.ROLES_BUILDER_TOKEN; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nest-access-control",
3
- "version": "2.0.0",
3
+ "version": "2.0.4",
4
4
  "description": "Access Control Module For Nestjs Framework",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -13,39 +13,48 @@
13
13
  },
14
14
  "repository": {
15
15
  "type": "git",
16
- "url": "git+https://github.com/shekohex/nest-access-control.git"
16
+ "url": "git+https://github.com/nestjsx/nest-access-control.git"
17
17
  },
18
18
  "keywords": [
19
19
  "nestjs",
20
20
  "access",
21
21
  "roles",
22
- "premissions",
22
+ "permissions",
23
23
  "nestjs modules",
24
24
  "addons"
25
25
  ],
26
26
  "author": "Shady Khalifa <shekohex@gmail.com>",
27
27
  "license": "MIT",
28
28
  "devDependencies": {
29
- "@nestjs/common": "^6.0.1",
30
- "@nestjs/core": "^6.0.1",
31
- "@types/jest": "^22.2.3",
29
+ "@nestjs/common": "^7.6.18",
30
+ "@nestjs/core": "^7.6.18",
31
+ "@nestjs/testing": "^7.6.18",
32
+ "@types/jest": "^27.0.0",
32
33
  "@types/node": "^10.1.2",
33
34
  "coveralls": "^3.0.1",
34
35
  "gulp": "^4.0.0",
35
36
  "gulp-sequence": "^1.0.0",
36
- "gulp-typescript": "^4.0.2",
37
- "jest": "^22.4.4",
37
+ "gulp-typescript": "^5.0.1",
38
+ "jest": "^27.4.0",
39
+ "node-notifier": "^10.0.0",
38
40
  "reflect-metadata": "^0.1.12",
39
41
  "rxjs": "^6.0.0",
40
- "ts-jest": "^22.4.6",
41
- "ts-node": "^6.0.3",
42
- "typescript": "^3.2"
42
+ "ts-jest": "^27.1.0",
43
+ "ts-node": "^10.4.0",
44
+ "typescript": "^4.5"
43
45
  },
44
46
  "bugs": {
45
- "url": "https://github.com/shekohex/nest-access-control/issues"
47
+ "url": "https://github.com/nestjsx/nest-access-control/issues"
46
48
  },
47
- "homepage": "https://github.com/shekohex/nest-access-control#readme",
49
+ "homepage": "https://github.com/nestjsx/nest-access-control#readme",
48
50
  "dependencies": {
49
51
  "accesscontrol": "^2.2.1"
52
+ },
53
+ "peerDependencies": {
54
+ "@apollo/gateway": "^0.45.1",
55
+ "@nestjs/graphql": "^7.6.18",
56
+ "apollo-server-core": "^3.6.1",
57
+ "graphql": "15.0.0",
58
+ "ts-morph": "^13.0.2"
50
59
  }
51
60
  }
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RolesBuilder = void 0;
3
4
  const accesscontrol_1 = require("accesscontrol");
4
5
  /**
5
6
  * @class RolesBuilder