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,43 @@
|
|
|
1
|
+
import { Injectable } from '@nestjs/common';
|
|
2
|
+
import { PassportStrategy } from '@nestjs/passport';
|
|
3
|
+
import { Strategy, Profile, VerifyCallback } from 'passport-google-oauth20';
|
|
4
|
+
import { ConfigService } from '@nestjs/config';
|
|
5
|
+
|
|
6
|
+
export interface OAuthProfile {
|
|
7
|
+
provider: 'google' | 'github';
|
|
8
|
+
providerUserId: string;
|
|
9
|
+
email: string;
|
|
10
|
+
name: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
@Injectable()
|
|
14
|
+
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
|
|
15
|
+
constructor(configService: ConfigService) {
|
|
16
|
+
super({
|
|
17
|
+
clientID: configService.getOrThrow<string>('GOOGLE_CLIENT_ID'),
|
|
18
|
+
clientSecret: configService.getOrThrow<string>(
|
|
19
|
+
'GOOGLE_CLIENT_SECRET',
|
|
20
|
+
),
|
|
21
|
+
callbackURL: `${configService.getOrThrow<string>(
|
|
22
|
+
'APP_URL',
|
|
23
|
+
)}/auth/google/callback`,
|
|
24
|
+
scope: ['email', 'profile'],
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async validate(
|
|
29
|
+
_accessToken: string,
|
|
30
|
+
_refreshToken: string,
|
|
31
|
+
profile: Profile,
|
|
32
|
+
done: VerifyCallback,
|
|
33
|
+
) {
|
|
34
|
+
const oauthProfile: OAuthProfile = {
|
|
35
|
+
provider: 'google',
|
|
36
|
+
providerUserId: profile.id,
|
|
37
|
+
email: profile.emails?.[0]?.value ?? '',
|
|
38
|
+
name: profile.displayName,
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
done(null, oauthProfile);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// nestforge:feature-file:auth:token
|
|
2
|
+
import { Injectable } from '@nestjs/common';
|
|
3
|
+
import { PassportStrategy } from '@nestjs/passport';
|
|
4
|
+
import { ExtractJwt, Strategy } from 'passport-jwt';
|
|
5
|
+
|
|
6
|
+
export interface JwtPayload {
|
|
7
|
+
sub: string;
|
|
8
|
+
email: string;
|
|
9
|
+
role: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
@Injectable()
|
|
13
|
+
export class JwtStrategy extends PassportStrategy(Strategy) {
|
|
14
|
+
constructor() {
|
|
15
|
+
super({
|
|
16
|
+
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
17
|
+
ignoreExpiration: false,
|
|
18
|
+
secretOrKey: process.env.JWT_ACCESS_SECRET as string,
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async validate(payload: JwtPayload) {
|
|
23
|
+
return { id: payload.sub, email: payload.email, role: payload.role };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// nestforge:feature-file:auth:token
|
|
2
|
+
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
|
3
|
+
import { JwtService } from '@nestjs/jwt';
|
|
4
|
+
import { createHash } from 'crypto';
|
|
5
|
+
import { PrismaService } from '../database/prisma.service';
|
|
6
|
+
|
|
7
|
+
@Injectable()
|
|
8
|
+
export class TokenService {
|
|
9
|
+
constructor(
|
|
10
|
+
private readonly prisma: PrismaService,
|
|
11
|
+
private readonly jwtService: JwtService,
|
|
12
|
+
) { }
|
|
13
|
+
|
|
14
|
+
async issueTokens(userId: string, email: string, role: string) {
|
|
15
|
+
const payload = { sub: userId, email, role };
|
|
16
|
+
|
|
17
|
+
const accessToken = this.jwtService.sign(payload, {
|
|
18
|
+
secret: process.env.JWT_ACCESS_SECRET,
|
|
19
|
+
expiresIn: process.env.JWT_ACCESS_EXPIRES_IN ?? '15m',
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
const refreshToken = this.jwtService.sign(payload, {
|
|
23
|
+
secret: process.env.JWT_REFRESH_SECRET,
|
|
24
|
+
expiresIn: process.env.JWT_REFRESH_EXPIRES_IN ?? '7d',
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
const expiresAt = new Date();
|
|
28
|
+
expiresAt.setDate(expiresAt.getDate() + 7);
|
|
29
|
+
|
|
30
|
+
await this.prisma.refreshToken.create({
|
|
31
|
+
data: {
|
|
32
|
+
tokenHash: this.hashToken(refreshToken),
|
|
33
|
+
userId,
|
|
34
|
+
expiresAt,
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
return { accessToken, refreshToken };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async refresh(refreshToken: string) {
|
|
42
|
+
const tokenHash = this.hashToken(refreshToken);
|
|
43
|
+
|
|
44
|
+
const stored = await this.prisma.refreshToken.findUnique({
|
|
45
|
+
where: { tokenHash },
|
|
46
|
+
include: { user: true },
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
if (!stored || stored.revokedAt || stored.expiresAt < new Date()) {
|
|
50
|
+
throw new UnauthorizedException('Refresh token inválido ou expirado');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
await this.prisma.refreshToken.update({
|
|
54
|
+
where: { id: stored.id },
|
|
55
|
+
data: { revokedAt: new Date() },
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
return this.issueTokens(
|
|
59
|
+
stored.user.id,
|
|
60
|
+
stored.user.email,
|
|
61
|
+
stored.user.role,
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async logout(refreshToken: string) {
|
|
66
|
+
const tokenHash = this.hashToken(refreshToken);
|
|
67
|
+
|
|
68
|
+
await this.prisma.refreshToken.updateMany({
|
|
69
|
+
where: {
|
|
70
|
+
tokenHash,
|
|
71
|
+
revokedAt: null,
|
|
72
|
+
},
|
|
73
|
+
data: {
|
|
74
|
+
revokedAt: new Date(),
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
return { message: 'Logout realizado com sucesso' };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
private hashToken(token: string): string {
|
|
82
|
+
return createHash('sha256').update(token).digest('hex');
|
|
83
|
+
}
|
|
84
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// nestforge:feature-file:rbac
|
|
2
|
+
import { Role } from '@prisma/client';
|
|
3
|
+
import { Permission } from './permissions';
|
|
4
|
+
|
|
5
|
+
export const ROLE_PERMISSIONS: Record<Role, Permission[]> = {
|
|
6
|
+
[Role.ADMIN]: Object.values(Permission),
|
|
7
|
+
[Role.MANAGER]: [Permission.UserRead, Permission.UserUpdate, Permission.ReportRead],
|
|
8
|
+
[Role.USER]: [Permission.UserRead],
|
|
9
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// nestforge:feature-file:rbac
|
|
2
|
+
import { SetMetadata } from '@nestjs/common';
|
|
3
|
+
import { Permission } from '../constants/permissions';
|
|
4
|
+
|
|
5
|
+
export const PERMISSIONS_KEY = 'permissions';
|
|
6
|
+
export const Permissions = (...permissions: Permission[]) =>
|
|
7
|
+
SetMetadata(PERMISSIONS_KEY, permissions);
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ArgumentsHost,
|
|
3
|
+
Catch,
|
|
4
|
+
ExceptionFilter,
|
|
5
|
+
HttpException,
|
|
6
|
+
HttpStatus,
|
|
7
|
+
} from '@nestjs/common';
|
|
8
|
+
import { Request, Response } from 'express';
|
|
9
|
+
|
|
10
|
+
@Catch()
|
|
11
|
+
export class HttpExceptionFilter implements ExceptionFilter {
|
|
12
|
+
catch(exception: unknown, host: ArgumentsHost) {
|
|
13
|
+
const ctx = host.switchToHttp();
|
|
14
|
+
const response = ctx.getResponse<Response>();
|
|
15
|
+
const request = ctx.getRequest<Request>();
|
|
16
|
+
|
|
17
|
+
const status =
|
|
18
|
+
exception instanceof HttpException
|
|
19
|
+
? exception.getStatus()
|
|
20
|
+
: HttpStatus.INTERNAL_SERVER_ERROR;
|
|
21
|
+
|
|
22
|
+
const message =
|
|
23
|
+
exception instanceof HttpException
|
|
24
|
+
? exception.getResponse()
|
|
25
|
+
: 'Erro interno do servidor';
|
|
26
|
+
|
|
27
|
+
response.status(status).json({
|
|
28
|
+
statusCode: status,
|
|
29
|
+
path: request.url,
|
|
30
|
+
timestamp: new Date().toISOString(),
|
|
31
|
+
message,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -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 '@prisma/client';
|
|
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 '@prisma/client';
|
|
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 '@prisma/client';
|
|
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 '@prisma/client';
|
|
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,49 @@
|
|
|
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
|
+
DATABASE_URL: z.string().url(),
|
|
9
|
+
// nestforge:feature:auth:token
|
|
10
|
+
JWT_ACCESS_SECRET: z.string().min(16),
|
|
11
|
+
JWT_ACCESS_EXPIRES_IN: z.string().default('15m'),
|
|
12
|
+
JWT_REFRESH_SECRET: z.string().min(16),
|
|
13
|
+
JWT_REFRESH_EXPIRES_IN: z.string().default('7d'),
|
|
14
|
+
// nestforge:feature:auth:token:end
|
|
15
|
+
REDIS_HOST: z.string().default('localhost'),
|
|
16
|
+
REDIS_PORT: z.coerce.number().default(6379),
|
|
17
|
+
MAIL_HOST: z.string().default('localhost'),
|
|
18
|
+
MAIL_PORT: z.coerce.number().default(1025),
|
|
19
|
+
MAIL_FROM: z.string().default('NestForge <no-reply@nestforge.dev>'),
|
|
20
|
+
GOOGLE_CLIENT_ID: z.string().optional(),
|
|
21
|
+
GOOGLE_CLIENT_SECRET: z.string().optional(),
|
|
22
|
+
GITHUB_CLIENT_ID: z.string().optional(),
|
|
23
|
+
GITHUB_CLIENT_SECRET: z.string().optional(),
|
|
24
|
+
THROTTLE_TTL: z.coerce.number().default(60),
|
|
25
|
+
THROTTLE_LIMIT: z.coerce.number().default(100),
|
|
26
|
+
// nestforge:feature:auth:session
|
|
27
|
+
ENABLE_CSRF: z
|
|
28
|
+
.enum(['true', 'false'])
|
|
29
|
+
.transform((value) => value === 'true')
|
|
30
|
+
.default('true'),
|
|
31
|
+
SESSION_SECRET: z.string().min(32),
|
|
32
|
+
SESSION_MAX_AGE: z.coerce.number().positive().default(604800000),
|
|
33
|
+
// nestforge:feature:auth:session:end
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
export type EnvConfig = z.infer<typeof envSchema>;
|
|
37
|
+
|
|
38
|
+
export function validateEnv(config: Record<string, unknown>): EnvConfig {
|
|
39
|
+
const parsed = envSchema.safeParse(config);
|
|
40
|
+
|
|
41
|
+
if (!parsed.success) {
|
|
42
|
+
const issues = parsed.error.issues
|
|
43
|
+
.map((issue) => `${issue.path.join('.')}: ${issue.message}`)
|
|
44
|
+
.join('\n');
|
|
45
|
+
throw new Error(`Variáveis de ambiente inválidas:\n${issues}`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return parsed.data;
|
|
49
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
|
2
|
+
import { PrismaClient } from '@prisma/client';
|
|
3
|
+
|
|
4
|
+
@Injectable()
|
|
5
|
+
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
|
|
6
|
+
async onModuleInit() {
|
|
7
|
+
await this.$connect();
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
async onModuleDestroy() {
|
|
11
|
+
await this.$disconnect();
|
|
12
|
+
}
|
|
13
|
+
}
|