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,263 @@
|
|
|
1
|
+
// nestforge:feature-file:auth:session
|
|
2
|
+
import { Injectable } from '@nestjs/common';
|
|
3
|
+
import {
|
|
4
|
+
and,
|
|
5
|
+
count,
|
|
6
|
+
eq,
|
|
7
|
+
gt,
|
|
8
|
+
isNull,
|
|
9
|
+
} from 'drizzle-orm';
|
|
10
|
+
import {
|
|
11
|
+
Store,
|
|
12
|
+
type SessionData,
|
|
13
|
+
} from 'express-session';
|
|
14
|
+
import { InjectDatabase } from '../database/database.decorators';
|
|
15
|
+
import type { DrizzleDatabase } from '../database/database.types';
|
|
16
|
+
import { sessions } from '../database/schema';
|
|
17
|
+
|
|
18
|
+
type StoreCallback = (error?: unknown) => void;
|
|
19
|
+
|
|
20
|
+
type GetCallback = (
|
|
21
|
+
error: unknown,
|
|
22
|
+
session?: SessionData | null,
|
|
23
|
+
) => void;
|
|
24
|
+
|
|
25
|
+
type AllCallback = (
|
|
26
|
+
error: unknown,
|
|
27
|
+
sessions?:
|
|
28
|
+
| SessionData[]
|
|
29
|
+
| Record<string, SessionData>
|
|
30
|
+
| null,
|
|
31
|
+
) => void;
|
|
32
|
+
|
|
33
|
+
type LengthCallback = (
|
|
34
|
+
error: unknown,
|
|
35
|
+
length?: number,
|
|
36
|
+
) => void;
|
|
37
|
+
|
|
38
|
+
@Injectable()
|
|
39
|
+
export class DrizzleSessionStore extends Store {
|
|
40
|
+
constructor(
|
|
41
|
+
@InjectDatabase()
|
|
42
|
+
private readonly database: DrizzleDatabase,
|
|
43
|
+
) {
|
|
44
|
+
super();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async get(
|
|
48
|
+
sessionId: string,
|
|
49
|
+
callback: GetCallback,
|
|
50
|
+
): Promise<void> {
|
|
51
|
+
try {
|
|
52
|
+
const [storedSession] =
|
|
53
|
+
await this.database
|
|
54
|
+
.select()
|
|
55
|
+
.from(sessions)
|
|
56
|
+
.where(
|
|
57
|
+
and(
|
|
58
|
+
eq(sessions.id, sessionId),
|
|
59
|
+
gt(sessions.expiredAt, Date.now()),
|
|
60
|
+
isNull(sessions.destroyedAt),
|
|
61
|
+
),
|
|
62
|
+
)
|
|
63
|
+
.limit(1);
|
|
64
|
+
|
|
65
|
+
if (!storedSession) {
|
|
66
|
+
callback(null, null);
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const sessionData = JSON.parse(
|
|
71
|
+
storedSession.json,
|
|
72
|
+
) as SessionData;
|
|
73
|
+
|
|
74
|
+
callback(null, sessionData);
|
|
75
|
+
} catch (error) {
|
|
76
|
+
callback(error);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async set(
|
|
81
|
+
sessionId: string,
|
|
82
|
+
sessionData: SessionData,
|
|
83
|
+
callback?: StoreCallback,
|
|
84
|
+
): Promise<void> {
|
|
85
|
+
try {
|
|
86
|
+
const values = {
|
|
87
|
+
id: sessionId,
|
|
88
|
+
expiredAt:
|
|
89
|
+
this.resolveExpiration(sessionData),
|
|
90
|
+
json: JSON.stringify(sessionData),
|
|
91
|
+
destroyedAt: null,
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
// nestforge:feature:database:postgres
|
|
95
|
+
await this.database
|
|
96
|
+
.insert(sessions)
|
|
97
|
+
.values(values)
|
|
98
|
+
.onConflictDoUpdate({
|
|
99
|
+
target: sessions.id,
|
|
100
|
+
set: {
|
|
101
|
+
expiredAt: values.expiredAt,
|
|
102
|
+
json: values.json,
|
|
103
|
+
destroyedAt: null,
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
// nestforge:feature:database:postgres:end
|
|
107
|
+
|
|
108
|
+
// nestforge:feature:database:mysql
|
|
109
|
+
await this.database
|
|
110
|
+
.insert(sessions)
|
|
111
|
+
.values(values)
|
|
112
|
+
.onDuplicateKeyUpdate({
|
|
113
|
+
set: {
|
|
114
|
+
expiredAt: values.expiredAt,
|
|
115
|
+
json: values.json,
|
|
116
|
+
destroyedAt: null,
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
// nestforge:feature:database:mysql:end
|
|
120
|
+
|
|
121
|
+
// nestforge:feature:database:sqlite
|
|
122
|
+
await this.database
|
|
123
|
+
.insert(sessions)
|
|
124
|
+
.values(values)
|
|
125
|
+
.onConflictDoUpdate({
|
|
126
|
+
target: sessions.id,
|
|
127
|
+
set: {
|
|
128
|
+
expiredAt: values.expiredAt,
|
|
129
|
+
json: values.json,
|
|
130
|
+
destroyedAt: null,
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
// nestforge:feature:database:sqlite:end
|
|
134
|
+
|
|
135
|
+
callback?.();
|
|
136
|
+
} catch (error) {
|
|
137
|
+
callback?.(error);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async destroy(
|
|
142
|
+
sessionId: string,
|
|
143
|
+
callback?: StoreCallback,
|
|
144
|
+
): Promise<void> {
|
|
145
|
+
try {
|
|
146
|
+
await this.database
|
|
147
|
+
.delete(sessions)
|
|
148
|
+
.where(eq(sessions.id, sessionId));
|
|
149
|
+
|
|
150
|
+
callback?.();
|
|
151
|
+
} catch (error) {
|
|
152
|
+
callback?.(error);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async touch(
|
|
157
|
+
sessionId: string,
|
|
158
|
+
sessionData: SessionData,
|
|
159
|
+
callback?: StoreCallback,
|
|
160
|
+
): Promise<void> {
|
|
161
|
+
try {
|
|
162
|
+
await this.database
|
|
163
|
+
.update(sessions)
|
|
164
|
+
.set({
|
|
165
|
+
expiredAt:
|
|
166
|
+
this.resolveExpiration(sessionData),
|
|
167
|
+
json: JSON.stringify(sessionData),
|
|
168
|
+
})
|
|
169
|
+
.where(eq(sessions.id, sessionId));
|
|
170
|
+
|
|
171
|
+
callback?.();
|
|
172
|
+
} catch (error) {
|
|
173
|
+
callback?.(error);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async all(
|
|
178
|
+
callback: AllCallback,
|
|
179
|
+
): Promise<void> {
|
|
180
|
+
try {
|
|
181
|
+
const storedSessions =
|
|
182
|
+
await this.database
|
|
183
|
+
.select({
|
|
184
|
+
json: sessions.json,
|
|
185
|
+
})
|
|
186
|
+
.from(sessions)
|
|
187
|
+
.where(
|
|
188
|
+
and(
|
|
189
|
+
gt(sessions.expiredAt, Date.now()),
|
|
190
|
+
isNull(sessions.destroyedAt),
|
|
191
|
+
),
|
|
192
|
+
);
|
|
193
|
+
|
|
194
|
+
const sessionData = storedSessions.map(
|
|
195
|
+
(storedSession) =>
|
|
196
|
+
JSON.parse(
|
|
197
|
+
storedSession.json,
|
|
198
|
+
) as SessionData,
|
|
199
|
+
);
|
|
200
|
+
|
|
201
|
+
callback(null, sessionData);
|
|
202
|
+
} catch (error) {
|
|
203
|
+
callback(error);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async length(
|
|
208
|
+
callback: LengthCallback,
|
|
209
|
+
): Promise<void> {
|
|
210
|
+
try {
|
|
211
|
+
const [result] = await this.database
|
|
212
|
+
.select({
|
|
213
|
+
value: count(),
|
|
214
|
+
})
|
|
215
|
+
.from(sessions)
|
|
216
|
+
.where(
|
|
217
|
+
and(
|
|
218
|
+
gt(sessions.expiredAt, Date.now()),
|
|
219
|
+
isNull(sessions.destroyedAt),
|
|
220
|
+
),
|
|
221
|
+
);
|
|
222
|
+
|
|
223
|
+
callback(null, result?.value ?? 0);
|
|
224
|
+
} catch (error) {
|
|
225
|
+
callback(error);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async clear(
|
|
230
|
+
callback?: StoreCallback,
|
|
231
|
+
): Promise<void> {
|
|
232
|
+
try {
|
|
233
|
+
await this.database.delete(sessions);
|
|
234
|
+
callback?.();
|
|
235
|
+
} catch (error) {
|
|
236
|
+
callback?.(error);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
private resolveExpiration(
|
|
241
|
+
sessionData: SessionData,
|
|
242
|
+
): number {
|
|
243
|
+
const expires = sessionData.cookie.expires;
|
|
244
|
+
|
|
245
|
+
if (expires) {
|
|
246
|
+
return new Date(expires).getTime();
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const maxAge = sessionData.cookie.maxAge;
|
|
250
|
+
|
|
251
|
+
if (
|
|
252
|
+
typeof maxAge === 'number' &&
|
|
253
|
+
maxAge > 0
|
|
254
|
+
) {
|
|
255
|
+
return Date.now() + maxAge;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
return (
|
|
259
|
+
Date.now() +
|
|
260
|
+
7 * 24 * 60 * 60 * 1000
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// nestforge:feature-file:redis,auth:password
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { createZodDto } from 'nestjs-zod';
|
|
4
|
+
|
|
5
|
+
export const forgotPasswordSchema = z.object({
|
|
6
|
+
email: z.string().email().describe('E-mail da conta a ser recuperada'),
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
export class ForgotPasswordDto extends createZodDto(forgotPasswordSchema) { }
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// nestforge:feature-file:auth:password
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { createZodDto } from 'nestjs-zod';
|
|
4
|
+
|
|
5
|
+
export const loginSchema = z.object({
|
|
6
|
+
email: z.string().email().describe('E-mail do usuário'),
|
|
7
|
+
password: z.string().min(8).describe('Senha'),
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
export class LoginDto extends createZodDto(loginSchema) { }
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// nestforge:feature-file:auth:token
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { createZodDto } from 'nestjs-zod';
|
|
4
|
+
|
|
5
|
+
export const refreshTokenSchema = z.object({
|
|
6
|
+
refreshToken: z.string().describe('Refresh token emitido no login'),
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
export class RefreshTokenDto extends createZodDto(refreshTokenSchema) { }
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// nestforge:feature-file:auth:password
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { createZodDto } from 'nestjs-zod';
|
|
4
|
+
|
|
5
|
+
export const registerSchema = z.object({
|
|
6
|
+
name: z.string().min(2).describe('Nome completo do usuário'),
|
|
7
|
+
email: z.string().email().describe('E-mail do usuário'),
|
|
8
|
+
password: z.string().min(8).describe('Senha (mínimo 8 caracteres)'),
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
export class RegisterDto extends createZodDto(registerSchema) { }
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// nestforge:feature-file:redis,auth:password
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { createZodDto } from 'nestjs-zod';
|
|
4
|
+
|
|
5
|
+
export const resetPasswordSchema = z.object({
|
|
6
|
+
token: z.string().describe('Token recebido por e-mail'),
|
|
7
|
+
password: z.string().min(8).describe('Nova senha (mínimo 8 caracteres)'),
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
export class ResetPasswordDto extends createZodDto(resetPasswordSchema) { }
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Injectable } from '@nestjs/common';
|
|
2
|
+
import { AuthGuard } from '@nestjs/passport';
|
|
3
|
+
|
|
4
|
+
@Injectable()
|
|
5
|
+
export class GithubAuthGuard extends AuthGuard('github') {
|
|
6
|
+
constructor() {
|
|
7
|
+
// API stateless (Bearer token) — não usamos sessão do Passport/Express
|
|
8
|
+
super({ session: false });
|
|
9
|
+
}
|
|
10
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Injectable } from '@nestjs/common';
|
|
2
|
+
import { AuthGuard } from '@nestjs/passport';
|
|
3
|
+
|
|
4
|
+
@Injectable()
|
|
5
|
+
export class GoogleAuthGuard extends AuthGuard('google') {
|
|
6
|
+
constructor() {
|
|
7
|
+
// API stateless (Bearer token) — não usamos sessão do Passport/Express
|
|
8
|
+
super({ session: false });
|
|
9
|
+
}
|
|
10
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// nestforge:feature-file:auth:token
|
|
2
|
+
import { ExecutionContext, Injectable } from '@nestjs/common';
|
|
3
|
+
import { Reflector } from '@nestjs/core';
|
|
4
|
+
import { AuthGuard } from '@nestjs/passport';
|
|
5
|
+
import { IS_PUBLIC_KEY } from '../../common/decorators/public.decorator';
|
|
6
|
+
|
|
7
|
+
@Injectable()
|
|
8
|
+
export class JwtAuthGuard extends AuthGuard('jwt') {
|
|
9
|
+
constructor(private reflector: Reflector) {
|
|
10
|
+
super();
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
canActivate(context: ExecutionContext) {
|
|
14
|
+
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
|
15
|
+
context.getHandler(),
|
|
16
|
+
context.getClass(),
|
|
17
|
+
]);
|
|
18
|
+
|
|
19
|
+
if (isPublic) {
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
return super.canActivate(context);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// nestforge:feature-file:auth:session
|
|
2
|
+
import {
|
|
3
|
+
ExecutionContext,
|
|
4
|
+
UnauthorizedException,
|
|
5
|
+
} from '@nestjs/common';
|
|
6
|
+
import { Reflector } from '@nestjs/core';
|
|
7
|
+
import { Request } from 'express';
|
|
8
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
9
|
+
import { SessionAuthGuard } from './session-auth.guard';
|
|
10
|
+
|
|
11
|
+
describe('SessionAuthGuard', () => {
|
|
12
|
+
let reflector: {
|
|
13
|
+
getAllAndOverride: ReturnType<typeof vi.fn>;
|
|
14
|
+
};
|
|
15
|
+
let guard: SessionAuthGuard;
|
|
16
|
+
|
|
17
|
+
beforeEach(() => {
|
|
18
|
+
reflector = {
|
|
19
|
+
getAllAndOverride: vi.fn(),
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
guard = new SessionAuthGuard(reflector as unknown as Reflector);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
function createContext(user?: {
|
|
26
|
+
id: string;
|
|
27
|
+
email: string;
|
|
28
|
+
role: string;
|
|
29
|
+
}) {
|
|
30
|
+
const request = {
|
|
31
|
+
session: {
|
|
32
|
+
user,
|
|
33
|
+
},
|
|
34
|
+
} as unknown as Request;
|
|
35
|
+
|
|
36
|
+
const context = {
|
|
37
|
+
getHandler: vi.fn(),
|
|
38
|
+
getClass: vi.fn(),
|
|
39
|
+
switchToHttp: vi.fn(() => ({
|
|
40
|
+
getRequest: () => request,
|
|
41
|
+
})),
|
|
42
|
+
} as unknown as ExecutionContext;
|
|
43
|
+
|
|
44
|
+
return { context, request };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
it('permite acesso a rotas públicas sem sessão', () => {
|
|
48
|
+
reflector.getAllAndOverride.mockReturnValue(true);
|
|
49
|
+
const { context } = createContext();
|
|
50
|
+
|
|
51
|
+
expect(guard.canActivate(context)).toBe(true);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('rejeita acesso quando não existe usuário na sessão', () => {
|
|
55
|
+
reflector.getAllAndOverride.mockReturnValue(false);
|
|
56
|
+
const { context } = createContext();
|
|
57
|
+
|
|
58
|
+
expect(() => guard.canActivate(context)).toThrow(
|
|
59
|
+
UnauthorizedException,
|
|
60
|
+
);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('permite acesso e disponibiliza o usuário autenticado', () => {
|
|
64
|
+
reflector.getAllAndOverride.mockReturnValue(false);
|
|
65
|
+
|
|
66
|
+
const user = {
|
|
67
|
+
id: 'user-1',
|
|
68
|
+
email: 'jeiel@example.com',
|
|
69
|
+
role: 'USER',
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const { context, request } = createContext(user);
|
|
73
|
+
|
|
74
|
+
expect(guard.canActivate(context)).toBe(true);
|
|
75
|
+
expect(request.user).toEqual(user);
|
|
76
|
+
});
|
|
77
|
+
});
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// nestforge:feature-file:auth:session
|
|
2
|
+
import {
|
|
3
|
+
CanActivate,
|
|
4
|
+
ExecutionContext,
|
|
5
|
+
Injectable,
|
|
6
|
+
UnauthorizedException,
|
|
7
|
+
} from '@nestjs/common';
|
|
8
|
+
import { Reflector } from '@nestjs/core';
|
|
9
|
+
import { Request } from 'express';
|
|
10
|
+
import { IS_PUBLIC_KEY } from '../../common/decorators/public.decorator';
|
|
11
|
+
|
|
12
|
+
@Injectable()
|
|
13
|
+
export class SessionAuthGuard implements CanActivate {
|
|
14
|
+
constructor(private readonly reflector: Reflector) { }
|
|
15
|
+
|
|
16
|
+
canActivate(context: ExecutionContext): boolean {
|
|
17
|
+
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
|
18
|
+
context.getHandler(),
|
|
19
|
+
context.getClass(),
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
if (isPublic) {
|
|
23
|
+
return true;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const request = context.switchToHttp().getRequest<Request>();
|
|
27
|
+
const user = request.session?.user;
|
|
28
|
+
|
|
29
|
+
if (!user) {
|
|
30
|
+
throw new UnauthorizedException('Sessão inválida ou expirada');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
request.user = user;
|
|
34
|
+
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// nestforge:feature-file:auth:session
|
|
2
|
+
import { Request } from 'express';
|
|
3
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
4
|
+
import { SessionService, SessionUser } from './session.service';
|
|
5
|
+
|
|
6
|
+
describe('SessionService', () => {
|
|
7
|
+
let sessionService: SessionService;
|
|
8
|
+
|
|
9
|
+
beforeEach(() => {
|
|
10
|
+
sessionService = new SessionService();
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
function createRequest() {
|
|
14
|
+
const session = {
|
|
15
|
+
user: undefined,
|
|
16
|
+
csrfToken: undefined as string | undefined,
|
|
17
|
+
regenerate: vi.fn(
|
|
18
|
+
(callback: (error?: Error) => void) => callback(),
|
|
19
|
+
),
|
|
20
|
+
save: vi.fn(
|
|
21
|
+
(callback: (error?: Error) => void) => callback(),
|
|
22
|
+
),
|
|
23
|
+
destroy: vi.fn(
|
|
24
|
+
(callback: (error?: Error) => void) => callback(),
|
|
25
|
+
),
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
return {
|
|
29
|
+
request: { session } as unknown as Request,
|
|
30
|
+
session,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
it('regenera, preenche e salva a sessão', async () => {
|
|
35
|
+
const { request, session } = createRequest();
|
|
36
|
+
const user: SessionUser = {
|
|
37
|
+
id: 'user-1',
|
|
38
|
+
email: 'jeiel@example.com',
|
|
39
|
+
role: 'USER',
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const result = await sessionService.establish(request, user);
|
|
43
|
+
|
|
44
|
+
expect(session.regenerate).toHaveBeenCalledOnce();
|
|
45
|
+
expect(session.user).toEqual(user);
|
|
46
|
+
expect(session.save).toHaveBeenCalledOnce();
|
|
47
|
+
expect(session.csrfToken).toMatch(/^[a-f0-9]{64}$/);
|
|
48
|
+
expect(result).toEqual({
|
|
49
|
+
user,
|
|
50
|
+
csrfToken: session.csrfToken,
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('emite e salva um novo token CSRF', async () => {
|
|
55
|
+
const { request, session } = createRequest();
|
|
56
|
+
|
|
57
|
+
const result = await sessionService.issueCsrfToken(request);
|
|
58
|
+
|
|
59
|
+
expect(result.csrfToken).toMatch(/^[a-f0-9]{64}$/);
|
|
60
|
+
expect(session.csrfToken).toBe(result.csrfToken);
|
|
61
|
+
expect(session.save).toHaveBeenCalledOnce();
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it('destrói a sessão atual', async () => {
|
|
65
|
+
const { request, session } = createRequest();
|
|
66
|
+
|
|
67
|
+
const result = await sessionService.destroy(request);
|
|
68
|
+
|
|
69
|
+
expect(session.destroy).toHaveBeenCalledOnce();
|
|
70
|
+
expect(result).toEqual({
|
|
71
|
+
message: 'Logout realizado com sucesso',
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
});
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// nestforge:feature-file:auth:session
|
|
2
|
+
import {
|
|
3
|
+
Injectable,
|
|
4
|
+
InternalServerErrorException,
|
|
5
|
+
} from '@nestjs/common';
|
|
6
|
+
import { Request } from 'express';
|
|
7
|
+
import { randomBytes } from 'node:crypto';
|
|
8
|
+
|
|
9
|
+
export interface SessionUser {
|
|
10
|
+
id: string;
|
|
11
|
+
email: string;
|
|
12
|
+
role: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
@Injectable()
|
|
16
|
+
export class SessionService {
|
|
17
|
+
async establish(request: Request, user: SessionUser) {
|
|
18
|
+
await this.regenerate(request);
|
|
19
|
+
|
|
20
|
+
const csrfToken = this.generateCsrfToken();
|
|
21
|
+
|
|
22
|
+
request.session.user = user;
|
|
23
|
+
request.session.csrfToken = csrfToken;
|
|
24
|
+
|
|
25
|
+
await this.save(request);
|
|
26
|
+
|
|
27
|
+
return { user, csrfToken };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async issueCsrfToken(request: Request) {
|
|
31
|
+
const csrfToken = this.generateCsrfToken();
|
|
32
|
+
|
|
33
|
+
request.session.csrfToken = csrfToken;
|
|
34
|
+
|
|
35
|
+
await this.save(request);
|
|
36
|
+
|
|
37
|
+
return { csrfToken };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
private generateCsrfToken(): string {
|
|
41
|
+
return randomBytes(32).toString('hex');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async destroy(request: Request) {
|
|
45
|
+
await new Promise<void>((resolve, reject) => {
|
|
46
|
+
request.session.destroy((error) => {
|
|
47
|
+
if (error) {
|
|
48
|
+
reject(
|
|
49
|
+
new InternalServerErrorException(
|
|
50
|
+
'Não foi possível encerrar a sessão',
|
|
51
|
+
),
|
|
52
|
+
);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
resolve();
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
return { message: 'Logout realizado com sucesso' };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
private async regenerate(request: Request): Promise<void> {
|
|
64
|
+
await new Promise<void>((resolve, reject) => {
|
|
65
|
+
request.session.regenerate((error) => {
|
|
66
|
+
if (error) {
|
|
67
|
+
reject(
|
|
68
|
+
new InternalServerErrorException(
|
|
69
|
+
'Não foi possível iniciar a sessão',
|
|
70
|
+
),
|
|
71
|
+
);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
resolve();
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
private async save(request: Request): Promise<void> {
|
|
81
|
+
await new Promise<void>((resolve, reject) => {
|
|
82
|
+
request.session.save((error) => {
|
|
83
|
+
if (error) {
|
|
84
|
+
reject(
|
|
85
|
+
new InternalServerErrorException(
|
|
86
|
+
'Não foi possível salvar a sessão',
|
|
87
|
+
),
|
|
88
|
+
);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
resolve();
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { Injectable } from '@nestjs/common';
|
|
2
|
+
import { PassportStrategy } from '@nestjs/passport';
|
|
3
|
+
import { Strategy, Profile } from 'passport-github2';
|
|
4
|
+
import { OAuthProfile } from './google.strategy';
|
|
5
|
+
import { ConfigService } from '@nestjs/config';
|
|
6
|
+
|
|
7
|
+
@Injectable()
|
|
8
|
+
export class GithubStrategy extends PassportStrategy(Strategy, 'github') {
|
|
9
|
+
constructor(configService: ConfigService) {
|
|
10
|
+
super({
|
|
11
|
+
clientID: configService.getOrThrow<string>('GITHUB_CLIENT_ID'),
|
|
12
|
+
clientSecret: configService.getOrThrow<string>(
|
|
13
|
+
'GITHUB_CLIENT_SECRET',
|
|
14
|
+
),
|
|
15
|
+
callbackURL: `${configService.getOrThrow<string>(
|
|
16
|
+
'APP_URL',
|
|
17
|
+
)}/auth/github/callback`,
|
|
18
|
+
scope: ['user:email'],
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async validate(
|
|
23
|
+
_accessToken: string,
|
|
24
|
+
_refreshToken: string,
|
|
25
|
+
profile: Profile,
|
|
26
|
+
done: (error: unknown, user?: OAuthProfile) => void,
|
|
27
|
+
) {
|
|
28
|
+
// o e-mail pode vir vazio se o usuário deixou o e-mail privado no GitHub
|
|
29
|
+
const email =
|
|
30
|
+
profile.emails?.[0]?.value ?? `${profile.username}@users.noreply.github.com`;
|
|
31
|
+
|
|
32
|
+
const oauthProfile: OAuthProfile = {
|
|
33
|
+
provider: 'github',
|
|
34
|
+
providerUserId: profile.id,
|
|
35
|
+
email,
|
|
36
|
+
name: profile.displayName || profile.username || 'Usuário GitHub',
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
done(null, oauthProfile);
|
|
40
|
+
}
|
|
41
|
+
}
|