@ftisindia/create-app 0.1.3 → 0.1.5
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/package.json +1 -1
- package/template/.env.example +6 -0
- package/template/README.md +11 -1
- package/template/_package.json +0 -2
- package/template/docs/API_REFERENCE.md +13 -0
- package/template/docs/OAUTH.md +7 -3
- package/template/scripts/gen-module.mjs +2 -0
- package/template/src/app.module.ts +16 -22
- package/template/src/common/dto/error-response.dto.ts +3 -3
- package/template/src/common/dto/membership-response.dto.ts +26 -14
- package/template/src/common/dto/mutation-response.dto.ts +1 -1
- package/template/src/common/dto/pagination-query.dto.ts +37 -0
- package/template/src/common/dto/role-summary.dto.ts +5 -5
- package/template/src/common/dto/user-summary.dto.ts +6 -6
- package/template/src/common/filters/http-exception.filter.ts +9 -19
- package/template/src/common/swagger/api-error-responses.ts +12 -12
- package/template/src/config/app.config.ts +8 -3
- package/template/src/config/auth.config.ts +3 -3
- package/template/src/config/database.config.ts +3 -3
- package/template/src/config/env.validation.ts +78 -40
- package/template/src/config/index.ts +5 -5
- package/template/src/config/rbac.config.ts +3 -3
- package/template/src/database/prisma/prisma-transaction.ts +1 -1
- package/template/src/database/prisma/prisma.module.ts +2 -2
- package/template/src/database/prisma/prisma.service.ts +3 -6
- package/template/src/main.ts +24 -11
- package/template/src/modules/access-control/access-control.module.ts +11 -10
- package/template/src/modules/access-control/application/role-permission-policy.ts +71 -0
- package/template/src/modules/access-control/application/route-registry.validator.ts +34 -63
- package/template/src/modules/access-control/application/services/ability.factory.ts +5 -9
- package/template/src/modules/access-control/application/services/access-control.service.ts +78 -85
- package/template/src/modules/access-control/application/services/permission.guard.ts +16 -21
- package/template/src/modules/access-control/application/services/rbac-cache.service.ts +7 -9
- package/template/src/modules/access-control/dto/access-control-response.dto.ts +32 -20
- package/template/src/modules/access-control/dto/create-role.dto.ts +6 -6
- package/template/src/modules/access-control/dto/current-access-control-response.dto.ts +31 -0
- package/template/src/modules/access-control/dto/update-role-permissions.dto.ts +3 -10
- package/template/src/modules/access-control/dto/update-role.dto.ts +6 -6
- package/template/src/modules/access-control/presentation/access-control.controller.ts +69 -74
- package/template/src/modules/access-control/presentation/current-access-control.controller.ts +40 -0
- package/template/src/modules/access-control/presentation/permissions.decorator.ts +3 -3
- package/template/src/modules/access-control/presentation/public.decorator.ts +2 -2
- package/template/src/modules/access-control/types/permission-key.ts +19 -19
- package/template/src/modules/access-control/types/route-permission-registry.ts +76 -76
- package/template/src/modules/audit/application/services/audit.service.ts +7 -7
- package/template/src/modules/audit/audit.module.ts +4 -4
- package/template/src/modules/audit/dto/audit-response.dto.ts +18 -18
- package/template/src/modules/audit/dto/list-audit-logs-query.dto.ts +14 -14
- package/template/src/modules/audit/presentation/audit.controller.ts +17 -23
- package/template/src/modules/auth/application/services/auth.service.ts +147 -110
- package/template/src/modules/auth/application/services/password.service.ts +2 -2
- package/template/src/modules/auth/application/services/token.service.ts +20 -21
- package/template/src/modules/auth/auth.module.ts +20 -47
- package/template/src/modules/auth/dto/auth-response.dto.ts +9 -10
- package/template/src/modules/auth/dto/login.dto.ts +4 -4
- package/template/src/modules/auth/dto/logout.dto.ts +1 -1
- package/template/src/modules/auth/dto/oauth-exchange.dto.ts +4 -5
- package/template/src/modules/auth/dto/refresh-token.dto.ts +4 -5
- package/template/src/modules/auth/dto/signup.dto.ts +5 -11
- package/template/src/modules/auth/infrastructure/passport/google-auth.guard.ts +6 -14
- package/template/src/modules/auth/infrastructure/passport/google-oauth-state.store.ts +98 -0
- package/template/src/modules/auth/infrastructure/passport/google.strategy.ts +21 -30
- package/template/src/modules/auth/infrastructure/passport/jwt-auth.guard.ts +3 -3
- package/template/src/modules/auth/infrastructure/passport/jwt.strategy.ts +11 -11
- package/template/src/modules/auth/presentation/auth.controller.ts +45 -45
- package/template/src/modules/auth/presentation/current-user.decorator.ts +3 -5
- package/template/src/modules/auth/presentation/google-oauth-exception.filter.ts +5 -10
- package/template/src/modules/health/dto/health-response.dto.ts +5 -5
- package/template/src/modules/health/health.module.ts +2 -2
- package/template/src/modules/health/presentation/health.controller.ts +13 -13
- package/template/src/modules/invitations/application/services/invitations.service.ts +127 -176
- package/template/src/modules/invitations/dto/accept-invitation.dto.ts +6 -7
- package/template/src/modules/invitations/dto/create-invitation.dto.ts +14 -15
- package/template/src/modules/invitations/dto/invitation-response.dto.ts +37 -29
- package/template/src/modules/invitations/dto/invitation-token.dto.ts +4 -4
- package/template/src/modules/invitations/invitations.module.ts +5 -5
- package/template/src/modules/invitations/presentation/invitations.controller.ts +61 -63
- package/template/src/modules/memberships/application/services/memberships.service.ts +70 -84
- package/template/src/modules/memberships/dto/transfer-owner.dto.ts +4 -4
- package/template/src/modules/memberships/dto/update-billing-contact.dto.ts +2 -2
- package/template/src/modules/memberships/dto/update-membership-owner.dto.ts +2 -2
- package/template/src/modules/memberships/dto/update-membership-role.dto.ts +4 -4
- package/template/src/modules/memberships/dto/update-membership-status.dto.ts +3 -3
- package/template/src/modules/memberships/memberships.module.ts +4 -4
- package/template/src/modules/memberships/presentation/memberships.controller.ts +83 -99
- package/template/src/modules/organisations/application/services/organisations.service.ts +87 -23
- package/template/src/modules/organisations/dto/create-organisation.dto.ts +6 -13
- package/template/src/modules/organisations/dto/organisation-response.dto.ts +65 -14
- package/template/src/modules/organisations/infrastructure/repositories/organisations.repository.ts +4 -7
- package/template/src/modules/organisations/organisations.module.ts +5 -5
- package/template/src/modules/organisations/presentation/organisations.controller.ts +31 -18
- package/template/src/modules/organisations/types/default-organisation-data.ts +3 -9
- package/template/src/modules/request-context/application/services/request-context.service.ts +15 -7
- package/template/src/modules/request-context/presentation/org-scope.guard.ts +4 -9
- package/template/src/modules/request-context/presentation/request-context.interceptor.ts +4 -9
- package/template/src/modules/request-context/presentation/request-context.middleware.ts +7 -8
- package/template/src/modules/request-context/request-context.module.ts +7 -7
- package/template/src/modules/request-context/types/request-context.ts +2 -2
- package/template/src/modules/sample/application/services/sample.service.ts +10 -8
- package/template/src/modules/sample/dto/sample-echo.dto.ts +3 -3
- package/template/src/modules/sample/dto/sample-response.dto.ts +12 -12
- package/template/src/modules/sample/presentation/sample.controller.ts +25 -42
- package/template/src/modules/sample/sample.module.ts +4 -4
- package/template/src/modules/settings/application/services/settings.service.ts +15 -27
- package/template/src/modules/settings/dto/setting-response.dto.ts +9 -9
- package/template/src/modules/settings/dto/update-setting.dto.ts +5 -5
- package/template/src/modules/settings/presentation/settings.controller.ts +29 -35
- package/template/src/modules/settings/settings.module.ts +5 -5
- package/template/src/modules/settings/types/setting-definitions.ts +49 -33
- package/template/test/auth-refresh.spec.ts +90 -0
- package/template/test/frontend-bootstrap.spec.ts +181 -0
- package/template/test/role-permission-policy.spec.ts +94 -0
- package/template/test/route-registry.validator.spec.ts +12 -0
- package/template/test/security.e2e-spec.ts +134 -2
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { randomBytes, createHash } from
|
|
2
|
-
import { InternalServerErrorException, Injectable } from
|
|
3
|
-
import { ConfigService } from
|
|
4
|
-
import { JwtService } from
|
|
5
|
-
import { Prisma } from
|
|
6
|
-
import { PrismaService } from
|
|
7
|
-
import { JwtPayload } from
|
|
1
|
+
import { randomBytes, createHash } from 'node:crypto';
|
|
2
|
+
import { InternalServerErrorException, Injectable } from '@nestjs/common';
|
|
3
|
+
import { ConfigService } from '@nestjs/config';
|
|
4
|
+
import { JwtService } from '@nestjs/jwt';
|
|
5
|
+
import { Prisma } from '@prisma/client';
|
|
6
|
+
import { PrismaService } from '../../../../database/prisma/prisma.service';
|
|
7
|
+
import { JwtPayload } from '../../types/jwt-payload';
|
|
8
8
|
|
|
9
9
|
type TokenUser = {
|
|
10
10
|
id: string;
|
|
@@ -31,17 +31,14 @@ export class TokenService {
|
|
|
31
31
|
|
|
32
32
|
return this.jwt.signAsync(payload, {
|
|
33
33
|
expiresIn: this.getAccessTokenTtl() as never,
|
|
34
|
-
algorithm:
|
|
35
|
-
issuer: this.config.get<string>(
|
|
36
|
-
audience: this.config.get<string>(
|
|
34
|
+
algorithm: 'HS256',
|
|
35
|
+
issuer: this.config.get<string>('auth.jwt.issuer'),
|
|
36
|
+
audience: this.config.get<string>('auth.jwt.audience'),
|
|
37
37
|
});
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
async createRefreshToken(
|
|
41
|
-
|
|
42
|
-
client: RefreshTokenStore = this.prisma,
|
|
43
|
-
) {
|
|
44
|
-
const refreshToken = randomBytes(48).toString("base64url");
|
|
40
|
+
async createRefreshToken(userId: string, client: RefreshTokenStore = this.prisma) {
|
|
41
|
+
const refreshToken = randomBytes(48).toString('base64url');
|
|
45
42
|
const tokenHash = this.hashRefreshToken(refreshToken);
|
|
46
43
|
const expiresAt = this.getRefreshTokenExpiry();
|
|
47
44
|
|
|
@@ -60,15 +57,19 @@ export class TokenService {
|
|
|
60
57
|
}
|
|
61
58
|
|
|
62
59
|
hashRefreshToken(refreshToken: string) {
|
|
63
|
-
return createHash(
|
|
60
|
+
return createHash('sha256').update(refreshToken).digest('hex');
|
|
64
61
|
}
|
|
65
62
|
|
|
66
63
|
getAccessTokenTtl() {
|
|
67
|
-
return this.config.get<string>(
|
|
64
|
+
return this.config.get<string>('auth.jwt.accessExpiresIn') ?? '15m';
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
getAccessTokenTtlSeconds() {
|
|
68
|
+
return Math.floor(parseDurationToMs(this.getAccessTokenTtl()) / 1000);
|
|
68
69
|
}
|
|
69
70
|
|
|
70
71
|
private getRefreshTokenExpiry() {
|
|
71
|
-
const ttl = this.config.get<string>(
|
|
72
|
+
const ttl = this.config.get<string>('auth.jwt.refreshExpiresIn') ?? '7d';
|
|
72
73
|
return new Date(Date.now() + parseDurationToMs(ttl));
|
|
73
74
|
}
|
|
74
75
|
}
|
|
@@ -76,9 +77,7 @@ export class TokenService {
|
|
|
76
77
|
function parseDurationToMs(value: string) {
|
|
77
78
|
const match = /^(\d+)([smhdw])$/.exec(value.trim());
|
|
78
79
|
if (!match) {
|
|
79
|
-
throw new InternalServerErrorException(
|
|
80
|
-
`Unsupported duration value: ${value}`,
|
|
81
|
-
);
|
|
80
|
+
throw new InternalServerErrorException(`Unsupported duration value: ${value}`);
|
|
82
81
|
}
|
|
83
82
|
|
|
84
83
|
const amount = Number(match[1]);
|
|
@@ -1,30 +1,31 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { ConfigModule, ConfigService } from
|
|
3
|
-
import { JwtModule } from
|
|
4
|
-
import { PassportModule } from
|
|
5
|
-
import
|
|
6
|
-
import { AuthService } from
|
|
7
|
-
import { PasswordService } from
|
|
8
|
-
import { TokenService } from
|
|
9
|
-
import { GoogleAuthGuard } from
|
|
10
|
-
import { GoogleStrategy } from
|
|
11
|
-
import { JwtAuthGuard } from
|
|
12
|
-
import { JwtStrategy } from
|
|
13
|
-
import { AuthController } from
|
|
14
|
-
import { GoogleOAuthExceptionFilter } from
|
|
1
|
+
import { Module } from '@nestjs/common';
|
|
2
|
+
import { ConfigModule, ConfigService } from '@nestjs/config';
|
|
3
|
+
import { JwtModule } from '@nestjs/jwt';
|
|
4
|
+
import { PassportModule } from '@nestjs/passport';
|
|
5
|
+
import { RequestContextModule } from '../request-context/request-context.module';
|
|
6
|
+
import { AuthService } from './application/services/auth.service';
|
|
7
|
+
import { PasswordService } from './application/services/password.service';
|
|
8
|
+
import { TokenService } from './application/services/token.service';
|
|
9
|
+
import { GoogleAuthGuard } from './infrastructure/passport/google-auth.guard';
|
|
10
|
+
import { GoogleStrategy } from './infrastructure/passport/google.strategy';
|
|
11
|
+
import { JwtAuthGuard } from './infrastructure/passport/jwt-auth.guard';
|
|
12
|
+
import { JwtStrategy } from './infrastructure/passport/jwt.strategy';
|
|
13
|
+
import { AuthController } from './presentation/auth.controller';
|
|
14
|
+
import { GoogleOAuthExceptionFilter } from './presentation/google-oauth-exception.filter';
|
|
15
15
|
|
|
16
16
|
@Module({
|
|
17
17
|
imports: [
|
|
18
18
|
PassportModule,
|
|
19
|
+
RequestContextModule,
|
|
19
20
|
JwtModule.registerAsync({
|
|
20
21
|
imports: [ConfigModule],
|
|
21
22
|
inject: [ConfigService],
|
|
22
23
|
useFactory: (config: ConfigService) => ({
|
|
23
|
-
secret: config.get<string>(
|
|
24
|
+
secret: config.get<string>('auth.jwt.secret') ?? '',
|
|
24
25
|
signOptions: {
|
|
25
|
-
algorithm:
|
|
26
|
-
issuer: config.get<string>(
|
|
27
|
-
audience: config.get<string>(
|
|
26
|
+
algorithm: 'HS256',
|
|
27
|
+
issuer: config.get<string>('auth.jwt.issuer'),
|
|
28
|
+
audience: config.get<string>('auth.jwt.audience'),
|
|
28
29
|
},
|
|
29
30
|
}),
|
|
30
31
|
}),
|
|
@@ -42,32 +43,4 @@ import { GoogleOAuthExceptionFilter } from "./presentation/google-oauth-exceptio
|
|
|
42
43
|
],
|
|
43
44
|
exports: [JwtAuthGuard, PasswordService],
|
|
44
45
|
})
|
|
45
|
-
export class AuthModule
|
|
46
|
-
constructor(private readonly config: ConfigService) {}
|
|
47
|
-
|
|
48
|
-
configure(consumer: MiddlewareConsumer) {
|
|
49
|
-
consumer
|
|
50
|
-
.apply(buildGoogleOAuthSessionMiddleware(this.config))
|
|
51
|
-
.forRoutes("auth/google", "auth/google/callback");
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function buildGoogleOAuthSessionMiddleware(config: ConfigService) {
|
|
56
|
-
const secret =
|
|
57
|
-
config.get<string>("auth.session.secret") ||
|
|
58
|
-
"google-oauth-disabled-session-secret";
|
|
59
|
-
|
|
60
|
-
return session({
|
|
61
|
-
secret,
|
|
62
|
-
name: "oauth.sid",
|
|
63
|
-
resave: false,
|
|
64
|
-
saveUninitialized: false,
|
|
65
|
-
cookie: {
|
|
66
|
-
httpOnly: true,
|
|
67
|
-
sameSite: "lax",
|
|
68
|
-
secure: config.get<string>("app.nodeEnv") === "production",
|
|
69
|
-
maxAge: 10 * 60 * 1000,
|
|
70
|
-
path: "/auth/google",
|
|
71
|
-
},
|
|
72
|
-
});
|
|
73
|
-
}
|
|
46
|
+
export class AuthModule {}
|
|
@@ -1,25 +1,24 @@
|
|
|
1
|
-
import { ApiProperty } from
|
|
2
|
-
import { ActiveUserSummaryDto } from
|
|
1
|
+
import { ApiProperty } from '@nestjs/swagger';
|
|
2
|
+
import { ActiveUserSummaryDto } from '../../../common/dto/user-summary.dto';
|
|
3
3
|
|
|
4
4
|
export class AuthTokensResponseDto {
|
|
5
5
|
@ApiProperty({
|
|
6
|
-
description:
|
|
7
|
-
example:
|
|
6
|
+
description: 'JWT access token for bearer authentication.',
|
|
7
|
+
example: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
|
|
8
8
|
})
|
|
9
9
|
accessToken!: string;
|
|
10
10
|
|
|
11
11
|
@ApiProperty({
|
|
12
|
-
description:
|
|
13
|
-
|
|
14
|
-
example: "rfr_9b2f4f8d2d9f4d65a1f4",
|
|
12
|
+
description: 'Opaque refresh token. Store it securely and send it only to auth endpoints.',
|
|
13
|
+
example: 'rfr_9b2f4f8d2d9f4d65a1f4',
|
|
15
14
|
})
|
|
16
15
|
refreshToken!: string;
|
|
17
16
|
|
|
18
|
-
@ApiProperty({ example:
|
|
19
|
-
tokenType!:
|
|
17
|
+
@ApiProperty({ example: 'Bearer' })
|
|
18
|
+
tokenType!: 'Bearer';
|
|
20
19
|
|
|
21
20
|
@ApiProperty({
|
|
22
|
-
description:
|
|
21
|
+
description: 'Access token lifetime in seconds.',
|
|
23
22
|
example: 900,
|
|
24
23
|
})
|
|
25
24
|
expiresIn!: number;
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { ApiProperty } from
|
|
2
|
-
import { IsEmail, IsString, MaxLength, MinLength } from
|
|
1
|
+
import { ApiProperty } from '@nestjs/swagger';
|
|
2
|
+
import { IsEmail, IsString, MaxLength, MinLength } from 'class-validator';
|
|
3
3
|
|
|
4
4
|
export class LoginDto {
|
|
5
|
-
@ApiProperty({ example:
|
|
5
|
+
@ApiProperty({ example: 'owner@example.com' })
|
|
6
6
|
@IsEmail()
|
|
7
7
|
@MaxLength(320)
|
|
8
8
|
email!: string;
|
|
9
9
|
|
|
10
|
-
@ApiProperty({ example:
|
|
10
|
+
@ApiProperty({ example: 'dev-password-123' })
|
|
11
11
|
@IsString()
|
|
12
12
|
@MinLength(8)
|
|
13
13
|
@MaxLength(128)
|
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import { ApiProperty } from
|
|
2
|
-
import { IsString, Length } from
|
|
1
|
+
import { ApiProperty } from '@nestjs/swagger';
|
|
2
|
+
import { IsString, Length } from 'class-validator';
|
|
3
3
|
|
|
4
4
|
export class OAuthExchangeDto {
|
|
5
5
|
@ApiProperty({
|
|
6
|
-
description:
|
|
7
|
-
|
|
8
|
-
example: "DXB2rcx5HcKXy35bA3AzYdVq2e4nGsgYeG3D9M7uAQM",
|
|
6
|
+
description: 'One-time code returned to the frontend by the Google OAuth callback redirect.',
|
|
7
|
+
example: 'DXB2rcx5HcKXy35bA3AzYdVq2e4nGsgYeG3D9M7uAQM',
|
|
9
8
|
minLength: 32,
|
|
10
9
|
maxLength: 256,
|
|
11
10
|
})
|
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import { ApiProperty } from
|
|
2
|
-
import { IsString, MinLength } from
|
|
1
|
+
import { ApiProperty } from '@nestjs/swagger';
|
|
2
|
+
import { IsString, MinLength } from 'class-validator';
|
|
3
3
|
|
|
4
4
|
export class RefreshTokenDto {
|
|
5
5
|
@ApiProperty({
|
|
6
|
-
description:
|
|
7
|
-
|
|
8
|
-
example: "rfr_9b2f4f8d2d9f4d65a1f4",
|
|
6
|
+
description: 'Opaque refresh token returned by signup, login, refresh, or OAuth exchange.',
|
|
7
|
+
example: 'rfr_9b2f4f8d2d9f4d65a1f4',
|
|
9
8
|
minLength: 32,
|
|
10
9
|
})
|
|
11
10
|
@IsString()
|
|
@@ -1,25 +1,19 @@
|
|
|
1
|
-
import { ApiProperty, ApiPropertyOptional } from
|
|
2
|
-
import {
|
|
3
|
-
IsEmail,
|
|
4
|
-
IsOptional,
|
|
5
|
-
IsString,
|
|
6
|
-
MaxLength,
|
|
7
|
-
MinLength,
|
|
8
|
-
} from "class-validator";
|
|
1
|
+
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
|
2
|
+
import { IsEmail, IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
|
|
9
3
|
|
|
10
4
|
export class SignupDto {
|
|
11
|
-
@ApiProperty({ example:
|
|
5
|
+
@ApiProperty({ example: 'owner@example.com' })
|
|
12
6
|
@IsEmail()
|
|
13
7
|
@MaxLength(320)
|
|
14
8
|
email!: string;
|
|
15
9
|
|
|
16
|
-
@ApiProperty({ minLength: 8, maxLength: 128, example:
|
|
10
|
+
@ApiProperty({ minLength: 8, maxLength: 128, example: 'dev-password-123' })
|
|
17
11
|
@IsString()
|
|
18
12
|
@MinLength(8)
|
|
19
13
|
@MaxLength(128)
|
|
20
14
|
password!: string;
|
|
21
15
|
|
|
22
|
-
@ApiPropertyOptional({ example:
|
|
16
|
+
@ApiPropertyOptional({ example: 'Starter Owner' })
|
|
23
17
|
@IsOptional()
|
|
24
18
|
@IsString()
|
|
25
19
|
@MaxLength(120)
|
|
@@ -1,25 +1,17 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
ForbiddenException,
|
|
5
|
-
Injectable,
|
|
6
|
-
} from "@nestjs/common";
|
|
7
|
-
import { ConfigService } from "@nestjs/config";
|
|
8
|
-
import { AuthGuard } from "@nestjs/passport";
|
|
1
|
+
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
|
|
2
|
+
import { ConfigService } from '@nestjs/config';
|
|
3
|
+
import { AuthGuard } from '@nestjs/passport';
|
|
9
4
|
|
|
10
5
|
@Injectable()
|
|
11
|
-
export class GoogleAuthGuard
|
|
12
|
-
extends AuthGuard("google")
|
|
13
|
-
implements CanActivate
|
|
14
|
-
{
|
|
6
|
+
export class GoogleAuthGuard extends AuthGuard('google') implements CanActivate {
|
|
15
7
|
constructor(private readonly config: ConfigService) {
|
|
16
8
|
super();
|
|
17
9
|
}
|
|
18
10
|
|
|
19
11
|
canActivate(context: ExecutionContext) {
|
|
20
|
-
const enabled = this.config.get<boolean>(
|
|
12
|
+
const enabled = this.config.get<boolean>('auth.providers.googleEnabled');
|
|
21
13
|
if (!enabled) {
|
|
22
|
-
throw new ForbiddenException(
|
|
14
|
+
throw new ForbiddenException('Google authentication is disabled.');
|
|
23
15
|
}
|
|
24
16
|
|
|
25
17
|
return super.canActivate(context);
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto';
|
|
2
|
+
|
|
3
|
+
const STATE_TTL_MS = 10 * 60 * 1000;
|
|
4
|
+
const IV_BYTES = 12;
|
|
5
|
+
const AUTH_TAG_BYTES = 16;
|
|
6
|
+
|
|
7
|
+
type StatePayload = {
|
|
8
|
+
verifier: string;
|
|
9
|
+
iat: number;
|
|
10
|
+
nonce: string;
|
|
11
|
+
state?: string;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
type StoreCallback = (error: Error | null, state?: string) => void;
|
|
15
|
+
type VerifyCallback = (error: Error | null, verifier?: false | string, state?: unknown) => void;
|
|
16
|
+
|
|
17
|
+
export class GoogleOAuthStateStore {
|
|
18
|
+
private readonly key: Buffer;
|
|
19
|
+
|
|
20
|
+
constructor(secret: string) {
|
|
21
|
+
this.key = createHash('sha256').update(secret).digest();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
store(
|
|
25
|
+
_request: unknown,
|
|
26
|
+
verifier: string,
|
|
27
|
+
state: unknown,
|
|
28
|
+
_meta: unknown,
|
|
29
|
+
callback: StoreCallback,
|
|
30
|
+
) {
|
|
31
|
+
try {
|
|
32
|
+
callback(
|
|
33
|
+
null,
|
|
34
|
+
this.encode({
|
|
35
|
+
verifier,
|
|
36
|
+
iat: Date.now(),
|
|
37
|
+
nonce: randomBytes(16).toString('base64url'),
|
|
38
|
+
state: typeof state === 'string' ? state : undefined,
|
|
39
|
+
}),
|
|
40
|
+
);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
callback(error instanceof Error ? error : new Error('Could not store OAuth state.'));
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
verify(_request: unknown, providedState: string, _meta: unknown, callback: VerifyCallback) {
|
|
47
|
+
try {
|
|
48
|
+
const payload = this.decode(providedState);
|
|
49
|
+
if (Date.now() - payload.iat > STATE_TTL_MS) {
|
|
50
|
+
callback(null, false, { message: 'OAuth state expired.' });
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
callback(null, payload.verifier, payload.state);
|
|
55
|
+
} catch {
|
|
56
|
+
callback(null, false, { message: 'Invalid authorization request state.' });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
private encode(payload: StatePayload) {
|
|
61
|
+
const iv = randomBytes(IV_BYTES);
|
|
62
|
+
const cipher = createCipheriv('aes-256-gcm', this.key, iv);
|
|
63
|
+
const encrypted = Buffer.concat([
|
|
64
|
+
cipher.update(JSON.stringify(payload), 'utf8'),
|
|
65
|
+
cipher.final(),
|
|
66
|
+
]);
|
|
67
|
+
const tag = cipher.getAuthTag();
|
|
68
|
+
|
|
69
|
+
return Buffer.concat([iv, tag, encrypted]).toString('base64url');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private decode(state: string): StatePayload {
|
|
73
|
+
const input = Buffer.from(state, 'base64url');
|
|
74
|
+
if (input.length <= IV_BYTES + AUTH_TAG_BYTES) {
|
|
75
|
+
throw new Error('OAuth state is malformed.');
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const iv = input.subarray(0, IV_BYTES);
|
|
79
|
+
const tag = input.subarray(IV_BYTES, IV_BYTES + AUTH_TAG_BYTES);
|
|
80
|
+
const encrypted = input.subarray(IV_BYTES + AUTH_TAG_BYTES);
|
|
81
|
+
const decipher = createDecipheriv('aes-256-gcm', this.key, iv);
|
|
82
|
+
decipher.setAuthTag(tag);
|
|
83
|
+
|
|
84
|
+
const decoded = JSON.parse(
|
|
85
|
+
Buffer.concat([decipher.update(encrypted), decipher.final()]).toString('utf8'),
|
|
86
|
+
) as Partial<StatePayload>;
|
|
87
|
+
|
|
88
|
+
if (
|
|
89
|
+
typeof decoded.verifier !== 'string' ||
|
|
90
|
+
typeof decoded.iat !== 'number' ||
|
|
91
|
+
typeof decoded.nonce !== 'string'
|
|
92
|
+
) {
|
|
93
|
+
throw new Error('OAuth state is invalid.');
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return decoded as StatePayload;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
@@ -1,49 +1,40 @@
|
|
|
1
|
-
import { Injectable, UnauthorizedException } from
|
|
2
|
-
import { ConfigService } from
|
|
3
|
-
import { PassportStrategy } from
|
|
4
|
-
import { Profile, Strategy, VerifyCallback } from
|
|
5
|
-
import { GoogleAuthProfile } from
|
|
1
|
+
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
|
2
|
+
import { ConfigService } from '@nestjs/config';
|
|
3
|
+
import { PassportStrategy } from '@nestjs/passport';
|
|
4
|
+
import { Profile, Strategy, VerifyCallback } from 'passport-google-oauth20';
|
|
5
|
+
import { GoogleAuthProfile } from '../../types/google-auth-profile';
|
|
6
|
+
import { GoogleOAuthStateStore } from './google-oauth-state.store';
|
|
6
7
|
|
|
7
8
|
@Injectable()
|
|
8
|
-
export class GoogleStrategy extends PassportStrategy(Strategy,
|
|
9
|
+
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
|
|
9
10
|
constructor(config: ConfigService) {
|
|
10
|
-
const enabled = config.get<boolean>(
|
|
11
|
+
const enabled = config.get<boolean>('auth.providers.googleEnabled');
|
|
12
|
+
const sessionSecret =
|
|
13
|
+
config.get<string>('auth.session.secret') || 'google-oauth-disabled-session-secret';
|
|
11
14
|
|
|
12
15
|
super({
|
|
13
|
-
clientID: enabled
|
|
14
|
-
? (config.get<string>("auth.google.clientId") ?? "")
|
|
15
|
-
: "google-disabled",
|
|
16
|
+
clientID: enabled ? (config.get<string>('auth.google.clientId') ?? '') : 'google-disabled',
|
|
16
17
|
clientSecret: enabled
|
|
17
|
-
? (config.get<string>(
|
|
18
|
-
:
|
|
18
|
+
? (config.get<string>('auth.google.clientSecret') ?? '')
|
|
19
|
+
: 'google-disabled',
|
|
19
20
|
callbackURL:
|
|
20
|
-
config.get<string>(
|
|
21
|
-
|
|
21
|
+
config.get<string>('auth.google.callbackUrl') ??
|
|
22
|
+
'http://localhost:3000/auth/google/callback',
|
|
22
23
|
state: true,
|
|
23
24
|
pkce: true,
|
|
24
|
-
|
|
25
|
-
|
|
25
|
+
store: new GoogleOAuthStateStore(sessionSecret),
|
|
26
|
+
scope: ['email', 'profile'],
|
|
27
|
+
} as never);
|
|
26
28
|
}
|
|
27
29
|
|
|
28
|
-
validate(
|
|
29
|
-
_accessToken: string,
|
|
30
|
-
_refreshToken: string,
|
|
31
|
-
profile: Profile,
|
|
32
|
-
done: VerifyCallback,
|
|
33
|
-
) {
|
|
30
|
+
validate(_accessToken: string, _refreshToken: string, profile: Profile, done: VerifyCallback) {
|
|
34
31
|
const email = profile.emails?.[0]?.value?.trim().toLowerCase();
|
|
35
32
|
if (!email) {
|
|
36
|
-
done(
|
|
37
|
-
new UnauthorizedException(
|
|
38
|
-
"Google account did not provide an email address.",
|
|
39
|
-
),
|
|
40
|
-
);
|
|
33
|
+
done(new UnauthorizedException('Google account did not provide an email address.'));
|
|
41
34
|
return;
|
|
42
35
|
}
|
|
43
36
|
|
|
44
|
-
const profileJson = profile._json as
|
|
45
|
-
| { email_verified?: boolean }
|
|
46
|
-
| undefined;
|
|
37
|
+
const profileJson = profile._json as { email_verified?: boolean } | undefined;
|
|
47
38
|
const result: GoogleAuthProfile = {
|
|
48
39
|
providerUserId: profile.id,
|
|
49
40
|
email,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Injectable } from
|
|
2
|
-
import { AuthGuard } from
|
|
1
|
+
import { Injectable } from '@nestjs/common';
|
|
2
|
+
import { AuthGuard } from '@nestjs/passport';
|
|
3
3
|
|
|
4
4
|
@Injectable()
|
|
5
|
-
export class JwtAuthGuard extends AuthGuard(
|
|
5
|
+
export class JwtAuthGuard extends AuthGuard('jwt') {}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { Injectable, UnauthorizedException } from
|
|
2
|
-
import { ConfigService } from
|
|
3
|
-
import { PassportStrategy } from
|
|
4
|
-
import { ExtractJwt, Strategy } from
|
|
5
|
-
import { PrismaService } from
|
|
6
|
-
import { AuthenticatedUser } from
|
|
7
|
-
import { JwtPayload } from
|
|
1
|
+
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
|
2
|
+
import { ConfigService } from '@nestjs/config';
|
|
3
|
+
import { PassportStrategy } from '@nestjs/passport';
|
|
4
|
+
import { ExtractJwt, Strategy } from 'passport-jwt';
|
|
5
|
+
import { PrismaService } from '../../../../database/prisma/prisma.service';
|
|
6
|
+
import { AuthenticatedUser } from '../../types/authenticated-user';
|
|
7
|
+
import { JwtPayload } from '../../types/jwt-payload';
|
|
8
8
|
|
|
9
9
|
@Injectable()
|
|
10
10
|
export class JwtStrategy extends PassportStrategy(Strategy) {
|
|
@@ -15,10 +15,10 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
|
|
15
15
|
super({
|
|
16
16
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
17
17
|
ignoreExpiration: false,
|
|
18
|
-
algorithms: [
|
|
19
|
-
issuer: config.get<string>(
|
|
20
|
-
audience: config.get<string>(
|
|
21
|
-
secretOrKey: config.get<string>(
|
|
18
|
+
algorithms: ['HS256'],
|
|
19
|
+
issuer: config.get<string>('auth.jwt.issuer'),
|
|
20
|
+
audience: config.get<string>('auth.jwt.audience'),
|
|
21
|
+
secretOrKey: config.get<string>('auth.jwt.secret') ?? '',
|
|
22
22
|
});
|
|
23
23
|
}
|
|
24
24
|
|