Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ lerna-debug.log*

# IDE - VSCode
.vscode/*
.claude
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
Expand All @@ -47,4 +48,4 @@ lerna-debug.log*

# Prisma
/prisma/.env
/prisma/migrations/dev
/prisma/migrations/dev
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "nestjs-template",
"version": "0.1.0",
"version": "2.0.1",
"description": "A comprehensive NestJS template with Clean Architecture, DDD, CQRS, JWT authentication, role-based authorization, email verification, PostgreSQL, and Prisma ORM",
"author": "Valerii Checha",
"email": "chechavalera@gmail.com",
Expand Down
22 changes: 22 additions & 0 deletions prisma/migrations/20250919080323_init/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
-- CreateTable
CREATE TABLE "File" (
"id" TEXT NOT NULL,
"filename" TEXT NOT NULL,
"originalName" TEXT NOT NULL,
"path" TEXT NOT NULL,
"mimeType" TEXT NOT NULL,
"size" INTEGER NOT NULL,
"bucket" TEXT NOT NULL,
"userId" TEXT,
"isPublic" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,

CONSTRAINT "File_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE INDEX "File_userId_idx" ON "File"("userId");

-- AddForeignKey
ALTER TABLE "File" ADD CONSTRAINT "File_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
86 changes: 54 additions & 32 deletions prisma/seed.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { PrismaClient } from '@prisma/client';
import * as bcrypt from 'bcrypt';
import { ResourceType, ActionType } from '../src/core/value-objects/resource-action.vo';

// Roles
const roles = [
Expand All @@ -20,80 +21,101 @@ const permissions = [
{
name: 'user:read',
description: 'Can read user information',
resource: 'user',
action: 'read',
resource: ResourceType.USER,
action: ActionType.READ,
},
{
name: 'user:write',
description: 'Can create and update user information',
resource: 'user',
action: 'write',
name: 'user:create',
description: 'Can create users',
resource: ResourceType.USER,
action: ActionType.CREATE,
},
{
name: 'user:update',
description: 'Can update user information',
resource: ResourceType.USER,
action: ActionType.UPDATE,
},
{
name: 'user:delete',
description: 'Can delete users',
resource: 'user',
action: 'delete',
resource: ResourceType.USER,
action: ActionType.DELETE,
},
{
name: 'role:read',
description: 'Can read role information',
resource: 'role',
action: 'read',
resource: ResourceType.ROLE,
action: ActionType.READ,
},
{
name: 'role:create',
description: 'Can create roles',
resource: ResourceType.ROLE,
action: ActionType.CREATE,
},
{
name: 'role:write',
description: 'Can create and update roles',
resource: 'role',
action: 'write',
name: 'role:update',
description: 'Can update roles',
resource: ResourceType.ROLE,
action: ActionType.UPDATE,
},
{
name: 'role:delete',
description: 'Can delete roles',
resource: 'role',
action: 'delete',
resource: ResourceType.ROLE,
action: ActionType.DELETE,
},
{
name: 'storage:write',
name: 'storage:create',
description: 'Can upload files',
resource: 'file',
action: 'write',
resource: ResourceType.STORAGE,
action: ActionType.CREATE,
},
{
name: 'storage:read',
description: 'Can read file information',
resource: 'file',
action: 'read',
resource: ResourceType.STORAGE,
action: ActionType.READ,
},
{
name: 'storage:update',
description: 'Can update file information',
resource: ResourceType.STORAGE,
action: ActionType.UPDATE,
},
{
name: 'storage:delete',
description: 'Can delete files',
resource: 'file',
action: 'delete',
resource: ResourceType.STORAGE,
action: ActionType.DELETE,
},
{
name: 'storage:manage',
description: 'Can update file information',
resource: 'file',
action: 'manage',
name: 'audit:read',
description: 'Can read audit logs',
resource: ResourceType.AUDIT,
action: ActionType.READ,
},
];

// Map of role names to permissions they should have
const rolePermissionsMap = {
admin: [
'user:read',
'user:write',
'user:create',
'user:update',
'user:delete',
'role:read',
'role:write',
'role:create',
'role:update',
'role:delete',
'storage:write',
'storage:create',
'storage:read',
'storage:update',
'storage:delete',
'storage:manage',
'audit:read',
],
user: ['user:read', 'storage:manage', 'storage:write', 'storage:read'],
user: ['user:read', 'storage:create', 'storage:read', 'storage:update'],
};

// Default admin user
Expand Down
6 changes: 3 additions & 3 deletions src/application/commands/auth/disable-2fa.command.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ICommand, CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { Injectable } from '@nestjs/common';
import { AuthService } from '@core/services/auth.service';
import { IUserBaseResponse } from '@application/dtos/responses/user.response';
import { UserBaseResponse } from '@application/dtos';
import { UserMapper } from '@application/mappers/user.mapper';

export class Disable2FACommand implements ICommand {
Expand All @@ -11,11 +11,11 @@ export class Disable2FACommand implements ICommand {
@Injectable()
@CommandHandler(Disable2FACommand)
export class Disable2FACommandHandler
implements ICommandHandler<Disable2FACommand, IUserBaseResponse>
implements ICommandHandler<Disable2FACommand, UserBaseResponse>
{
constructor(private readonly authService: AuthService) {}

async execute(command: Disable2FACommand): Promise<IUserBaseResponse> {
async execute(command: Disable2FACommand): Promise<UserBaseResponse> {
const { userId } = command;

// Disable 2FA for the user
Expand Down
8 changes: 4 additions & 4 deletions src/application/commands/auth/login.command.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { Email } from '@core/value-objects/email.vo';
import { FirstName, LastName } from '@core/value-objects/name.vo';
import { Role } from '@core/entities/role.entity';
import { Permission } from '@core/entities/permission.entity';
import { ResourceAction, ActionType } from '@core/value-objects/resource-action.vo';
import { ResourceAction, ActionType, ResourceType } from '@core/value-objects/resource-action.vo';
import { I18nService } from 'nestjs-i18n';
import { LoggerService } from '@infrastructure/logger/logger.service';
import { ROLE_REPOSITORY } from '@shared/constants/tokens';
Expand Down Expand Up @@ -305,11 +305,11 @@ describe('LoginCommandHandler', () => {
// Create roles with permissions for repository responses
const userRoleWithPermissions = createRoleWithPermissions();

const adminResourceAction = new ResourceAction('user', ActionType.WRITE);
const adminResourceAction = new ResourceAction(ResourceType.USER, ActionType.UPDATE);
const adminPermission = Permission.fromData({
id: '550e8400-e29b-41d4-a716-446655440004',
resourceAction: adminResourceAction,
description: 'Can write user details',
description: 'Can update user details',
createdAt: new Date(),
updatedAt: new Date(),
});
Expand Down Expand Up @@ -351,7 +351,7 @@ describe('LoginCommandHandler', () => {
// Check that permissions from both roles are included
expect(tokenProvider.generateTokens).toHaveBeenCalledWith(
user,
expect.arrayContaining(['user:read', 'user:write']),
expect.arrayContaining(['user:read', 'user:update']),
true,
);

Expand Down
5 changes: 2 additions & 3 deletions src/application/commands/auth/login.command.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { ICommand, CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { LoginDto } from '@application/dtos/auth/login.dto';
import { AuthResponse } from '@application/dtos/responses/user.response';
import { LoginRequest, AuthResponse } from '@application/dtos';
import { UnauthorizedException, Injectable, Inject } from '@nestjs/common';
import { UserService } from '@core/services/user.service';
import { AuthService } from '@core/services/auth.service';
Expand All @@ -12,7 +11,7 @@ import { ROLE_REPOSITORY } from '@shared/constants/tokens';
import { LoggerService } from '@infrastructure/logger/logger.service';

export class LoginCommand implements ICommand {
constructor(public readonly loginDto: LoginDto) {}
constructor(public readonly loginDto: LoginRequest) {}
}

@Injectable()
Expand Down
8 changes: 4 additions & 4 deletions src/application/commands/auth/refresh-token.command.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { UserId } from '@core/value-objects/user-id.vo';
import { Token } from '@core/value-objects/token.vo';
import { Role } from '@core/entities/role.entity';
import { Permission } from '@core/entities/permission.entity';
import { ResourceAction, ActionType } from '@core/value-objects/resource-action.vo';
import { ResourceAction, ActionType, ResourceType } from '@core/value-objects/resource-action.vo';
import { USER_REPOSITORY, ROLE_REPOSITORY } from '@shared/constants/tokens';

// Mock UUID generation
Expand Down Expand Up @@ -275,11 +275,11 @@ describe('RefreshTokenCommandHandler', () => {
// Create roles with permissions for repository responses
const userRoleWithPermissions = createRoleWithPermissions();

const adminResourceAction = new ResourceAction('user', ActionType.WRITE);
const adminResourceAction = new ResourceAction(ResourceType.USER, ActionType.UPDATE);
const adminPermission = Permission.fromData({
id: '550e8400-e29b-41d4-a716-446655440004',
resourceAction: adminResourceAction,
description: 'Can write user details',
description: 'Can update user details',
createdAt: new Date(),
updatedAt: new Date(),
});
Expand Down Expand Up @@ -316,7 +316,7 @@ describe('RefreshTokenCommandHandler', () => {
// Check that JWT was signed with both permissions
expect(jwtService.sign).toHaveBeenCalledWith(
expect.objectContaining({
permissions: expect.arrayContaining(['user:read', 'user:write']),
permissions: expect.arrayContaining(['user:read', 'user:update']),
}),
expect.any(Object),
);
Expand Down
7 changes: 3 additions & 4 deletions src/application/commands/auth/refresh-token.command.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { ICommand, CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { RefreshTokenDto } from '@application/dtos/auth/refresh-token.dto';
import { IAuthRefreshTokenResponse } from '@application/dtos/responses/user.response';
import { RefreshTokenRequest, RefreshTokenResponse } from '@application/dtos';
import { UnauthorizedException, Injectable, Inject } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
Expand All @@ -11,7 +10,7 @@ import { v4 as uuidv4 } from 'uuid';
import { USER_REPOSITORY, ROLE_REPOSITORY } from '@shared/constants/tokens';

export class RefreshTokenCommand implements ICommand {
constructor(public readonly refreshTokenDto: RefreshTokenDto) {}
constructor(public readonly refreshTokenDto: RefreshTokenRequest) {}
}

@Injectable()
Expand All @@ -27,7 +26,7 @@ export class RefreshTokenCommandHandler implements ICommandHandler<RefreshTokenC
private readonly configService: ConfigService,
) {}

async execute(command: RefreshTokenCommand): Promise<IAuthRefreshTokenResponse> {
async execute(command: RefreshTokenCommand): Promise<RefreshTokenResponse> {
const { refreshToken } = command.refreshTokenDto;

// Validate refresh token
Expand Down
7 changes: 3 additions & 4 deletions src/application/commands/auth/register-user.command.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
import { ICommand, CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { RegisterDto } from '@application/dtos/auth/register.dto';
import { IUserBaseResponse } from '@application/dtos/responses/user.response';
import { RegisterRequest, UserBaseResponse } from '@application/dtos';
import { Injectable } from '@nestjs/common';
import { UserService } from '@core/services/user.service';
import { UserMapper } from '@application/mappers/user.mapper';

export class RegisterUserCommand implements ICommand {
constructor(public readonly registerDto: RegisterDto) {}
constructor(public readonly registerDto: RegisterRequest) {}
}

@Injectable()
@CommandHandler(RegisterUserCommand)
export class RegisterUserCommandHandler implements ICommandHandler<RegisterUserCommand> {
constructor(private readonly userService: UserService) {}

async execute(command: RegisterUserCommand): Promise<IUserBaseResponse> {
async execute(command: RegisterUserCommand): Promise<UserBaseResponse> {
const { email, password, firstName, lastName } = command.registerDto;

const user = await this.userService.createUser(email, password, firstName, lastName);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { ICommand, CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { RequestPasswordResetDto } from '@application/dtos/auth/password-reset.dto';
import { RequestPasswordResetRequest } from '@application/dtos';
import { Injectable } from '@nestjs/common';
import { AuthService } from '@core/services/auth.service';
import { EmailProvider } from '@presentation/modules/auth/providers/email.provider';
import { EntityNotFoundException } from '@core/exceptions/domain-exceptions';

export class RequestPasswordResetCommand implements ICommand {
constructor(public readonly dto: RequestPasswordResetDto) {}
constructor(public readonly dto: RequestPasswordResetRequest) {}
}

@Injectable()
Expand Down
4 changes: 2 additions & 2 deletions src/application/commands/auth/reset-password.command.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ICommand, CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { ResetPasswordDto } from '@application/dtos/auth/password-reset.dto';
import { ResetPasswordRequest } from '@application/dtos';
import { Injectable, UnauthorizedException, BadRequestException } from '@nestjs/common';
import { AuthService } from '@core/services/auth.service';
import { UserService } from '@core/services/user.service';
Expand All @@ -10,7 +10,7 @@ import {
} from '@core/exceptions/domain-exceptions';

export class ResetPasswordCommand implements ICommand {
constructor(public readonly dto: ResetPasswordDto) {}
constructor(public readonly dto: ResetPasswordRequest) {}
}

@Injectable()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { ICommand, CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { SendVerificationEmailDto } from '@application/dtos/auth/email-verification.dto';
import { SendVerificationEmailRequest } from '@application/dtos';
import { Injectable } from '@nestjs/common';
import { AuthService } from '@core/services/auth.service';
import { EmailProvider } from '@presentation/modules/auth/providers/email.provider';

export class SendVerificationEmailCommand implements ICommand {
constructor(public readonly dto: SendVerificationEmailDto) {}
constructor(public readonly dto: SendVerificationEmailRequest) {}
}

@Injectable()
Expand Down
Loading
Loading