@iquadras/shared-guards 0.0.1

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.
Files changed (68) hide show
  1. package/.gitattributes +2 -0
  2. package/LICENSE +24 -0
  3. package/README.md +201 -0
  4. package/dist/adonis/index.d.ts +7 -0
  5. package/dist/adonis/index.js +34 -0
  6. package/dist/adonis/index.js.map +1 -0
  7. package/dist/adonis/jwt.d.ts +2 -0
  8. package/dist/adonis/jwt.js +46 -0
  9. package/dist/adonis/jwt.js.map +1 -0
  10. package/dist/core/constants.d.ts +7 -0
  11. package/dist/core/constants.js +10 -0
  12. package/dist/core/constants.js.map +1 -0
  13. package/dist/core/index.d.ts +4 -0
  14. package/dist/core/index.js +21 -0
  15. package/dist/core/index.js.map +1 -0
  16. package/dist/core/jwt.d.ts +2 -0
  17. package/dist/core/jwt.js +17 -0
  18. package/dist/core/jwt.js.map +1 -0
  19. package/dist/core/permissions.d.ts +4 -0
  20. package/dist/core/permissions.js +28 -0
  21. package/dist/core/permissions.js.map +1 -0
  22. package/dist/core/types.d.ts +19 -0
  23. package/dist/core/types.js +3 -0
  24. package/dist/core/types.js.map +1 -0
  25. package/dist/index.d.ts +1 -0
  26. package/dist/index.js +18 -0
  27. package/dist/index.js.map +1 -0
  28. package/dist/nestjs/constants.d.ts +3 -0
  29. package/dist/nestjs/constants.js +7 -0
  30. package/dist/nestjs/constants.js.map +1 -0
  31. package/dist/nestjs/decorators/auth.decorator.d.ts +1 -0
  32. package/dist/nestjs/decorators/auth.decorator.js +8 -0
  33. package/dist/nestjs/decorators/auth.decorator.js.map +1 -0
  34. package/dist/nestjs/decorators/get-user.decorator.d.ts +2 -0
  35. package/dist/nestjs/decorators/get-user.decorator.js +12 -0
  36. package/dist/nestjs/decorators/get-user.decorator.js.map +1 -0
  37. package/dist/nestjs/decorators/permissions.decorator.d.ts +9 -0
  38. package/dist/nestjs/decorators/permissions.decorator.js +6 -0
  39. package/dist/nestjs/decorators/permissions.decorator.js.map +1 -0
  40. package/dist/nestjs/decorators/require-module.decorator.d.ts +6 -0
  41. package/dist/nestjs/decorators/require-module.decorator.js +11 -0
  42. package/dist/nestjs/decorators/require-module.decorator.js.map +1 -0
  43. package/dist/nestjs/decorators/require-organization-admin.decorator.d.ts +5 -0
  44. package/dist/nestjs/decorators/require-organization-admin.decorator.js +10 -0
  45. package/dist/nestjs/decorators/require-organization-admin.decorator.js.map +1 -0
  46. package/dist/nestjs/decorators/require-super-admin.decorator.d.ts +1 -0
  47. package/dist/nestjs/decorators/require-super-admin.decorator.js +7 -0
  48. package/dist/nestjs/decorators/require-super-admin.decorator.js.map +1 -0
  49. package/dist/nestjs/guards/jwt-auth.guard.d.ts +10 -0
  50. package/dist/nestjs/guards/jwt-auth.guard.js +69 -0
  51. package/dist/nestjs/guards/jwt-auth.guard.js.map +1 -0
  52. package/dist/nestjs/guards/permissions.guard.d.ts +8 -0
  53. package/dist/nestjs/guards/permissions.guard.js +98 -0
  54. package/dist/nestjs/guards/permissions.guard.js.map +1 -0
  55. package/dist/nestjs/index.d.ts +15 -0
  56. package/dist/nestjs/index.js +29 -0
  57. package/dist/nestjs/index.js.map +1 -0
  58. package/dist/nestjs/module/shared-guards.module.d.ts +4 -0
  59. package/dist/nestjs/module/shared-guards.module.js +44 -0
  60. package/dist/nestjs/module/shared-guards.module.js.map +1 -0
  61. package/dist/nestjs/utils/logger.util.d.ts +2 -0
  62. package/dist/nestjs/utils/logger.util.js +6 -0
  63. package/dist/nestjs/utils/logger.util.js.map +1 -0
  64. package/dist/react/index.d.ts +5 -0
  65. package/dist/react/index.js +24 -0
  66. package/dist/react/index.js.map +1 -0
  67. package/dist/tsconfig.tsbuildinfo +1 -0
  68. package/package.json +74 -0
