nestforge-generator 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +371 -0
- package/README.pt-BR.md +370 -0
- package/dist/features/auth-strategy.js +19 -0
- package/dist/features/auth-strategy.js.map +1 -0
- package/dist/features/database.js +59 -0
- package/dist/features/database.js.map +1 -0
- package/dist/features/dependencies.js +57 -0
- package/dist/features/dependencies.js.map +1 -0
- package/dist/features/language.js +172 -0
- package/dist/features/language.js.map +1 -0
- package/dist/features/markers.js +116 -0
- package/dist/features/markers.js.map +1 -0
- package/dist/generator.js +120 -0
- package/dist/generator.js.map +1 -0
- package/dist/index.js +59 -0
- package/dist/index.js.map +1 -0
- package/dist/prompts.js +137 -0
- package/dist/prompts.js.map +1 -0
- package/package.json +76 -0
- package/templates/drizzle/.env.example +45 -0
- package/templates/drizzle/.env.test +38 -0
- package/templates/drizzle/.github/workflows/ci.yml +119 -0
- package/templates/drizzle/ARCHITECTURE.md +227 -0
- package/templates/drizzle/ARCHITECTURE.pt-BR.md +225 -0
- package/templates/drizzle/CODE_OF_CONDUCT.md +29 -0
- package/templates/drizzle/CODE_OF_CONDUCT.pt-BR.md +27 -0
- package/templates/drizzle/CONTRIBUTING.md +57 -0
- package/templates/drizzle/CONTRIBUTING.pt-BR.md +54 -0
- package/templates/drizzle/Dockerfile +43 -0
- package/templates/drizzle/LICENSE +21 -0
- package/templates/drizzle/README.md +257 -0
- package/templates/drizzle/README.pt-BR.md +257 -0
- package/templates/drizzle/ROADMAP.md +143 -0
- package/templates/drizzle/ROADMAP.pt-BR.md +143 -0
- package/templates/drizzle/TESTING.md +136 -0
- package/templates/drizzle/TESTING.pt-BR.md +136 -0
- package/templates/drizzle/docker-compose.yml +82 -0
- package/templates/drizzle/docs/adding-a-module.md +585 -0
- package/templates/drizzle/docs/features-markers.md +457 -0
- package/templates/drizzle/drizzle.config.ts +49 -0
- package/templates/drizzle/nest-cli.json +8 -0
- package/templates/drizzle/package.json +96 -0
- package/templates/drizzle/src/app.module.ts +72 -0
- package/templates/drizzle/src/auth/auth.controller.ts +283 -0
- package/templates/drizzle/src/auth/auth.module.ts +81 -0
- package/templates/drizzle/src/auth/auth.service.spec.ts +111 -0
- package/templates/drizzle/src/auth/auth.service.ts +631 -0
- package/templates/drizzle/src/auth/drizzle-session.store.ts +263 -0
- package/templates/drizzle/src/auth/dto/forgot-password.dto.ts +9 -0
- package/templates/drizzle/src/auth/dto/login.dto.ts +10 -0
- package/templates/drizzle/src/auth/dto/refresh-token.dto.ts +9 -0
- package/templates/drizzle/src/auth/dto/register.dto.ts +11 -0
- package/templates/drizzle/src/auth/dto/reset-password.dto.ts +10 -0
- package/templates/drizzle/src/auth/guards/github-auth.guard.ts +10 -0
- package/templates/drizzle/src/auth/guards/google-auth.guard.ts +10 -0
- package/templates/drizzle/src/auth/guards/jwt-auth.guard.ts +25 -0
- package/templates/drizzle/src/auth/guards/session-auth.guard.spec.ts +77 -0
- package/templates/drizzle/src/auth/guards/session-auth.guard.ts +37 -0
- package/templates/drizzle/src/auth/session.service.spec.ts +74 -0
- package/templates/drizzle/src/auth/session.service.ts +96 -0
- package/templates/drizzle/src/auth/strategies/github.strategy.ts +41 -0
- package/templates/drizzle/src/auth/strategies/google.strategy.ts +43 -0
- package/templates/drizzle/src/auth/strategies/jwt.strategy.ts +25 -0
- package/templates/drizzle/src/auth/token.service.ts +175 -0
- package/templates/drizzle/src/common/constants/permissions.ts +8 -0
- package/templates/drizzle/src/common/constants/role-permissions.ts +9 -0
- package/templates/drizzle/src/common/constants/role.enum.ts +5 -0
- package/templates/drizzle/src/common/decorators/current-user.decorator.ts +8 -0
- package/templates/drizzle/src/common/decorators/permissions.decorator.ts +7 -0
- package/templates/drizzle/src/common/decorators/public.decorator.ts +4 -0
- package/templates/drizzle/src/common/decorators/roles.decorator.ts +6 -0
- package/templates/drizzle/src/common/filters/http-exception.filter.ts +34 -0
- package/templates/drizzle/src/common/guards/permissions.guard.spec.ts +54 -0
- package/templates/drizzle/src/common/guards/permissions.guard.ts +28 -0
- package/templates/drizzle/src/common/guards/roles.guard.spec.ts +37 -0
- package/templates/drizzle/src/common/guards/roles.guard.ts +24 -0
- package/templates/drizzle/src/common/interceptors/logging.interceptor.ts +23 -0
- package/templates/drizzle/src/common/middleware/csrf.middleware.spec.ts +97 -0
- package/templates/drizzle/src/common/middleware/csrf.middleware.ts +46 -0
- package/templates/drizzle/src/common/utils/avatar-storage.util.ts +32 -0
- package/templates/drizzle/src/common/utils/hash.util.ts +5 -0
- package/templates/drizzle/src/config/env.validation.ts +50 -0
- package/templates/drizzle/src/database/database-lifecycle.service.ts +30 -0
- package/templates/drizzle/src/database/database.constants.ts +2 -0
- package/templates/drizzle/src/database/database.decorators.ts +5 -0
- package/templates/drizzle/src/database/database.module.ts +96 -0
- package/templates/drizzle/src/database/database.types.ts +28 -0
- package/templates/drizzle/src/database/schema/index.ts +11 -0
- package/templates/drizzle/src/database/schema/mysql.schema.ts +215 -0
- package/templates/drizzle/src/database/schema/postgres.schema.ts +218 -0
- package/templates/drizzle/src/database/schema/sqlite.schema.ts +190 -0
- package/templates/drizzle/src/database/seed.ts +152 -0
- package/templates/drizzle/src/health/health.controller.ts +49 -0
- package/templates/drizzle/src/health/health.module.ts +19 -0
- package/templates/drizzle/src/health/indicators/drizzle-health.indicator.spec.ts +71 -0
- package/templates/drizzle/src/health/indicators/drizzle-health.indicator.ts +52 -0
- package/templates/drizzle/src/health/indicators/redis-health.indicator.spec.ts +54 -0
- package/templates/drizzle/src/health/indicators/redis-health.indicator.ts +33 -0
- package/templates/drizzle/src/mail/mail.module.ts +12 -0
- package/templates/drizzle/src/mail/mail.processor.ts +48 -0
- package/templates/drizzle/src/mail/mail.service.ts +24 -0
- package/templates/drizzle/src/mail/templates/email-templates.ts +28 -0
- package/templates/drizzle/src/main.ts +145 -0
- package/templates/drizzle/src/metrics/metrics.controller.ts +22 -0
- package/templates/drizzle/src/metrics/metrics.interceptor.ts +30 -0
- package/templates/drizzle/src/metrics/metrics.module.ts +12 -0
- package/templates/drizzle/src/metrics/metrics.service.ts +34 -0
- package/templates/drizzle/src/types/express-session.d.ts +13 -0
- package/templates/drizzle/src/users/dto/create-user.dto.ts +12 -0
- package/templates/drizzle/src/users/dto/find-users-query.dto.ts +12 -0
- package/templates/drizzle/src/users/dto/update-user.dto.ts +6 -0
- package/templates/drizzle/src/users/entities/user.entity.ts +23 -0
- package/templates/drizzle/src/users/users.controller.ts +165 -0
- package/templates/drizzle/src/users/users.module.ts +10 -0
- package/templates/drizzle/src/users/users.service.spec.ts +301 -0
- package/templates/drizzle/src/users/users.service.ts +213 -0
- package/templates/drizzle/test/auth.e2e-spec.ts +114 -0
- package/templates/drizzle/test/session-auth.e2e-spec.ts +163 -0
- package/templates/drizzle/test/users.e2e-spec.ts +212 -0
- package/templates/drizzle/test/utils/clean-database.ts +104 -0
- package/templates/drizzle/test/utils/e2e-setup.ts +77 -0
- package/templates/drizzle/tsconfig.build.json +4 -0
- package/templates/drizzle/tsconfig.json +25 -0
- package/templates/drizzle/vitest.config.ts +20 -0
- package/templates/drizzle/vitest.e2e.config.ts +19 -0
- package/templates/prisma/.env.example +44 -0
- package/templates/prisma/.env.test +37 -0
- package/templates/prisma/.github/workflows/ci.yml +109 -0
- package/templates/prisma/ARCHITECTURE.md +70 -0
- package/templates/prisma/ARCHITECTURE.pt-BR.md +63 -0
- package/templates/prisma/CODE_OF_CONDUCT.md +29 -0
- package/templates/prisma/CODE_OF_CONDUCT.pt-BR.md +27 -0
- package/templates/prisma/CONTRIBUTING.md +57 -0
- package/templates/prisma/CONTRIBUTING.pt-BR.md +54 -0
- package/templates/prisma/Dockerfile +33 -0
- package/templates/prisma/LICENSE +21 -0
- package/templates/prisma/README.md +267 -0
- package/templates/prisma/README.pt-BR.md +267 -0
- package/templates/prisma/ROADMAP.md +75 -0
- package/templates/prisma/ROADMAP.pt-BR.md +65 -0
- package/templates/prisma/TESTING.md +123 -0
- package/templates/prisma/TESTING.pt-BR.md +123 -0
- package/templates/prisma/docker-compose.yml +78 -0
- package/templates/prisma/docs/adding-a-module.md +230 -0
- package/templates/prisma/docs/features-markers.md +50 -0
- package/templates/prisma/nest-cli.json +8 -0
- package/templates/prisma/package.json +95 -0
- package/templates/prisma/prisma/schema.prisma +105 -0
- package/templates/prisma/prisma/seed.ts +46 -0
- package/templates/prisma/src/app.module.ts +72 -0
- package/templates/prisma/src/auth/auth.controller.ts +283 -0
- package/templates/prisma/src/auth/auth.module.ts +59 -0
- package/templates/prisma/src/auth/auth.service.spec.ts +53 -0
- package/templates/prisma/src/auth/auth.service.ts +224 -0
- package/templates/prisma/src/auth/dto/forgot-password.dto.ts +9 -0
- package/templates/prisma/src/auth/dto/login.dto.ts +10 -0
- package/templates/prisma/src/auth/dto/refresh-token.dto.ts +9 -0
- package/templates/prisma/src/auth/dto/register.dto.ts +11 -0
- package/templates/prisma/src/auth/dto/reset-password.dto.ts +10 -0
- package/templates/prisma/src/auth/guards/github-auth.guard.ts +10 -0
- package/templates/prisma/src/auth/guards/google-auth.guard.ts +10 -0
- package/templates/prisma/src/auth/guards/jwt-auth.guard.ts +25 -0
- package/templates/prisma/src/auth/guards/session-auth.guard.spec.ts +77 -0
- package/templates/prisma/src/auth/guards/session-auth.guard.ts +37 -0
- package/templates/prisma/src/auth/session.service.spec.ts +74 -0
- package/templates/prisma/src/auth/session.service.ts +96 -0
- package/templates/prisma/src/auth/strategies/github.strategy.ts +41 -0
- package/templates/prisma/src/auth/strategies/google.strategy.ts +43 -0
- package/templates/prisma/src/auth/strategies/jwt.strategy.ts +25 -0
- package/templates/prisma/src/auth/token.service.ts +84 -0
- package/templates/prisma/src/common/constants/permissions.ts +8 -0
- package/templates/prisma/src/common/constants/role-permissions.ts +9 -0
- package/templates/prisma/src/common/decorators/current-user.decorator.ts +8 -0
- package/templates/prisma/src/common/decorators/permissions.decorator.ts +7 -0
- package/templates/prisma/src/common/decorators/public.decorator.ts +4 -0
- package/templates/prisma/src/common/decorators/roles.decorator.ts +6 -0
- package/templates/prisma/src/common/filters/http-exception.filter.ts +34 -0
- package/templates/prisma/src/common/guards/permissions.guard.spec.ts +54 -0
- package/templates/prisma/src/common/guards/permissions.guard.ts +28 -0
- package/templates/prisma/src/common/guards/roles.guard.spec.ts +37 -0
- package/templates/prisma/src/common/guards/roles.guard.ts +24 -0
- package/templates/prisma/src/common/interceptors/logging.interceptor.ts +23 -0
- package/templates/prisma/src/common/middleware/csrf.middleware.spec.ts +97 -0
- package/templates/prisma/src/common/middleware/csrf.middleware.ts +46 -0
- package/templates/prisma/src/common/utils/avatar-storage.util.ts +32 -0
- package/templates/prisma/src/common/utils/hash.util.ts +5 -0
- package/templates/prisma/src/config/env.validation.ts +49 -0
- package/templates/prisma/src/database/prisma.module.ts +9 -0
- package/templates/prisma/src/database/prisma.service.ts +13 -0
- package/templates/prisma/src/health/health.controller.ts +49 -0
- package/templates/prisma/src/health/health.module.ts +19 -0
- package/templates/prisma/src/health/indicators/prisma-health.indicator.spec.ts +22 -0
- package/templates/prisma/src/health/indicators/prisma-health.indicator.ts +19 -0
- package/templates/prisma/src/health/indicators/redis-health.indicator.spec.ts +54 -0
- package/templates/prisma/src/health/indicators/redis-health.indicator.ts +33 -0
- package/templates/prisma/src/mail/mail.module.ts +12 -0
- package/templates/prisma/src/mail/mail.processor.ts +48 -0
- package/templates/prisma/src/mail/mail.service.ts +24 -0
- package/templates/prisma/src/mail/templates/email-templates.ts +28 -0
- package/templates/prisma/src/main.ts +92 -0
- package/templates/prisma/src/metrics/metrics.controller.ts +22 -0
- package/templates/prisma/src/metrics/metrics.interceptor.ts +30 -0
- package/templates/prisma/src/metrics/metrics.module.ts +12 -0
- package/templates/prisma/src/metrics/metrics.service.ts +34 -0
- package/templates/prisma/src/types/express-session.d.ts +13 -0
- package/templates/prisma/src/users/dto/create-user.dto.ts +12 -0
- package/templates/prisma/src/users/dto/find-users-query.dto.ts +12 -0
- package/templates/prisma/src/users/dto/update-user.dto.ts +6 -0
- package/templates/prisma/src/users/entities/user.entity.ts +20 -0
- package/templates/prisma/src/users/users.controller.ts +165 -0
- package/templates/prisma/src/users/users.module.ts +10 -0
- package/templates/prisma/src/users/users.service.spec.ts +104 -0
- package/templates/prisma/src/users/users.service.ts +114 -0
- package/templates/prisma/test/auth.e2e-spec.ts +75 -0
- package/templates/prisma/test/session-auth.e2e-spec.ts +163 -0
- package/templates/prisma/test/users.e2e-spec.ts +106 -0
- package/templates/prisma/test/utils/clean-database.ts +14 -0
- package/templates/prisma/test/utils/e2e-setup.ts +58 -0
- package/templates/prisma/tsconfig.build.json +4 -0
- package/templates/prisma/tsconfig.json +25 -0
- package/templates/prisma/vitest.config.ts +20 -0
- package/templates/prisma/vitest.e2e.config.ts +19 -0
- package/templates/typeorm/.env.example +45 -0
- package/templates/typeorm/.env.test +38 -0
- package/templates/typeorm/.github/workflows/ci.yml +116 -0
- package/templates/typeorm/ARCHITECTURE.md +158 -0
- package/templates/typeorm/ARCHITECTURE.pt-BR.md +156 -0
- package/templates/typeorm/CODE_OF_CONDUCT.md +29 -0
- package/templates/typeorm/CODE_OF_CONDUCT.pt-BR.md +27 -0
- package/templates/typeorm/CONTRIBUTING.md +57 -0
- package/templates/typeorm/CONTRIBUTING.pt-BR.md +54 -0
- package/templates/typeorm/Dockerfile +43 -0
- package/templates/typeorm/LICENSE +21 -0
- package/templates/typeorm/README.md +266 -0
- package/templates/typeorm/README.pt-BR.md +266 -0
- package/templates/typeorm/ROADMAP.md +79 -0
- package/templates/typeorm/ROADMAP.pt-BR.md +67 -0
- package/templates/typeorm/TESTING.md +114 -0
- package/templates/typeorm/TESTING.pt-BR.md +114 -0
- package/templates/typeorm/docker-compose.yml +78 -0
- package/templates/typeorm/docs/adding-a-module.md +369 -0
- package/templates/typeorm/docs/features-markers.md +50 -0
- package/templates/typeorm/nest-cli.json +8 -0
- package/templates/typeorm/package.json +98 -0
- package/templates/typeorm/src/app.module.ts +72 -0
- package/templates/typeorm/src/auth/auth.controller.ts +283 -0
- package/templates/typeorm/src/auth/auth.module.ts +86 -0
- package/templates/typeorm/src/auth/auth.service.spec.ts +111 -0
- package/templates/typeorm/src/auth/auth.service.ts +346 -0
- package/templates/typeorm/src/auth/dto/forgot-password.dto.ts +9 -0
- package/templates/typeorm/src/auth/dto/login.dto.ts +10 -0
- package/templates/typeorm/src/auth/dto/refresh-token.dto.ts +9 -0
- package/templates/typeorm/src/auth/dto/register.dto.ts +11 -0
- package/templates/typeorm/src/auth/dto/reset-password.dto.ts +10 -0
- package/templates/typeorm/src/auth/entities/email-verification-token.entity.ts +69 -0
- package/templates/typeorm/src/auth/entities/oauth-account.entity.ts +50 -0
- package/templates/typeorm/src/auth/entities/password-reset-token.entity.ts +69 -0
- package/templates/typeorm/src/auth/entities/refresh-token.entity.ts +69 -0
- package/templates/typeorm/src/auth/entities/session.entity.ts +50 -0
- package/templates/typeorm/src/auth/guards/github-auth.guard.ts +10 -0
- package/templates/typeorm/src/auth/guards/google-auth.guard.ts +10 -0
- package/templates/typeorm/src/auth/guards/jwt-auth.guard.ts +25 -0
- package/templates/typeorm/src/auth/guards/session-auth.guard.spec.ts +77 -0
- package/templates/typeorm/src/auth/guards/session-auth.guard.ts +37 -0
- package/templates/typeorm/src/auth/session.service.spec.ts +74 -0
- package/templates/typeorm/src/auth/session.service.ts +96 -0
- package/templates/typeorm/src/auth/strategies/github.strategy.ts +41 -0
- package/templates/typeorm/src/auth/strategies/google.strategy.ts +43 -0
- package/templates/typeorm/src/auth/strategies/jwt.strategy.ts +25 -0
- package/templates/typeorm/src/auth/token.service.ts +115 -0
- package/templates/typeorm/src/common/constants/permissions.ts +8 -0
- package/templates/typeorm/src/common/constants/role-permissions.ts +9 -0
- package/templates/typeorm/src/common/constants/role.enum.ts +5 -0
- package/templates/typeorm/src/common/decorators/current-user.decorator.ts +8 -0
- package/templates/typeorm/src/common/decorators/permissions.decorator.ts +7 -0
- package/templates/typeorm/src/common/decorators/public.decorator.ts +4 -0
- package/templates/typeorm/src/common/decorators/roles.decorator.ts +6 -0
- package/templates/typeorm/src/common/filters/http-exception.filter.ts +34 -0
- package/templates/typeorm/src/common/guards/permissions.guard.spec.ts +54 -0
- package/templates/typeorm/src/common/guards/permissions.guard.ts +28 -0
- package/templates/typeorm/src/common/guards/roles.guard.spec.ts +37 -0
- package/templates/typeorm/src/common/guards/roles.guard.ts +24 -0
- package/templates/typeorm/src/common/interceptors/logging.interceptor.ts +23 -0
- package/templates/typeorm/src/common/middleware/csrf.middleware.spec.ts +97 -0
- package/templates/typeorm/src/common/middleware/csrf.middleware.ts +46 -0
- package/templates/typeorm/src/common/utils/avatar-storage.util.ts +32 -0
- package/templates/typeorm/src/common/utils/hash.util.ts +5 -0
- package/templates/typeorm/src/config/env.validation.ts +50 -0
- package/templates/typeorm/src/database/data-source.ts +20 -0
- package/templates/typeorm/src/database/database.module.ts +39 -0
- package/templates/typeorm/src/database/seed.ts +81 -0
- package/templates/typeorm/src/database/typeorm-options.ts +49 -0
- package/templates/typeorm/src/health/health.controller.ts +49 -0
- package/templates/typeorm/src/health/health.module.ts +19 -0
- package/templates/typeorm/src/health/indicators/redis-health.indicator.spec.ts +54 -0
- package/templates/typeorm/src/health/indicators/redis-health.indicator.ts +33 -0
- package/templates/typeorm/src/health/indicators/typeorm-health.indicator.spec.ts +49 -0
- package/templates/typeorm/src/health/indicators/typeorm-health.indicator.ts +37 -0
- package/templates/typeorm/src/mail/mail.module.ts +12 -0
- package/templates/typeorm/src/mail/mail.processor.ts +48 -0
- package/templates/typeorm/src/mail/mail.service.ts +24 -0
- package/templates/typeorm/src/mail/templates/email-templates.ts +28 -0
- package/templates/typeorm/src/main.ts +107 -0
- package/templates/typeorm/src/metrics/metrics.controller.ts +22 -0
- package/templates/typeorm/src/metrics/metrics.interceptor.ts +30 -0
- package/templates/typeorm/src/metrics/metrics.module.ts +12 -0
- package/templates/typeorm/src/metrics/metrics.service.ts +34 -0
- package/templates/typeorm/src/types/express-session.d.ts +13 -0
- package/templates/typeorm/src/users/dto/create-user.dto.ts +12 -0
- package/templates/typeorm/src/users/dto/find-users-query.dto.ts +12 -0
- package/templates/typeorm/src/users/dto/update-user.dto.ts +6 -0
- package/templates/typeorm/src/users/entities/user.entity.ts +113 -0
- package/templates/typeorm/src/users/users.controller.ts +165 -0
- package/templates/typeorm/src/users/users.module.ts +13 -0
- package/templates/typeorm/src/users/users.service.spec.ts +183 -0
- package/templates/typeorm/src/users/users.service.ts +124 -0
- package/templates/typeorm/test/auth.e2e-spec.ts +111 -0
- package/templates/typeorm/test/session-auth.e2e-spec.ts +159 -0
- package/templates/typeorm/test/users.e2e-spec.ts +183 -0
- package/templates/typeorm/test/utils/clean-database.ts +65 -0
- package/templates/typeorm/test/utils/e2e-setup.ts +77 -0
- package/templates/typeorm/tsconfig.build.json +4 -0
- package/templates/typeorm/tsconfig.json +25 -0
- package/templates/typeorm/vitest.config.ts +20 -0
- package/templates/typeorm/vitest.e2e.config.ts +19 -0
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// nestforge:feature-file:rbac
|
|
2
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
3
|
+
import { ExecutionContext } from '@nestjs/common';
|
|
4
|
+
import { Reflector } from '@nestjs/core';
|
|
5
|
+
import { Role } from '../constants/role.enum';
|
|
6
|
+
import { Permission } from '../constants/permissions';
|
|
7
|
+
import { PermissionsGuard } from './permissions.guard';
|
|
8
|
+
|
|
9
|
+
function createContext(user?: { role: Role }): ExecutionContext {
|
|
10
|
+
return {
|
|
11
|
+
switchToHttp: () => ({ getRequest: () => ({ user }) }),
|
|
12
|
+
getHandler: () => ({}),
|
|
13
|
+
getClass: () => ({}),
|
|
14
|
+
} as unknown as ExecutionContext;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
describe('PermissionsGuard', () => {
|
|
18
|
+
it('libera acesso quando a rota não exige nenhuma permissão', () => {
|
|
19
|
+
const reflector = { getAllAndOverride: vi.fn().mockReturnValue(undefined) } as unknown as Reflector;
|
|
20
|
+
const guard = new PermissionsGuard(reflector);
|
|
21
|
+
|
|
22
|
+
expect(guard.canActivate(createContext({ role: Role.USER }))).toBe(true);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it('libera acesso quando a role do usuário tem a permissão exigida', () => {
|
|
26
|
+
const reflector = {
|
|
27
|
+
getAllAndOverride: vi.fn().mockReturnValue([Permission.UserRead]),
|
|
28
|
+
} as unknown as Reflector;
|
|
29
|
+
const guard = new PermissionsGuard(reflector);
|
|
30
|
+
|
|
31
|
+
expect(guard.canActivate(createContext({ role: Role.USER }))).toBe(true);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('bloqueia acesso quando a role do usuário não tem a permissão exigida', () => {
|
|
35
|
+
const reflector = {
|
|
36
|
+
getAllAndOverride: vi.fn().mockReturnValue([Permission.UserDelete]),
|
|
37
|
+
} as unknown as Reflector;
|
|
38
|
+
const guard = new PermissionsGuard(reflector);
|
|
39
|
+
|
|
40
|
+
expect(guard.canActivate(createContext({ role: Role.USER }))).toBe(false);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('exige todas as permissões quando mais de uma é requisitada', () => {
|
|
44
|
+
const reflector = {
|
|
45
|
+
getAllAndOverride: vi.fn().mockReturnValue([Permission.UserRead, Permission.UserUpdate]),
|
|
46
|
+
} as unknown as Reflector;
|
|
47
|
+
const guard = new PermissionsGuard(reflector);
|
|
48
|
+
|
|
49
|
+
// MANAGER tem user:read e user:update
|
|
50
|
+
expect(guard.canActivate(createContext({ role: Role.MANAGER }))).toBe(true);
|
|
51
|
+
// USER só tem user:read
|
|
52
|
+
expect(guard.canActivate(createContext({ role: Role.USER }))).toBe(false);
|
|
53
|
+
});
|
|
54
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// nestforge:feature-file:rbac
|
|
2
|
+
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
|
3
|
+
import { Reflector } from '@nestjs/core';
|
|
4
|
+
import { Role } from '../constants/role.enum';
|
|
5
|
+
import { PERMISSIONS_KEY } from '../decorators/permissions.decorator';
|
|
6
|
+
import { Permission } from '../constants/permissions';
|
|
7
|
+
import { ROLE_PERMISSIONS } from '../constants/role-permissions';
|
|
8
|
+
|
|
9
|
+
@Injectable()
|
|
10
|
+
export class PermissionsGuard implements CanActivate {
|
|
11
|
+
constructor(private reflector: Reflector) { }
|
|
12
|
+
|
|
13
|
+
canActivate(context: ExecutionContext): boolean {
|
|
14
|
+
const requiredPermissions = this.reflector.getAllAndOverride<Permission[]>(
|
|
15
|
+
PERMISSIONS_KEY,
|
|
16
|
+
[context.getHandler(), context.getClass()],
|
|
17
|
+
);
|
|
18
|
+
|
|
19
|
+
if (!requiredPermissions || requiredPermissions.length === 0) {
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const { user } = context.switchToHttp().getRequest();
|
|
24
|
+
const userPermissions = ROLE_PERMISSIONS[user?.role as Role] ?? [];
|
|
25
|
+
|
|
26
|
+
return requiredPermissions.every((permission) => userPermissions.includes(permission));
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// nestforge:feature-file:rbac
|
|
2
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
3
|
+
import { ExecutionContext } from '@nestjs/common';
|
|
4
|
+
import { Reflector } from '@nestjs/core';
|
|
5
|
+
import { Role } from '../constants/role.enum';
|
|
6
|
+
import { RolesGuard } from './roles.guard';
|
|
7
|
+
|
|
8
|
+
function createContext(user?: { role: Role }): ExecutionContext {
|
|
9
|
+
return {
|
|
10
|
+
switchToHttp: () => ({ getRequest: () => ({ user }) }),
|
|
11
|
+
getHandler: () => ({}),
|
|
12
|
+
getClass: () => ({}),
|
|
13
|
+
} as unknown as ExecutionContext;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
describe('RolesGuard', () => {
|
|
17
|
+
it('libera acesso quando a rota não exige nenhuma role', () => {
|
|
18
|
+
const reflector = { getAllAndOverride: vi.fn().mockReturnValue(undefined) } as unknown as Reflector;
|
|
19
|
+
const guard = new RolesGuard(reflector);
|
|
20
|
+
|
|
21
|
+
expect(guard.canActivate(createContext({ role: Role.USER }))).toBe(true);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it('libera acesso quando o usuário tem a role exigida', () => {
|
|
25
|
+
const reflector = { getAllAndOverride: vi.fn().mockReturnValue([Role.ADMIN]) } as unknown as Reflector;
|
|
26
|
+
const guard = new RolesGuard(reflector);
|
|
27
|
+
|
|
28
|
+
expect(guard.canActivate(createContext({ role: Role.ADMIN }))).toBe(true);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('bloqueia acesso quando o usuário não tem a role exigida', () => {
|
|
32
|
+
const reflector = { getAllAndOverride: vi.fn().mockReturnValue([Role.ADMIN]) } as unknown as Reflector;
|
|
33
|
+
const guard = new RolesGuard(reflector);
|
|
34
|
+
|
|
35
|
+
expect(guard.canActivate(createContext({ role: Role.USER }))).toBe(false);
|
|
36
|
+
});
|
|
37
|
+
});
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// nestforge:feature-file:rbac
|
|
2
|
+
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
|
3
|
+
import { Reflector } from '@nestjs/core';
|
|
4
|
+
import { Role } from '../constants/role.enum';
|
|
5
|
+
import { ROLES_KEY } from '../decorators/roles.decorator';
|
|
6
|
+
|
|
7
|
+
@Injectable()
|
|
8
|
+
export class RolesGuard implements CanActivate {
|
|
9
|
+
constructor(private reflector: Reflector) {}
|
|
10
|
+
|
|
11
|
+
canActivate(context: ExecutionContext): boolean {
|
|
12
|
+
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
|
|
13
|
+
context.getHandler(),
|
|
14
|
+
context.getClass(),
|
|
15
|
+
]);
|
|
16
|
+
|
|
17
|
+
if (!requiredRoles || requiredRoles.length === 0) {
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const { user } = context.switchToHttp().getRequest();
|
|
22
|
+
return requiredRoles.includes(user?.role);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CallHandler,
|
|
3
|
+
ExecutionContext,
|
|
4
|
+
Injectable,
|
|
5
|
+
NestInterceptor,
|
|
6
|
+
} from '@nestjs/common';
|
|
7
|
+
import { Observable, tap } from 'rxjs';
|
|
8
|
+
|
|
9
|
+
@Injectable()
|
|
10
|
+
export class LoggingInterceptor implements NestInterceptor {
|
|
11
|
+
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
|
12
|
+
const request = context.switchToHttp().getRequest();
|
|
13
|
+
const { method, url } = request;
|
|
14
|
+
const start = Date.now();
|
|
15
|
+
|
|
16
|
+
return next.handle().pipe(
|
|
17
|
+
tap(() => {
|
|
18
|
+
const duration = Date.now() - start;
|
|
19
|
+
console.log(`[${method}] ${url} - ${duration}ms`);
|
|
20
|
+
}),
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// nestforge:feature-file:auth:session
|
|
2
|
+
import { ForbiddenException } from '@nestjs/common';
|
|
3
|
+
import { NextFunction, Request, Response } from 'express';
|
|
4
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
5
|
+
import { CsrfMiddleware } from './csrf.middleware';
|
|
6
|
+
|
|
7
|
+
describe('CsrfMiddleware', () => {
|
|
8
|
+
let middleware: CsrfMiddleware;
|
|
9
|
+
let response: Response;
|
|
10
|
+
let next: ReturnType<typeof vi.fn>;
|
|
11
|
+
|
|
12
|
+
beforeEach(() => {
|
|
13
|
+
middleware = new CsrfMiddleware();
|
|
14
|
+
response = {} as Response;
|
|
15
|
+
next = vi.fn();
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
function createRequest(
|
|
19
|
+
method: string,
|
|
20
|
+
sessionToken?: string,
|
|
21
|
+
headerToken?: string,
|
|
22
|
+
): Request {
|
|
23
|
+
return {
|
|
24
|
+
method,
|
|
25
|
+
session: {
|
|
26
|
+
csrfToken: sessionToken,
|
|
27
|
+
},
|
|
28
|
+
get: vi.fn((header: string) => {
|
|
29
|
+
if (header.toLowerCase() === 'x-csrf-token') {
|
|
30
|
+
return headerToken;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
return undefined;
|
|
34
|
+
}),
|
|
35
|
+
} as unknown as Request;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
it.each(['GET', 'HEAD', 'OPTIONS'])(
|
|
39
|
+
'permite o método seguro %s sem token',
|
|
40
|
+
(method) => {
|
|
41
|
+
const request = createRequest(method);
|
|
42
|
+
|
|
43
|
+
middleware.use(
|
|
44
|
+
request,
|
|
45
|
+
response,
|
|
46
|
+
next as unknown as NextFunction,
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
expect(next).toHaveBeenCalledOnce();
|
|
50
|
+
},
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
it('rejeita uma requisição sem token CSRF', () => {
|
|
54
|
+
const request = createRequest('POST');
|
|
55
|
+
|
|
56
|
+
expect(() =>
|
|
57
|
+
middleware.use(
|
|
58
|
+
request,
|
|
59
|
+
response,
|
|
60
|
+
next as unknown as NextFunction,
|
|
61
|
+
),
|
|
62
|
+
).toThrow(ForbiddenException);
|
|
63
|
+
|
|
64
|
+
expect(next).not.toHaveBeenCalled();
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('rejeita quando o token do header é diferente da sessão', () => {
|
|
68
|
+
const request = createRequest(
|
|
69
|
+
'PATCH',
|
|
70
|
+
'session-token',
|
|
71
|
+
'invalid-token',
|
|
72
|
+
);
|
|
73
|
+
|
|
74
|
+
expect(() =>
|
|
75
|
+
middleware.use(
|
|
76
|
+
request,
|
|
77
|
+
response,
|
|
78
|
+
next as unknown as NextFunction,
|
|
79
|
+
),
|
|
80
|
+
).toThrow(ForbiddenException);
|
|
81
|
+
|
|
82
|
+
expect(next).not.toHaveBeenCalled();
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('permite quando o token corresponde ao valor da sessão', () => {
|
|
86
|
+
const token = 'a'.repeat(64);
|
|
87
|
+
const request = createRequest('DELETE', token, token);
|
|
88
|
+
|
|
89
|
+
middleware.use(
|
|
90
|
+
request,
|
|
91
|
+
response,
|
|
92
|
+
next as unknown as NextFunction,
|
|
93
|
+
);
|
|
94
|
+
|
|
95
|
+
expect(next).toHaveBeenCalledOnce();
|
|
96
|
+
});
|
|
97
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// nestforge:feature-file:auth:session
|
|
2
|
+
import {
|
|
3
|
+
ForbiddenException,
|
|
4
|
+
Injectable,
|
|
5
|
+
NestMiddleware,
|
|
6
|
+
} from '@nestjs/common';
|
|
7
|
+
import { timingSafeEqual } from 'node:crypto';
|
|
8
|
+
import { NextFunction, Request, Response } from 'express';
|
|
9
|
+
|
|
10
|
+
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
11
|
+
const CSRF_HEADER = 'x-csrf-token';
|
|
12
|
+
|
|
13
|
+
@Injectable()
|
|
14
|
+
export class CsrfMiddleware implements NestMiddleware {
|
|
15
|
+
use(request: Request, _response: Response, next: NextFunction) {
|
|
16
|
+
if (SAFE_METHODS.has(request.method)) {
|
|
17
|
+
next();
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const sessionToken = request.session?.csrfToken;
|
|
22
|
+
const headerToken = request.get(CSRF_HEADER);
|
|
23
|
+
|
|
24
|
+
if (
|
|
25
|
+
!sessionToken ||
|
|
26
|
+
!headerToken ||
|
|
27
|
+
!this.tokensMatch(sessionToken, headerToken)
|
|
28
|
+
) {
|
|
29
|
+
throw new ForbiddenException(
|
|
30
|
+
'Token CSRF inválido ou ausente',
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
next();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
private tokensMatch(expected: string, received: string): boolean {
|
|
38
|
+
const expectedBuffer = Buffer.from(expected, 'utf8');
|
|
39
|
+
const receivedBuffer = Buffer.from(received, 'utf8');
|
|
40
|
+
|
|
41
|
+
return (
|
|
42
|
+
expectedBuffer.length === receivedBuffer.length &&
|
|
43
|
+
timingSafeEqual(expectedBuffer, receivedBuffer)
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { BadRequestException } from '@nestjs/common';
|
|
2
|
+
import { randomUUID } from 'crypto';
|
|
3
|
+
import { diskStorage } from 'multer';
|
|
4
|
+
import { extname } from 'path';
|
|
5
|
+
|
|
6
|
+
const ALLOWED_MIME_TYPES = ['image/png', 'image/jpeg', 'image/webp'];
|
|
7
|
+
|
|
8
|
+
export const avatarStorage = diskStorage({
|
|
9
|
+
destination: './uploads/avatars',
|
|
10
|
+
filename: (_req, file, callback) => {
|
|
11
|
+
const uniqueName = `${randomUUID()}${extname(file.originalname)}`;
|
|
12
|
+
callback(null, uniqueName);
|
|
13
|
+
},
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
export function avatarFileFilter(
|
|
17
|
+
_req: unknown,
|
|
18
|
+
file: Express.Multer.File,
|
|
19
|
+
callback: (error: Error | null, acceptFile: boolean) => void,
|
|
20
|
+
) {
|
|
21
|
+
if (!ALLOWED_MIME_TYPES.includes(file.mimetype)) {
|
|
22
|
+
callback(
|
|
23
|
+
new BadRequestException('Formato de imagem não suportado (use PNG, JPEG ou WEBP)'),
|
|
24
|
+
false,
|
|
25
|
+
);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
callback(null, true);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const AVATAR_MAX_SIZE_BYTES = 2 * 1024 * 1024; // 2MB
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
const envSchema = z.object({
|
|
4
|
+
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
|
|
5
|
+
PORT: z.coerce.number().default(3000),
|
|
6
|
+
APP_URL: z.string().url().default('http://localhost:3000'),
|
|
7
|
+
CORS_ORIGINS: z.string().min(1).default('http://localhost:5173'),
|
|
8
|
+
DB_TYPE: z.enum(['postgres', 'mysql', 'sqlite']).default('postgres'),
|
|
9
|
+
DATABASE_URL: z.string().url(),
|
|
10
|
+
// nestforge:feature:auth:token
|
|
11
|
+
JWT_ACCESS_SECRET: z.string().min(16),
|
|
12
|
+
JWT_ACCESS_EXPIRES_IN: z.string().default('15m'),
|
|
13
|
+
JWT_REFRESH_SECRET: z.string().min(16),
|
|
14
|
+
JWT_REFRESH_EXPIRES_IN: z.string().default('7d'),
|
|
15
|
+
// nestforge:feature:auth:token:end
|
|
16
|
+
REDIS_HOST: z.string().default('localhost'),
|
|
17
|
+
REDIS_PORT: z.coerce.number().default(6379),
|
|
18
|
+
MAIL_HOST: z.string().default('localhost'),
|
|
19
|
+
MAIL_PORT: z.coerce.number().default(1025),
|
|
20
|
+
MAIL_FROM: z.string().default('NestForge <no-reply@nestforge.dev>'),
|
|
21
|
+
GOOGLE_CLIENT_ID: z.string().optional(),
|
|
22
|
+
GOOGLE_CLIENT_SECRET: z.string().optional(),
|
|
23
|
+
GITHUB_CLIENT_ID: z.string().optional(),
|
|
24
|
+
GITHUB_CLIENT_SECRET: z.string().optional(),
|
|
25
|
+
THROTTLE_TTL: z.coerce.number().default(60),
|
|
26
|
+
THROTTLE_LIMIT: z.coerce.number().default(100),
|
|
27
|
+
// nestforge:feature:auth:session
|
|
28
|
+
ENABLE_CSRF: z
|
|
29
|
+
.enum(['true', 'false'])
|
|
30
|
+
.transform((value) => value === 'true')
|
|
31
|
+
.default('true'),
|
|
32
|
+
SESSION_SECRET: z.string().min(32),
|
|
33
|
+
SESSION_MAX_AGE: z.coerce.number().positive().default(604800000),
|
|
34
|
+
// nestforge:feature:auth:session:end
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
export type EnvConfig = z.infer<typeof envSchema>;
|
|
38
|
+
|
|
39
|
+
export function validateEnv(config: Record<string, unknown>): EnvConfig {
|
|
40
|
+
const parsed = envSchema.safeParse(config);
|
|
41
|
+
|
|
42
|
+
if (!parsed.success) {
|
|
43
|
+
const issues = parsed.error.issues
|
|
44
|
+
.map((issue) => `${issue.path.join('.')}: ${issue.message}`)
|
|
45
|
+
.join('\n');
|
|
46
|
+
throw new Error(`Variáveis de ambiente inválidas:\n${issues}`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return parsed.data;
|
|
50
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import 'reflect-metadata';
|
|
2
|
+
import { DataSource } from 'typeorm';
|
|
3
|
+
import {
|
|
4
|
+
createTypeOrmOptions,
|
|
5
|
+
DatabaseType,
|
|
6
|
+
} from './typeorm-options';
|
|
7
|
+
|
|
8
|
+
const databaseType = (
|
|
9
|
+
process.env.DB_TYPE ?? 'postgres'
|
|
10
|
+
) as DatabaseType;
|
|
11
|
+
|
|
12
|
+
const databaseUrl = process.env.DATABASE_URL;
|
|
13
|
+
|
|
14
|
+
if (!databaseUrl) {
|
|
15
|
+
throw new Error('DATABASE_URL não foi definida');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export default new DataSource(
|
|
19
|
+
createTypeOrmOptions(databaseType, databaseUrl),
|
|
20
|
+
);
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Global, Module } from '@nestjs/common';
|
|
2
|
+
import { ConfigService } from '@nestjs/config';
|
|
3
|
+
import {
|
|
4
|
+
TypeOrmModule,
|
|
5
|
+
TypeOrmModuleOptions,
|
|
6
|
+
} from '@nestjs/typeorm';
|
|
7
|
+
import {
|
|
8
|
+
createTypeOrmOptions,
|
|
9
|
+
DatabaseType,
|
|
10
|
+
} from './typeorm-options';
|
|
11
|
+
|
|
12
|
+
@Global()
|
|
13
|
+
@Module({
|
|
14
|
+
imports: [
|
|
15
|
+
TypeOrmModule.forRootAsync({
|
|
16
|
+
inject: [ConfigService],
|
|
17
|
+
useFactory: (
|
|
18
|
+
configService: ConfigService,
|
|
19
|
+
): TypeOrmModuleOptions => {
|
|
20
|
+
const databaseType =
|
|
21
|
+
configService.getOrThrow<DatabaseType>(
|
|
22
|
+
'DB_TYPE',
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
const databaseUrl =
|
|
26
|
+
configService.getOrThrow<string>(
|
|
27
|
+
'DATABASE_URL',
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
return createTypeOrmOptions(
|
|
31
|
+
databaseType,
|
|
32
|
+
databaseUrl,
|
|
33
|
+
);
|
|
34
|
+
},
|
|
35
|
+
}),
|
|
36
|
+
],
|
|
37
|
+
exports: [TypeOrmModule],
|
|
38
|
+
})
|
|
39
|
+
export class DatabaseModule { }
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// nestforge:feature-file:auth:password
|
|
2
|
+
import * as bcrypt from 'bcryptjs';
|
|
3
|
+
import dataSource from './data-source';
|
|
4
|
+
import { UserEntity } from '../users/entities/user.entity';
|
|
5
|
+
import { Role } from '../common/constants/role.enum';
|
|
6
|
+
|
|
7
|
+
interface SeedUser {
|
|
8
|
+
name: string;
|
|
9
|
+
email: string;
|
|
10
|
+
password: string;
|
|
11
|
+
role: Role;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const SEED_USERS: SeedUser[] = [
|
|
15
|
+
{
|
|
16
|
+
name: 'Admin',
|
|
17
|
+
email: 'admin@nestforge.dev',
|
|
18
|
+
password: 'admin123',
|
|
19
|
+
role: Role.ADMIN,
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
name: 'Manager',
|
|
23
|
+
email: 'manager@nestforge.dev',
|
|
24
|
+
password: 'manager123',
|
|
25
|
+
role: Role.MANAGER,
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
name: 'Usuário',
|
|
29
|
+
email: 'user@nestforge.dev',
|
|
30
|
+
password: 'user1234',
|
|
31
|
+
role: Role.USER,
|
|
32
|
+
},
|
|
33
|
+
];
|
|
34
|
+
|
|
35
|
+
async function seed() {
|
|
36
|
+
await dataSource.initialize();
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
const usersRepository =
|
|
40
|
+
dataSource.getRepository(UserEntity);
|
|
41
|
+
|
|
42
|
+
for (const seedUser of SEED_USERS) {
|
|
43
|
+
const existingUser =
|
|
44
|
+
await usersRepository.findOne({
|
|
45
|
+
where: {
|
|
46
|
+
email: seedUser.email,
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
if (!existingUser) {
|
|
51
|
+
const passwordHash = await bcrypt.hash(
|
|
52
|
+
seedUser.password,
|
|
53
|
+
10,
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
const user = usersRepository.create({
|
|
57
|
+
name: seedUser.name,
|
|
58
|
+
email: seedUser.email,
|
|
59
|
+
passwordHash,
|
|
60
|
+
role: seedUser.role,
|
|
61
|
+
emailVerifiedAt: new Date(),
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
await usersRepository.save(user);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
console.log(
|
|
68
|
+
`Seed: ${seedUser.email} / ${seedUser.password} (${seedUser.role})`,
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
} finally {
|
|
72
|
+
if (dataSource.isInitialized) {
|
|
73
|
+
await dataSource.destroy();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
seed().catch((error: unknown) => {
|
|
79
|
+
console.error('Erro ao executar o seed:', error);
|
|
80
|
+
process.exitCode = 1;
|
|
81
|
+
});
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { DataSourceOptions } from 'typeorm';
|
|
3
|
+
|
|
4
|
+
export type DatabaseType = 'postgres' | 'mysql' | 'sqlite';
|
|
5
|
+
|
|
6
|
+
export function createTypeOrmOptions(
|
|
7
|
+
databaseType: DatabaseType,
|
|
8
|
+
databaseUrl: string,
|
|
9
|
+
): DataSourceOptions {
|
|
10
|
+
const commonOptions = {
|
|
11
|
+
entities: [
|
|
12
|
+
join(__dirname, '..', '**', '*.entity.{ts,js}'),
|
|
13
|
+
],
|
|
14
|
+
migrations: [
|
|
15
|
+
join(__dirname, 'migrations', '*.{ts,js}'),
|
|
16
|
+
],
|
|
17
|
+
migrationsTableName: 'typeorm_migrations',
|
|
18
|
+
synchronize: false,
|
|
19
|
+
logging: process.env.NODE_ENV === 'development',
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
switch (databaseType) {
|
|
23
|
+
case 'postgres':
|
|
24
|
+
return {
|
|
25
|
+
...commonOptions,
|
|
26
|
+
type: 'postgres',
|
|
27
|
+
url: databaseUrl,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
case 'mysql':
|
|
31
|
+
return {
|
|
32
|
+
...commonOptions,
|
|
33
|
+
type: 'mysql',
|
|
34
|
+
url: databaseUrl,
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
case 'sqlite':
|
|
38
|
+
return {
|
|
39
|
+
...commonOptions,
|
|
40
|
+
type: 'better-sqlite3',
|
|
41
|
+
database: databaseUrl.replace(/^file:/, ''),
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
default:
|
|
45
|
+
throw new Error(
|
|
46
|
+
`Banco "${databaseType}" não suportado pelo template TypeORM`,
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Controller, Get } from '@nestjs/common';
|
|
2
|
+
import {
|
|
3
|
+
DiskHealthIndicator,
|
|
4
|
+
HealthCheck,
|
|
5
|
+
HealthCheckService,
|
|
6
|
+
MemoryHealthIndicator,
|
|
7
|
+
} from '@nestjs/terminus';
|
|
8
|
+
// nestforge:feature:swagger
|
|
9
|
+
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
|
10
|
+
// nestforge:feature:swagger:end
|
|
11
|
+
import { Public } from '../common/decorators/public.decorator';
|
|
12
|
+
import { TypeOrmHealthIndicator } from './indicators/typeorm-health.indicator';
|
|
13
|
+
// nestforge:feature:redis
|
|
14
|
+
import { RedisHealthIndicator } from './indicators/redis-health.indicator';
|
|
15
|
+
// nestforge:feature:redis:end
|
|
16
|
+
|
|
17
|
+
// nestforge:feature:swagger
|
|
18
|
+
@ApiTags('health')
|
|
19
|
+
// nestforge:feature:swagger:end
|
|
20
|
+
@Controller('health')
|
|
21
|
+
export class HealthController {
|
|
22
|
+
constructor(
|
|
23
|
+
private readonly health: HealthCheckService,
|
|
24
|
+
private readonly databaseIndicator: TypeOrmHealthIndicator,
|
|
25
|
+
// nestforge:feature:redis
|
|
26
|
+
private readonly redisIndicator: RedisHealthIndicator,
|
|
27
|
+
// nestforge:feature:redis:end
|
|
28
|
+
private readonly memory: MemoryHealthIndicator,
|
|
29
|
+
private readonly disk: DiskHealthIndicator,
|
|
30
|
+
) { }
|
|
31
|
+
|
|
32
|
+
@Public()
|
|
33
|
+
@Get()
|
|
34
|
+
@HealthCheck()
|
|
35
|
+
// nestforge:feature:swagger
|
|
36
|
+
@ApiOperation({ summary: 'Verifica a saúde da API (banco, memória, disco e demais dependências configuradas)' })
|
|
37
|
+
// nestforge:feature:swagger:end
|
|
38
|
+
check() {
|
|
39
|
+
return this.health.check([
|
|
40
|
+
() => this.databaseIndicator.isHealthy('database'),
|
|
41
|
+
// nestforge:feature:redis
|
|
42
|
+
() => this.redisIndicator.isHealthy('redis'),
|
|
43
|
+
// nestforge:feature:redis:end
|
|
44
|
+
() => this.memory.checkHeap('memory_heap', 300 * 1024 * 1024),
|
|
45
|
+
() => this.memory.checkRSS('memory_rss', 300 * 1024 * 1024),
|
|
46
|
+
() => this.disk.checkStorage('disk', { path: '/', thresholdPercent: 0.9 }),
|
|
47
|
+
]);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { Module } from '@nestjs/common';
|
|
2
|
+
import { TerminusModule } from '@nestjs/terminus';
|
|
3
|
+
import { HealthController } from './health.controller';
|
|
4
|
+
import { TypeOrmHealthIndicator } from './indicators/typeorm-health.indicator';
|
|
5
|
+
// nestforge:feature:redis
|
|
6
|
+
import { RedisHealthIndicator } from './indicators/redis-health.indicator';
|
|
7
|
+
// nestforge:feature:redis:end
|
|
8
|
+
|
|
9
|
+
@Module({
|
|
10
|
+
imports: [TerminusModule],
|
|
11
|
+
controllers: [HealthController],
|
|
12
|
+
providers: [
|
|
13
|
+
TypeOrmHealthIndicator,
|
|
14
|
+
// nestforge:feature:redis
|
|
15
|
+
RedisHealthIndicator,
|
|
16
|
+
// nestforge:feature:redis:end
|
|
17
|
+
],
|
|
18
|
+
})
|
|
19
|
+
export class HealthModule { }
|