nest-access-control 2.0.2 → 2.0.3

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,168 +1,207 @@
1
- # Nest Access Control
2
-
3
- ![MIT](https://img.shields.io/cocoapods/l/AFNetworking.svg?style=flat-square)
4
- [![npm version](https://badge.fury.io/js/nest-access-control.svg)](https://badge.fury.io/js/nest-access-control)
5
- ![Open Source Love](https://badges.frapsoft.com/os/v1/open-source.svg?v=102)
6
- [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)
7
- [![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)](https://forthebadge.com)
8
- [![forthebadge](https://forthebadge.com/images/badges/uses-badges.svg)](https://forthebadge.com)
9
-
10
- #### A helper Module for building a Role and Attribute based Access Control System for Nestjs
11
-
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:
13
-
14
- This module is built on top of [onury's](https://github.com/onury) [accesscontrol](https://github.com/onury/accesscontrol) library
15
- here is some of it's Core Features
16
-
17
- - Chainable, friendly API.
18
- e.g. `ac.can(role).create(resource)`
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.
29
-
30
- #### What this Module Provide ?
31
-
32
- In this module you will have all these features out of the box, but in nest-ish way.
33
-
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.
37
-
38
- ## Installation
39
-
40
- - NPM:
41
-
42
- ```bash
43
- npm install nest-access-control --save
44
- ```
45
-
46
- - Yarn:
47
-
48
- ```bash
49
- yarn add nest-access-control
50
- ```
51
-
52
- ---
53
-
54
- #### Example
55
-
56
- > See example folder for the more code
57
-
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.
59
-
60
- 1. Let's first define our roles:
61
-
62
- To build our roles we will need the `RolesBuilder` class, it extends the `AccessControl` class from `accesscontrol` package.
63
-
64
- ```ts
65
- // app.roles.ts
66
-
67
- export enum AppRoles {
68
- USER_CREATE_ANY_VIDEO = 'USER_CREATE_ANY_VIDEO',
69
- ADMIN_UPDATE_OWN_VIDEO = 'ADMIN_UPDATE_OWN_VIDEO',
70
- }
71
-
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
- ```
84
-
85
- > Pro Tip :+1: : Keep all roles organized and in one file e,g: `app.roles.ts`
86
-
87
- 2. Next let's use `AccessControlModule` in our Root module:
88
-
89
- ```ts
90
- // app.module.ts
91
-
92
- import { roles } from './app.roles';
93
-
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
- ```ts
106
- // app.controller.ts
107
- ...
108
- @Controller()
109
- export class AppController {
110
- constructor(private readonly appService: AppService) {}
111
- @UseGuards(AuthGuard, ACGuard)
112
- @UseRoles({
113
- resource: 'video',
114
- action: 'read',
115
- possession: 'any',
116
- })
117
- @Get()
118
- root(@UserRoles() userRoles: any) {
119
- return this.appService.root(userRoles);
120
- }
121
- }
122
- ```
123
-
124
- So let's discuss what's going on !
125
-
126
- First we introduced two new decorators, actually they are three, but let's see what they can do:
127
-
128
- - `@UseRoles({ ... })`: this the most used decorator, it define what roles should user have to access this route.
129
- It may take one or more role, but keep in mind that all roles **must** be satisfied.
130
- 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`.
131
- 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) .
132
- > \*note: for those who are asking what ACGuard stands for, it of course stands for Access Control Guard :smile:
133
-
134
- * `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.
135
- The decorator is 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.
136
-
137
- * `@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)`.
138
-
139
- 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` ?
140
- Ok let's discuss the **LIMITATIONS**.
141
-
142
- #### Limitations
143
-
144
- First of all, this module built with some assumptions
145
-
146
- 1. The user object will be exist in `req.user`
147
- 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)
148
- 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.
149
-
150
- 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.
151
-
152
- ## CHANGELOG
153
-
154
- See [CHANGELOG](CHANGELOG.md) for more information.
155
-
156
- ## Contributing
157
-
158
- You are welcome with this project for contributing, just make a PR.
159
-
160
- ## Authors
161
-
162
- - **Shady Khalifa** - _Initial work_
163
-
164
- See also the list of [contributors](https://github.com/nestjsx/nest-access-control/contributors) who participated in this project.
165
-
166
- ## License
167
-
168
- This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details.
1
+ # Nest Access Control
2
+
3
+ ![MIT](https://img.shields.io/cocoapods/l/AFNetworking.svg?style=flat-square)
4
+ [![npm version](https://badge.fury.io/js/nest-access-control.svg)](https://badge.fury.io/js/nest-access-control)
5
+ ![Open Source Love](https://badges.frapsoft.com/os/v1/open-source.svg?v=102)
6
+ [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)
7
+ [![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)](https://forthebadge.com)
8
+ [![forthebadge](https://forthebadge.com/images/badges/uses-badges.svg)](https://forthebadge.com)
9
+
10
+ #### A helper Module for building a Role and Attribute based Access Control System for Nestjs
11
+
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:
13
+
14
+ This module is built on top of [onury's](https://github.com/onury) [accesscontrol](https://github.com/onury/accesscontrol) library
15
+ here is some of it's Core Features
16
+
17
+ - Chainable, friendly API.
18
+ e.g. `ac.can(role).create(resource)`
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.
29
+
30
+ #### What does this Module Provide?
31
+
32
+ In this module you will have all these features out of the box, but in nest-ish way.
33
+
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.
37
+
38
+ ## Installation
39
+
40
+ - NPM:
41
+
42
+ ```bash
43
+ npm install nest-access-control --save
44
+ ```
45
+
46
+ - Yarn:
47
+
48
+ ```bash
49
+ yarn add nest-access-control
50
+ ```
51
+
52
+ ---
53
+
54
+ #### Example
55
+
56
+ > See example folder for the more code
57
+
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.
59
+
60
+ 1. Let's first define our roles:
61
+
62
+ To build our roles we will need the `RolesBuilder` class, it extends the `AccessControl` class from `accesscontrol` package.
63
+
64
+ ```ts
65
+ // app.roles.ts
66
+
67
+ export enum AppRoles {
68
+ USER_CREATE_ANY_VIDEO = 'USER_CREATE_ANY_VIDEO',
69
+ ADMIN_UPDATE_OWN_VIDEO = 'ADMIN_UPDATE_OWN_VIDEO',
70
+ }
71
+
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
+ ```
84
+
85
+ > Pro Tip :+1: : Keep all roles organized and in one file e,g: `app.roles.ts`
86
+
87
+ 2. Next let's use `AccessControlModule` in our Root module:
88
+
89
+ ```ts
90
+ // app.module.ts
91
+
92
+ import { roles } from './app.roles';
93
+
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
+ }
123
+ ```
124
+
125
+ ### ForRootAsync
126
+
127
+ Injecting providers for a RoleBuilder Factory (using a database to populate roles)
128
+
129
+ ```ts
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
+
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 {}
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.
162
+
163
+ So let's discuss what's going on!
164
+
165
+ First we introduced two new decorators, actually they are three, but let's see what they can do:
166
+
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).
171
+ > \*note: for those who are asking what ACGuard stands for, it of course stands for Access Control Guard :smile:
172
+
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.
175
+
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)`.
177
+
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**.
180
+
181
+ #### Limitations
182
+
183
+ First of all, this module built with some assumptions
184
+
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.
188
+
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.
190
+
191
+ ## CHANGELOG
192
+
193
+ See [CHANGELOG](CHANGELOG.md) for more information.
194
+
195
+ ## Contributing
196
+
197
+ You are welcome with this project for contributing, just make a PR.
198
+
199
+ ## Authors
200
+
201
+ - **Shady Khalifa** - _Initial work_
202
+
203
+ See also the list of [contributors](https://github.com/nestjsx/nest-access-control/contributors) who participated in this project.
204
+
205
+ ## License
206
+
207
+ This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details.
@@ -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);
@@ -6,7 +6,7 @@ export declare class AccessControlModule {
6
6
  * Register a pre-defined roles
7
7
  * @param {RolesBuilder} roles A list containing the access grant
8
8
  * definitions. See the structure of this object in the examples.
9
- * @param {ACOptions} options A configurable options
9
+ * @param {ACOptions} options A list of configurable options (currently just one)
10
10
  */
11
11
  static forRoles(roles: RolesBuilder, options?: ACOptions): DynamicModule;
12
12
  static forRootAsync(options: {
@@ -7,6 +7,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  };
8
8
  var AccessControlModule_1;
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.AccessControlModule = void 0;
10
11
  const common_1 = require("@nestjs/common");
11
12
  const constants_1 = require("@nestjs/common/constants");
12
13
  const constants_2 = require("./constants");
@@ -16,7 +17,7 @@ let AccessControlModule = AccessControlModule_1 = class AccessControlModule {
16
17
  * Register a pre-defined roles
17
18
  * @param {RolesBuilder} roles A list containing the access grant
18
19
  * definitions. See the structure of this object in the examples.
19
- * @param {ACOptions} options A configurable options
20
+ * @param {ACOptions} options A list of configurable options (currently just one)
20
21
  */
21
22
  static forRoles(roles, options) {
22
23
  let controllers = [];
@@ -66,7 +67,7 @@ let AccessControlModule = AccessControlModule_1 = class AccessControlModule {
66
67
  }
67
68
  };
68
69
  AccessControlModule = AccessControlModule_1 = __decorate([
69
- common_1.Global(),
70
- common_1.Module({})
70
+ (0, common_1.Global)(),
71
+ (0, common_1.Module)({})
71
72
  ], AccessControlModule);
72
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;
@@ -3,4 +3,4 @@ import { Role } from '../role.interface';
3
3
  * Define an access information required for this route.
4
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
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;
@@ -4,4 +4,4 @@
4
4
  * You can pass an optional property key to the decorator to get it from the user object
5
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,13 +1,37 @@
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
+ const graphql_1 = require("@nestjs/graphql");
6
+ function userFactory(ctx) {
7
+ const contextType = ctx.getType();
8
+ if (contextType === 'http') {
9
+ // do something that is only important in the context of regular HTTP requests (REST)
10
+ const { user } = ctx.switchToHttp().getRequest();
11
+ return user;
12
+ }
13
+ else if (contextType === 'rpc') {
14
+ // do something that is only important in the context of Microservice requests
15
+ throw new Error('Rpc context is not implemented yet');
16
+ }
17
+ else if (contextType === 'ws') {
18
+ // do something that is only important in the context of Websockets requests
19
+ throw new Error('Websockets context is not implemented yet');
20
+ }
21
+ else if (ctx.getType() === 'graphql') {
22
+ // do something that is only important in the context of GraphQL requests
23
+ const gqlExecutionContext = graphql_1.GqlExecutionContext.create(ctx);
24
+ return gqlExecutionContext.getContext().req.user;
25
+ }
26
+ throw new Error('Invalid context');
27
+ }
4
28
  /**
5
29
  * Access the user roles from the request object i.e `req.user.roles`.
6
30
  *
7
31
  * You can pass an optional property key to the decorator to get it from the user object
8
32
  * e.g `@UserRoles('permissions')` will return the `req.user.permissions` instead.
9
33
  */
10
- exports.UserRoles = common_1.createParamDecorator((data, ctx) => {
11
- const request = ctx.switchToHttp().getRequest();
12
- return data ? request.user[data] : request.user.roles;
34
+ exports.UserRoles = (0, common_1.createParamDecorator)((data, ctx) => {
35
+ const user = userFactory(ctx);
36
+ return data ? user[data] : user.roles;
13
37
  });
@@ -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.GrantsController = void 0;
15
16
  const common_1 = require("@nestjs/common");
16
17
  const inject_roles_builder_decorator_1 = require("./decorators/inject-roles-builder.decorator");
17
18
  const roles_builder_class_1 = require("./roles-builder.class");
@@ -24,14 +25,14 @@ let GrantsController = class GrantsController {
24
25
  }
25
26
  };
26
27
  __decorate([
27
- common_1.Get(),
28
+ (0, common_1.Get)(),
28
29
  __metadata("design:type", Function),
29
30
  __metadata("design:paramtypes", []),
30
31
  __metadata("design:returntype", void 0)
31
32
  ], GrantsController.prototype, "getGrants", null);
32
33
  GrantsController = __decorate([
33
- common_1.Controller(),
34
- __param(0, inject_roles_builder_decorator_1.InjectRolesBuilder()),
34
+ (0, common_1.Controller)(),
35
+ __param(0, (0, inject_roles_builder_decorator_1.InjectRolesBuilder)()),
35
36
  __metadata("design:paramtypes", [roles_builder_class_1.RolesBuilder])
36
37
  ], GrantsController);
37
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,52 +1,55 @@
1
- {
2
- "name": "nest-access-control",
3
- "version": "2.0.2",
4
- "description": "Access Control Module For Nestjs Framework",
5
- "main": "index.js",
6
- "scripts": {
7
- "test": "jest --notify --config=jest.json",
8
- "test:watch": "jest --watch --config=jest.json",
9
- "test:coverage": "jest --config=jest.json --coverage --coverageDirectory=coverage",
10
- "build": "gulp build && gulp move",
11
- "build:lib": "gulp build --dist lib && cp -rf package.json lib && cp -rf README.md lib",
12
- "npm:publish": "cd lib && npm publish"
13
- },
14
- "repository": {
15
- "type": "git",
16
- "url": "git+https://github.com/nestjsx/nest-access-control.git"
17
- },
18
- "keywords": [
19
- "nestjs",
20
- "access",
21
- "roles",
22
- "permissions",
23
- "nestjs modules",
24
- "addons"
25
- ],
26
- "author": "Shady Khalifa <shekohex@gmail.com>",
27
- "license": "MIT",
28
- "devDependencies": {
29
- "@nestjs/common": "^6.0.1",
30
- "@nestjs/core": "^6.0.1",
31
- "@nestjs/testing": "^6.1.1",
32
- "@types/jest": "^24.0.12",
33
- "@types/node": "^10.1.2",
34
- "coveralls": "^3.0.1",
35
- "gulp": "^4.0.0",
36
- "gulp-sequence": "^1.0.0",
37
- "gulp-typescript": "^4.0.2",
38
- "jest": "^24.8.0",
39
- "reflect-metadata": "^0.1.12",
40
- "rxjs": "^6.0.0",
41
- "ts-jest": "^24.0.2",
42
- "ts-node": "^6.0.3",
43
- "typescript": "^3.2"
44
- },
45
- "bugs": {
46
- "url": "https://github.com/nestjsx/nest-access-control/issues"
47
- },
48
- "homepage": "https://github.com/nestjsx/nest-access-control#readme",
49
- "dependencies": {
50
- "accesscontrol": "^2.2.1"
51
- }
52
- }
1
+ {
2
+ "name": "nest-access-control",
3
+ "version": "2.0.3",
4
+ "description": "Access Control Module For Nestjs Framework",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "jest --notify --config=jest.json",
8
+ "test:watch": "jest --watch --config=jest.json",
9
+ "test:coverage": "jest --config=jest.json --coverage --coverageDirectory=coverage",
10
+ "build": "gulp build && gulp move",
11
+ "build:lib": "gulp build --dist lib && cp -rf package.json lib && cp -rf README.md lib",
12
+ "npm:publish": "cd lib && npm publish"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/nestjsx/nest-access-control.git"
17
+ },
18
+ "keywords": [
19
+ "nestjs",
20
+ "access",
21
+ "roles",
22
+ "permissions",
23
+ "nestjs modules",
24
+ "addons"
25
+ ],
26
+ "author": "Shady Khalifa <shekohex@gmail.com>",
27
+ "license": "MIT",
28
+ "devDependencies": {
29
+ "@nestjs/common": "^7.6.18",
30
+ "@nestjs/core": "^7.6.18",
31
+ "@nestjs/graphql": "^7.6.18",
32
+ "@nestjs/testing": "^7.6.18",
33
+ "@types/jest": "^27.0.0",
34
+ "@types/node": "^10.1.2",
35
+ "coveralls": "^3.0.1",
36
+ "graphql": "15.0.0",
37
+ "gulp": "^4.0.0",
38
+ "gulp-sequence": "^1.0.0",
39
+ "gulp-typescript": "^5.0.1",
40
+ "jest": "^27.4.0",
41
+ "node-notifier": "^10.0.0",
42
+ "reflect-metadata": "^0.1.12",
43
+ "rxjs": "^6.0.0",
44
+ "ts-jest": "^27.1.0",
45
+ "ts-node": "^10.4.0",
46
+ "typescript": "^4.5"
47
+ },
48
+ "bugs": {
49
+ "url": "https://github.com/nestjsx/nest-access-control/issues"
50
+ },
51
+ "homepage": "https://github.com/nestjsx/nest-access-control#readme",
52
+ "dependencies": {
53
+ "accesscontrol": "^2.2.1"
54
+ }
55
+ }
@@ -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