package/.gitattributes ADDED
@@ -0,0 +1,2 @@
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
package/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ Copyright (c) iQuadras. All Rights Reserved.
2
+
3
+ Este software e seu código-fonte são protegidos por direitos autorais e pertencem exclusivamente à iQuadras.
4
+
5
+ 1. Direitos reservados
6
+ Todo o direito de propriedade intelectual sobre o software permanece com a iQuadras. Nenhum direito de uso é concedido além do expressamente autorizado por contrato ou por escrito.
7
+
8
+ 2. Uso permitido
9
+ • Em servidores da iQuadras.
10
+ • Em ambiente local ou em servidor do cliente, quando houver contrato ou autorização escrita da iQuadras.
11
+
12
+ 3. Restrições
13
+ É proibido, sem autorização prévia por escrito: reproduzir, distribuir, modificar, sublicenciar, fazer engenharia reversa ou utilizar o software para fins não autorizados. O código e as informações técnicas são confidenciais.
14
+
15
+ 4. Sem licenças implícitas
16
+ Nada neste documento concede direitos a terceiros ou implica qualquer relação contratual além do acordado por escrito com a iQuadras.
17
+
18
+ 5. Sem garantias
19
+ O software é fornecido "como está" (as is), sem garantias de qualquer tipo, expressas ou implícitas, incluindo comercialização ou adequação a um propósito específico.
20
+
21
+ 6. Limitação de responsabilidade
22
+ Em nenhuma hipótese a iQuadras será responsável por danos diretos, indiretos, incidentais ou consequenciais decorrentes do uso ou da impossibilidade de uso do software.
23
+
24
+ Contato para licenciamento: canais oficiais da iQuadras.
package/README.md ADDED
@@ -0,0 +1,201 @@
1
+ # @iquadras/shared-guards
2
+
3
+ Guards compartilhados para autenticação e autorização JWT no ecossistema iQuadras.
4
+
5
+ ## Geral
6
+
7
+ ### Hierarquia de permissões
8
+
9
+ 1. **superAdmin** — Acesso total ao sistema (admin iQuadras)
10
+ 2. **isAdmin na organização** — Acesso total naquela organização (dono do centro)
11
+ 3. **Módulos** — Acesso apenas aos módulos em `permissions[].modules`
12
+
13
+ ### Módulos disponíveis
14
+
15
+ | Módulo | Descrição |
16
+ |--------|-----------|
17
+ | `MODULES.BOOKING` | Reserva de quadras |
18
+ | `MODULES.CLASSES` | Aulas |
19
+ | `MODULES.REPLAY` | Replay |
20
+
21
+ ### Funções de permissão (core)
22
+
23
+ - `isSuperAdmin(user)` — É super admin?
24
+ - `isOrgAdmin(user, organizationId)` — É admin da org ou super admin?
25
+ - `hasModuleAccess(user, organizationId, module)` — Tem acesso ao módulo na org?
26
+
27
+ ### Header do JWT
28
+
29
+ O token deve ser enviado em **`x-auth-access-token`**.
30
+
31
+ ---
32
+
33
+ ## NestJS
34
+
35
+ ### Instalação
36
+
37
+ ```bash
38
+ npm install @iquadras/shared-guards @nestjs/jwt
39
+ ```
40
+
41
+ ### Configuração
42
+
43
+ **1.** Defina `JWT_SECRET` no `.env`
44
+
45
+ **2.** Importe o módulo no `AppModule`:
46
+
47
+ ```typescript
48
+ import { SharedGuardsModule } from '@iquadras/shared-guards';
49
+
50
+ @Module({
51
+ imports: [SharedGuardsModule.forRoot()],
52
+ })
53
+ export class AppModule {}
54
+ ```
55
+
56
+ **3.** Remova o `JwtModule` de outros módulos — o `SharedGuardsModule` já registra globalmente.
57
+
58
+ **4.** (Opcional) Logs em `main.ts`:
59
+
60
+ ```typescript
61
+ const app = await NestFactory.create(AppModule, {
62
+ logger: ['error', 'warn', 'log', 'debug'],
63
+ });
64
+ ```
65
+
66
+ ### Uso
67
+
68
+ Rotas são públicas por padrão. Use decorators para proteger.
69
+
70
+ | Decorator | Quem tem acesso |
71
+ |-----------|-----------------|
72
+ | `@RequireAnyAuth()` | Qualquer usuário autenticado |
73
+ | `@RequireSuperAdminAuth()` | Apenas super admins |
74
+ | `@RequireOrganizationAdminAuth({ organizationIdSource })` | Super admins ou admin da organização |
75
+ | `@RequireModuleAuth(module, { organizationIdSource })` | Super admin, admin da org ou usuário com o módulo |
76
+
77
+ **OrganizationId:** `@RequireOrganizationAdminAuth` e `@RequireModuleAuth` exigem `organizationIdSource` — informe sempre de onde virá o ID (params, query ou body):
78
+
79
+ ```typescript
80
+ import { RequireAnyAuth, GetUser, RequireModuleAuth, RequireOrganizationAdminAuth, RequireSuperAdminAuth, MODULES } from '@iquadras/shared-guards';
81
+
82
+ @Controller('organizations/:organizationId/reservas')
83
+ export class ReservasController {
84
+ @Get(':id') findOne(@Param('id') id: string) { /* público */ }
85
+
86
+ // organizationId no path (params)
87
+ @Post() @RequireModuleAuth(MODULES.BOOKING, { organizationIdSource: 'params.organizationId' }) create(@Body() dto: CreateReservaDto) { }
88
+
89
+ // organizationId no body
90
+ @Post('outra-rota') @RequireModuleAuth(MODULES.BOOKING, { organizationIdSource: 'body.organizationId' }) createFromBody(@Body() dto: Dto) { }
91
+
92
+ // organizationId na query
93
+ @Get() @RequireOrganizationAdminAuth({ organizationIdSource: 'query.orgId' }) list(@Query() q: { orgId: string }) { }
94
+
95
+ @Patch(':id/estornar') @RequireOrganizationAdminAuth({ organizationIdSource: 'params.organizationId' }) estornar(@Param('id') id: string) { }
96
+
97
+ @Delete(':id') @RequireSuperAdminAuth() remove(@Param('id') id: string) { }
98
+ }
99
+ ```
100
+
101
+ Paths comuns: `params.organizationId`, `params.orgId`, `query.organizationId`, `query.orgId`, `body.organizationId`, `body.orgId`. Pode passar array para tentar na ordem: `{ organizationIdSource: ['body.organizationId', 'query.orgId'] }`.
102
+
103
+ **Quando o organizationId é descoberto no processo** (ex: buscando um recurso pelo id e obtendo a org dele), valide manualmente no controller com as funções do core:
104
+
105
+ ```typescript
106
+ import { isOrgAdmin, hasModuleAccess, GetUser } from '@iquadras/shared-guards';
107
+ import type { JwtPayload } from '@iquadras/shared-guards';
108
+
109
+ // No controller, após buscar o recurso:
110
+ const reserva = await this.reservasService.findOne(id);
111
+ const user = request.user as JwtPayload;
112
+ if (!isOrgAdmin(user, reserva.organizationId)) {
113
+ throw new ForbiddenException('Sem permissão');
114
+ }
115
+ ```
116
+
117
+ ---
118
+
119
+ ## Adonis
120
+
121
+ ### Instalação
122
+
123
+ ```bash
124
+ npm install @iquadras/shared-guards
125
+ ```
126
+
127
+ ### Uso
128
+
129
+ As funções recebem o token e fazem a validação internamente:
130
+
131
+ ```typescript
132
+ import {
133
+ getTokenFromHeader,
134
+ isSuperAdmin,
135
+ isOrgAdmin,
136
+ hasModuleAccess,
137
+ MODULES,
138
+ AUTH_ACCESS_TOKEN_HEADER,
139
+ } from '@iquadras/shared-guards/adonis';
140
+
141
+ // Exemplo no middleware
142
+ export default class RequireSuperAdminMiddleware {
143
+ async handle(ctx: HttpContext, next: NextFn) {
144
+ const token = getTokenFromHeader(ctx.request.header(AUTH_ACCESS_TOKEN_HEADER));
145
+ if (!token) return ctx.response.unauthorized({ message: 'Token não informado' });
146
+
147
+ if (!(await isSuperAdmin(token))) {
148
+ return ctx.response.forbidden({ message: 'Acesso negado' });
149
+ }
150
+ await next();
151
+ }
152
+ }
153
+ ```
154
+
155
+ ---
156
+
157
+ ## React
158
+
159
+ ### Instalação
160
+
161
+ ```bash
162
+ npm install @iquadras/shared-guards
163
+ ```
164
+
165
+ ### Uso
166
+
167
+ As funções recebem o token e fazem o decode internamente (sem validar — no client não temos o secret):
168
+
169
+ ```typescript
170
+ import {
171
+ isSuperAdmin,
172
+ isOrgAdmin,
173
+ hasModuleAccess,
174
+ MODULES,
175
+ } from '@iquadras/shared-guards/react';
176
+
177
+ // No componente — token do localStorage, contexto de auth, etc.
178
+ const token = getTokenFromStorage(); // sua função
179
+
180
+ const canCreate = hasModuleAccess(token, orgId, MODULES.BOOKING);
181
+ const isAdmin = isOrgAdmin(token, orgId);
182
+ const isSuper = isSuperAdmin(token);
183
+ ```
184
+
185
+ > **Atenção:** O decode no React não valida a assinatura. Use apenas para UI (exibir/esconder elementos). A validação real ocorre na API.
186
+
187
+ ---
188
+
189
+ ## Core
190
+
191
+ Para usar apenas a lógica (sem framework):
192
+
193
+ ```typescript
194
+ import {
195
+ isSuperAdmin,
196
+ isOrgAdmin,
197
+ hasModuleAccess,
198
+ decodeToken,
199
+ MODULES,
200
+ } from '@iquadras/shared-guards/core';
201
+ ```
@@ -0,0 +1,7 @@
1
+ export { MODULES, AUTH_ACCESS_TOKEN_HEADER } from '../core';
2
+ export { verifyToken } from './jwt';
3
+ export type { JwtPayload, OrganizationPermission, ModuleType } from '../core';
4
+ export declare function getTokenFromHeader(header: string | string[] | undefined): string | undefined;
5
+ export declare function isSuperAdmin(token: string): Promise<boolean>;
6
+ export declare function isOrgAdmin(token: string, organizationId: string): Promise<boolean>;
7
+ export declare function hasModuleAccess(token: string, organizationId: string, module: string): Promise<boolean>;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.verifyToken = exports.AUTH_ACCESS_TOKEN_HEADER = exports.MODULES = void 0;
4
+ exports.getTokenFromHeader = getTokenFromHeader;
5
+ exports.isSuperAdmin = isSuperAdmin;
6
+ exports.isOrgAdmin = isOrgAdmin;
7
+ exports.hasModuleAccess = hasModuleAccess;
8
+ const permissions_1 = require("../core/permissions");
9
+ const jwt_1 = require("./jwt");
10
+ var core_1 = require("../core");
11
+ Object.defineProperty(exports, "MODULES", { enumerable: true, get: function () { return core_1.MODULES; } });
12
+ Object.defineProperty(exports, "AUTH_ACCESS_TOKEN_HEADER", { enumerable: true, get: function () { return core_1.AUTH_ACCESS_TOKEN_HEADER; } });
13
+ var jwt_2 = require("./jwt");
14
+ Object.defineProperty(exports, "verifyToken", { enumerable: true, get: function () { return jwt_2.verifyToken; } });
15
+ function getTokenFromHeader(header) {
16
+ if (typeof header === 'string')
17
+ return header;
18
+ if (Array.isArray(header) && header.length > 0)
19
+ return header[0];
20
+ return undefined;
21
+ }
22
+ async function isSuperAdmin(token) {
23
+ const user = await (0, jwt_1.verifyToken)(token);
24
+ return (0, permissions_1.isSuperAdmin)(user);
25
+ }
26
+ async function isOrgAdmin(token, organizationId) {
27
+ const user = await (0, jwt_1.verifyToken)(token);
28
+ return (0, permissions_1.isOrgAdmin)(user, organizationId);
29
+ }
30
+ async function hasModuleAccess(token, organizationId, module) {
31
+ const user = await (0, jwt_1.verifyToken)(token);
32
+ return (0, permissions_1.hasModuleAccess)(user, organizationId, module);
33
+ }
34
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/adonis/index.ts"],"names":[],"mappings":";;;AAmBA,gDAMC;AAED,oCAGC;AAED,gCAMC;AAED,0CAOC;AA3CD,qDAI6B;AAE7B,+BAAoC;AAEpC,gCAA4D;AAAnD,+FAAA,OAAO,OAAA;AAAE,gHAAA,wBAAwB,OAAA;AAC1C,6BAAoC;AAA3B,kGAAA,WAAW,OAAA;AAMpB,SAAgB,kBAAkB,CAChC,MAAqC;IAErC,IAAI,OAAO,MAAM,KAAK,QAAQ;QAAE,OAAO,MAAM,CAAC;IAC9C,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC;IACjE,OAAO,SAAS,CAAC;AACnB,CAAC;AAEM,KAAK,UAAU,YAAY,CAAC,KAAa;IAC9C,MAAM,IAAI,GAAG,MAAM,IAAA,iBAAW,EAAC,KAAK,CAAC,CAAC;IACtC,OAAO,IAAA,0BAAgB,EAAC,IAAI,CAAC,CAAC;AAChC,CAAC;AAEM,KAAK,UAAU,UAAU,CAC9B,KAAa,EACb,cAAsB;IAEtB,MAAM,IAAI,GAAG,MAAM,IAAA,iBAAW,EAAC,KAAK,CAAC,CAAC;IACtC,OAAO,IAAA,wBAAc,EAAC,IAAI,EAAE,cAAc,CAAC,CAAC;AAC9C,CAAC;AAEM,KAAK,UAAU,eAAe,CACnC,KAAa,EACb,cAAsB,EACtB,MAAc;IAEd,MAAM,IAAI,GAAG,MAAM,IAAA,iBAAW,EAAC,KAAK,CAAC,CAAC;IACtC,OAAO,IAAA,6BAAmB,EAAC,IAAI,EAAE,cAAc,EAAE,MAAM,CAAC,CAAC;AAC3D,CAAC"}
@@ -0,0 +1,2 @@
1
+ import type { JwtPayload } from '../core/types';
2
+ export declare function verifyToken(token: string, secret?: string): Promise<JwtPayload>;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.verifyToken = verifyToken;
37
+ const jwt = __importStar(require("jsonwebtoken"));
38
+ async function verifyToken(token, secret) {
39
+ const key = secret ?? process.env.JWT_SECRET;
40
+ if (!key) {
41
+ throw new Error('JWT_SECRET deve ser definido na variável de ambiente');
42
+ }
43
+ const payload = jwt.verify(token, key);
44
+ return payload;
45
+ }
46
+ //# sourceMappingURL=jwt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwt.js","sourceRoot":"","sources":["../../src/adonis/jwt.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,kCAUC;AAjBD,kDAAoC;AAO7B,KAAK,UAAU,WAAW,CAC/B,KAAa,EACb,MAAe;IAEf,MAAM,GAAG,GAAG,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;IAC7C,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IACD,MAAM,OAAO,GAAG,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,CAAe,CAAC;IACrD,OAAO,OAAO,CAAC;AACjB,CAAC"}
@@ -0,0 +1,7 @@
1
+ export declare const AUTH_ACCESS_TOKEN_HEADER = "x-auth-access-token";
2
+ export declare const MODULES: {
3
+ readonly BOOKING: "BOOKING";
4
+ readonly CLASSES: "CLASSES";
5
+ readonly REPLAY: "REPLAY";
6
+ };
7
+ export type ModuleType = (typeof MODULES)[keyof typeof MODULES];
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MODULES = exports.AUTH_ACCESS_TOKEN_HEADER = void 0;
4
+ exports.AUTH_ACCESS_TOKEN_HEADER = 'x-auth-access-token';
5
+ exports.MODULES = {
6
+ BOOKING: 'BOOKING',
7
+ CLASSES: 'CLASSES',
8
+ REPLAY: 'REPLAY',
9
+ };
10
+ //# sourceMappingURL=constants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/core/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,wBAAwB,GAAG,qBAAqB,CAAC;AAEjD,QAAA,OAAO,GAAG;IACrB,OAAO,EAAE,SAAS;IAClB,OAAO,EAAE,SAAS;IAClB,MAAM,EAAE,QAAQ;CACR,CAAC"}
@@ -0,0 +1,4 @@
1
+ export * from './types';
2
+ export * from './constants';
3
+ export * from './permissions';
4
+ export * from './jwt';
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./types"), exports);
18
+ __exportStar(require("./constants"), exports);
19
+ __exportStar(require("./permissions"), exports);
20
+ __exportStar(require("./jwt"), exports);
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,0CAAwB;AACxB,8CAA4B;AAC5B,gDAA8B;AAC9B,wCAAsB"}
@@ -0,0 +1,2 @@
1
+ import type { JwtPayload } from './types';
2
+ export declare function decodeToken(token: string): JwtPayload;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decodeToken = decodeToken;
4
+ function decodeToken(token) {
5
+ const parts = token.split('.');
6
+ if (parts.length !== 3) {
7
+ throw new Error('Token JWT inválido');
8
+ }
9
+ const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
10
+ const pad = base64.length % 4;
11
+ const padded = pad ? base64 + '='.repeat(4 - pad) : base64;
12
+ const json = typeof atob !== 'undefined'
13
+ ? atob(padded)
14
+ : Buffer.from(padded, 'base64').toString('utf-8');
15
+ return JSON.parse(json);
16
+ }
17
+ //# sourceMappingURL=jwt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwt.js","sourceRoot":"","sources":["../../src/core/jwt.ts"],"names":[],"mappings":";;AAOA,kCAaC;AAbD,SAAgB,WAAW,CAAC,KAAa;IACvC,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC/B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;IACxC,CAAC;IACD,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;IAC9D,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;IAC9B,MAAM,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;IAC3D,MAAM,IAAI,GACR,OAAO,IAAI,KAAK,WAAW;QACzB,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC;QACd,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IACtD,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAe,CAAC;AACxC,CAAC"}
@@ -0,0 +1,4 @@
1
+ import type { JwtPayload } from './types';
2
+ export declare function isSuperAdmin(user: JwtPayload): boolean;
3
+ export declare function isOrgAdmin(user: JwtPayload, organizationId: string): boolean;
4
+ export declare function hasModuleAccess(user: JwtPayload, organizationId: string, module: string): boolean;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isSuperAdmin = isSuperAdmin;
4
+ exports.isOrgAdmin = isOrgAdmin;
5
+ exports.hasModuleAccess = hasModuleAccess;
6
+ function findOrgPermission(user, organizationId) {
7
+ return user.permissions?.find((p) => p.organizationId.toLowerCase() === organizationId.toLowerCase());
8
+ }
9
+ function isSuperAdmin(user) {
10
+ return user.superAdmin === true;
11
+ }
12
+ function isOrgAdmin(user, organizationId) {
13
+ if (user.superAdmin)
14
+ return true;
15
+ const perm = findOrgPermission(user, organizationId);
16
+ return perm?.isAdmin === true;
17
+ }
18
+ function hasModuleAccess(user, organizationId, module) {
19
+ if (user.superAdmin)
20
+ return true;
21
+ const perm = findOrgPermission(user, organizationId);
22
+ if (!perm)
23
+ return false;
24
+ if (perm.isAdmin)
25
+ return true;
26
+ return perm.modules.includes(module);
27
+ }
28
+ //# sourceMappingURL=permissions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"permissions.js","sourceRoot":"","sources":["../../src/core/permissions.ts"],"names":[],"mappings":";;AAWA,oCAEC;AAED,gCAIC;AAED,0CAUC;AA7BD,SAAS,iBAAiB,CACxB,IAAgB,EAChB,cAAsB;IAEtB,OAAO,IAAI,CAAC,WAAW,EAAE,IAAI,CAC3B,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,cAAc,CAAC,WAAW,EAAE,KAAK,cAAc,CAAC,WAAW,EAAE,CACvE,CAAC;AACJ,CAAC;AAED,SAAgB,YAAY,CAAC,IAAgB;IAC3C,OAAO,IAAI,CAAC,UAAU,KAAK,IAAI,CAAC;AAClC,CAAC;AAED,SAAgB,UAAU,CAAC,IAAgB,EAAE,cAAsB;IACjE,IAAI,IAAI,CAAC,UAAU;QAAE,OAAO,IAAI,CAAC;IACjC,MAAM,IAAI,GAAG,iBAAiB,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;IACrD,OAAO,IAAI,EAAE,OAAO,KAAK,IAAI,CAAC;AAChC,CAAC;AAED,SAAgB,eAAe,CAC7B,IAAgB,EAChB,cAAsB,EACtB,MAAc;IAEd,IAAI,IAAI,CAAC,UAAU;QAAE,OAAO,IAAI,CAAC;IACjC,MAAM,IAAI,GAAG,iBAAiB,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;IACrD,IAAI,CAAC,IAAI;QAAE,OAAO,KAAK,CAAC;IACxB,IAAI,IAAI,CAAC,OAAO;QAAE,OAAO,IAAI,CAAC;IAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AACvC,CAAC"}
@@ -0,0 +1,19 @@
1
+ export interface OrganizationPermission {
2
+ organizationId: string;
3
+ isAdmin: boolean;
4
+ modules: string[];
5
+ }
6
+ export interface JwtPayload {
7
+ sub: string;
8
+ email: string;
9
+ phone?: string;
10
+ name?: string;
11
+ documentType?: string;
12
+ document?: string;
13
+ avatar?: string;
14
+ isVerified?: boolean;
15
+ superAdmin: boolean;
16
+ permissions?: OrganizationPermission[];
17
+ iat?: number;
18
+ exp?: number;
19
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/core/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1 @@
1
+ export * from './nestjs';
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./nestjs"), exports);
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAOA,2CAAyB"}
@@ -0,0 +1,3 @@
1
+ import { AUTH_ACCESS_TOKEN_HEADER } from '../core/constants';
2
+ export { AUTH_ACCESS_TOKEN_HEADER };
3
+ export declare const REQUIRES_AUTH_KEY = "requiresAuth";
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REQUIRES_AUTH_KEY = exports.AUTH_ACCESS_TOKEN_HEADER = void 0;
4
+ const constants_1 = require("../core/constants");
5
+ Object.defineProperty(exports, "AUTH_ACCESS_TOKEN_HEADER", { enumerable: true, get: function () { return constants_1.AUTH_ACCESS_TOKEN_HEADER; } });
6
+ exports.REQUIRES_AUTH_KEY = 'requiresAuth';
7
+ //# sourceMappingURL=constants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/nestjs/constants.ts"],"names":[],"mappings":";;;AAAA,iDAA6D;AAEpD,yGAFA,oCAAwB,OAEA;AAEpB,QAAA,iBAAiB,GAAG,cAAc,CAAC"}
@@ -0,0 +1 @@
1
+ export declare const RequireAnyAuth: () => import("@nestjs/common").CustomDecorator<string>;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RequireAnyAuth = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ const constants_1 = require("../constants");
6
+ const RequireAnyAuth = () => (0, common_1.SetMetadata)(constants_1.REQUIRES_AUTH_KEY, true);
7
+ exports.RequireAnyAuth = RequireAnyAuth;
8
+ //# sourceMappingURL=auth.decorator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.decorator.js","sourceRoot":"","sources":["../../../src/nestjs/decorators/auth.decorator.ts"],"names":[],"mappings":";;;AAAA,2CAA6C;AAC7C,4CAAiD;AAE1C,MAAM,cAAc,GAAG,GAAG,EAAE,CAAC,IAAA,oBAAW,EAAC,6BAAiB,EAAE,IAAI,CAAC,CAAC;AAA5D,QAAA,cAAc,kBAA8C"}
@@ -0,0 +1,2 @@
1
+ import type { JwtPayload } from '../../core/types';
2
+ export declare const GetUser: (...dataOrPipes: (keyof JwtPayload | import("@nestjs/common").PipeTransform<any, any> | import("@nestjs/common").Type<import("@nestjs/common").PipeTransform<any, any>> | undefined)[]) => ParameterDecorator;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GetUser = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ exports.GetUser = (0, common_1.createParamDecorator)((data, ctx) => {
6
+ const request = ctx.switchToHttp().getRequest();
7
+ const user = request.user;
8
+ if (data)
9
+ return user?.[data];
10
+ return user;
11
+ });
12
+ //# sourceMappingURL=get-user.decorator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"get-user.decorator.js","sourceRoot":"","sources":["../../../src/nestjs/decorators/get-user.decorator.ts"],"names":[],"mappings":";;;AAAA,2CAAwE;AAG3D,QAAA,OAAO,GAAG,IAAA,6BAAoB,EACzC,CAAC,IAAkC,EAAE,GAAqB,EAAwB,EAAE;IAClF,MAAM,OAAO,GAAG,GAAG,CAAC,YAAY,EAAE,CAAC,UAAU,EAAwB,CAAC;IACtE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAC1B,IAAI,IAAI;QAAE,OAAO,IAAI,EAAE,CAAC,IAAI,CAAC,CAAC;IAC9B,OAAO,IAAI,CAAC;AACd,CAAC,CACF,CAAC"}
@@ -0,0 +1,9 @@
1
+ import type { ModuleType } from '../../core/constants';
2
+ export type PermissionType = 'SUPER_ADMIN_ONLY' | 'ORGANIZATION_ADMIN_ONLY' | 'MODULE_ACCESS';
3
+ export type OrganizationIdSource = string | string[];
4
+ export interface PermissionMetadata {
5
+ type: PermissionType;
6
+ module?: ModuleType;
7
+ organizationIdSource?: OrganizationIdSource;
8
+ }
9
+ export declare const Permission: import("@nestjs/core").ReflectableDecorator<PermissionMetadata, PermissionMetadata>;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Permission = void 0;
4
+ const core_1 = require("@nestjs/core");
5
+ exports.Permission = core_1.Reflector.createDecorator();
6
+ //# sourceMappingURL=permissions.decorator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"permissions.decorator.js","sourceRoot":"","sources":["../../../src/nestjs/decorators/permissions.decorator.ts"],"names":[],"mappings":";;;AAAA,uCAAyC;AAsB5B,QAAA,UAAU,GAAG,gBAAS,CAAC,eAAe,EAAsB,CAAC"}
@@ -0,0 +1,6 @@
1
+ import type { ModuleType } from '../../core/constants';
2
+ import type { OrganizationIdSource } from './permissions.decorator';
3
+ export interface RequireModuleAuthOptions {
4
+ organizationIdSource: OrganizationIdSource;
5
+ }
6
+ export declare const RequireModuleAuth: (module: ModuleType, options: RequireModuleAuthOptions) => import("@nestjs/common").CustomDecorator;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RequireModuleAuth = void 0;
4
+ const permissions_decorator_1 = require("./permissions.decorator");
5
+ const RequireModuleAuth = (module, options) => (0, permissions_decorator_1.Permission)({
6
+ type: 'MODULE_ACCESS',
7
+ module,
8
+ organizationIdSource: options.organizationIdSource,
9
+ });
10
+ exports.RequireModuleAuth = RequireModuleAuth;
11
+ //# sourceMappingURL=require-module.decorator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"require-module.decorator.js","sourceRoot":"","sources":["../../../src/nestjs/decorators/require-module.decorator.ts"],"names":[],"mappings":";;;AAAA,mEAAqD;AAS9C,MAAM,iBAAiB,GAAG,CAAC,MAAkB,EAAE,OAAiC,EAAE,EAAE,CACzF,IAAA,kCAAU,EAAC;IACT,IAAI,EAAE,eAAe;IACrB,MAAM;IACN,oBAAoB,EAAE,OAAO,CAAC,oBAAoB;CACnD,CAAC,CAAC;AALQ,QAAA,iBAAiB,qBAKzB"}
@@ -0,0 +1,5 @@
1
+ import type { OrganizationIdSource } from './permissions.decorator';
2
+ export interface RequireOrganizationAdminOptions {
3
+ organizationIdSource: OrganizationIdSource;
4
+ }
5
+ export declare const RequireOrganizationAdminAuth: (options: RequireOrganizationAdminOptions) => import("@nestjs/common").CustomDecorator;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RequireOrganizationAdminAuth = void 0;
4
+ const permissions_decorator_1 = require("./permissions.decorator");
5
+ const RequireOrganizationAdminAuth = (options) => (0, permissions_decorator_1.Permission)({
6
+ type: 'ORGANIZATION_ADMIN_ONLY',
7
+ organizationIdSource: options.organizationIdSource,
8
+ });
9
+ exports.RequireOrganizationAdminAuth = RequireOrganizationAdminAuth;
10
+ //# sourceMappingURL=require-organization-admin.decorator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"require-organization-admin.decorator.js","sourceRoot":"","sources":["../../../src/nestjs/decorators/require-organization-admin.decorator.ts"],"names":[],"mappings":";;;AAAA,mEAAqD;AAQ9C,MAAM,4BAA4B,GAAG,CAAC,OAAwC,EAAE,EAAE,CACvF,IAAA,kCAAU,EAAC;IACT,IAAI,EAAE,yBAAyB;IAC/B,oBAAoB,EAAE,OAAO,CAAC,oBAAoB;CACnD,CAAC,CAAC;AAJQ,QAAA,4BAA4B,gCAIpC"}
@@ -0,0 +1 @@
1
+ export declare const RequireSuperAdminAuth: () => import("@nestjs/common").CustomDecorator;