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 docker-compose.dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ services:
target: development
container_name: dev_api
command: >
sh -c "pnpm prisma migrate deploy &&
sh -c "pnpm install --frozen-lockfile &&
pnpm prisma migrate deploy &&
pnpm prisma db seed &&
pnpm start:dev"
ports:
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@
"test:cov": "jest --coverage",
"test:ci": "jest --runInBand --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "NODE_OPTIONS=--experimental-vm-modules dotenv -e .env.test -- jest --runInBand --config ./test/jest-e2e.json",
"test:e2e:watch": "NODE_OPTIONS=--experimental-vm-modules dotenv -e .env.test -- jest --runInBand --watch --config ./test/jest-e2e.json",
"test:e2e": "prisma generate && pnpm build && NODE_OPTIONS=--experimental-vm-modules dotenv -e .env.test -- jest --runInBand --config ./test/jest-e2e.json",
"test:e2e:watch": "prisma generate && pnpm build && NODE_OPTIONS=--experimental-vm-modules dotenv -e .env.test -- jest --runInBand --watch --config ./test/jest-e2e.json",
"test:all": "pnpm test && pnpm test:e2e",
"prepare": "husky"
},
Expand All @@ -45,6 +45,7 @@
"@nestjs/jwt": "^11.0.2",
"@nestjs/mapped-types": "*",
"@nestjs/platform-express": "^11.0.1",
"@nestjs/schedule": "^6.1.3",
"@nestjs/swagger": "^11.2.6",
"@nestjs/throttler": "^6.5.0",
"@prisma/adapter-pg": "^7.5.0",
Expand Down
35 changes: 35 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "users" ADD COLUMN "deletedAt" TIMESTAMP(3);
13 changes: 7 additions & 6 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@ datasource db {
}

model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deleted Boolean @default(false)
role Role @default(USER)
tokenVersion Int @default(1)
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deleted Boolean @default(false)
deletedAt DateTime?
role Role @default(USER)
tokenVersion Int @default(1)

email String @unique
password String
Expand Down
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ThrottlerStorageRedisService } from '@nest-lab/throttler-storage-redis'
import { Module } from '@nestjs/common'
import { ConfigModule, ConfigService } from '@nestjs/config'
import { APP_GUARD } from '@nestjs/core'
import { ScheduleModule } from '@nestjs/schedule'
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler'
import { AppController } from './app.controller'
import { AppService } from './app.service'
Expand Down Expand Up @@ -36,6 +37,7 @@ import { UserModule } from './user/user.module'
storage: new ThrottlerStorageRedisService(redis),
}),
}),
ScheduleModule.forRoot(),
],
controllers: [AppController],
providers: [
Expand Down
2 changes: 1 addition & 1 deletion src/token/token.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export class TokenService {
private readonly prisma: PrismaService,
) {}

public async generateToken(user: User): Promise<{
public async generateToken(user: Omit<User, 'password'>): Promise<{
accessToken: string
refreshToken: string
}> {
Expand Down
1 change: 1 addition & 0 deletions src/user/dto/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './change-user-role.dto'
export * from './create-user.dto'
export * from './delete-user.dto'
export * from './reactivate-user.dto'
export * from './update-user.dto'
20 changes: 20 additions & 0 deletions src/user/dto/reactivate-user.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { ApiProperty, ApiSchema } from '@nestjs/swagger'
import { IsEmail, IsNotEmpty, IsString } from 'class-validator'

@ApiSchema({ name: 'ReactivateUserRequest' })
export class ReactivateUserDto {
@ApiProperty({ example: 'user@example.com' })
@IsEmail()
@IsNotEmpty()
email: string

@ApiProperty({ example: 'password123' })
@IsString()
@IsNotEmpty()
password: string

@ApiProperty({ example: '019cdba1-96a7-7471-be71-42636407ce41' })
@IsString()
@IsNotEmpty()
emailVerifiedCode: string
}
33 changes: 33 additions & 0 deletions src/user/user-cleanup.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Injectable } from '@nestjs/common'
import { Cron, CronExpression } from '@nestjs/schedule'
import { PrismaService } from 'src/infra/prisma/prisma.service'

@Injectable()
export class UserCleanupService {
constructor(private readonly prisma: PrismaService) {}

// runs every day at midnight
@Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
async handleUserCleanup() {
const now = new Date()
// 7-day grace period
const threshold = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)

const usersToDelete = await this.prisma.user.findMany({
where: {
deleted: true,
deletedAt: {
lte: threshold,
},
},
})

for (const user of usersToDelete) {
// IMPORTANT: handle dependencies before delete

await this.prisma.$transaction([
this.prisma.user.delete({ where: { id: user.id } }),
])
}
}
}
37 changes: 36 additions & 1 deletion src/user/user.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ForbiddenException, NotFoundException } from '@nestjs/common'
import { Test, TestingModule } from '@nestjs/testing'
import { Role } from 'generated/prisma/enums'
import { ChangeUserRoleDto, DeleteUserDto } from './dto'
import { ChangeUserRoleDto, DeleteUserDto, ReactivateUserDto } from './dto'
import { UserController } from './user.controller'
import { UserService } from './user.service'

Expand All @@ -10,6 +10,7 @@ const mockUsersService = {
findUserByUserId: jest.fn(),
updateUser: jest.fn(),
softDeleteUser: jest.fn(),
reactivateUser: jest.fn(),
hardDeleteUser: jest.fn(),
changeUserRole: jest.fn(),
}
Expand Down Expand Up @@ -169,6 +170,40 @@ describe('UsersController', () => {
})
})

describe('reactivateUser', () => {
const reactivateUserDto: ReactivateUserDto = {
email: 'test@email.com',
password: 'StrongPassword!123',
emailVerifiedCode: 'verification-code',
}

it('should reactivate user and return tokens', async () => {
const expectedRes = {
id: 1,
message: 'User reactivated',
accessToken: 'new-access-token',
refreshToken: 'new-refresh-token',
}

userService.reactivateUser.mockResolvedValue(expectedRes)

await expect(controller.reactivateUser(reactivateUserDto)).resolves.toBe(
expectedRes,
)
expect(userService.reactivateUser).toHaveBeenCalledWith(reactivateUserDto)
})

it('propagates NotFoundException from service', async () => {
const expectedErr = new NotFoundException('User not found')

userService.reactivateUser.mockRejectedValue(expectedErr)

await expect(controller.reactivateUser(reactivateUserDto)).rejects.toBe(
expectedErr,
)
})
})

describe('changeUserRole', () => {
it('should change user role and return response', async () => {
const userId = 1
Expand Down
21 changes: 18 additions & 3 deletions src/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,22 @@ import {
Controller,
Delete,
Get,
HttpCode,
HttpStatus,
Param,
ParseIntPipe,
Patch,
Post,
} from '@nestjs/common'
import { Role } from 'generated/prisma/enums'
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'
import { Roles, User } from 'src/auth/decorator'
import { ChangeUserRoleDto, DeleteUserDto, UpdateUserDto } from './dto'
import { Role } from 'generated/prisma/enums'
import { Public, Roles, User } from 'src/auth/decorator'
import {
ChangeUserRoleDto,
DeleteUserDto,
ReactivateUserDto,
UpdateUserDto,
} from './dto'
import { UserService } from './user.service'

@ApiTags('Users')
Expand Down Expand Up @@ -51,6 +59,13 @@ export class UserController {
return this.userService.softDeleteUser(email, deleteUserDto)
}

@Public()
@HttpCode(HttpStatus.OK)
@Post('reactivate-user')
reactivateUser(@Body() reactivateUserDto: ReactivateUserDto) {
return this.userService.reactivateUser(reactivateUserDto)
}

@Delete('hard-delete')
hardDeleteUser(
@User('email') email: string,
Expand Down
3 changes: 2 additions & 1 deletion src/user/user.module.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { Module } from '@nestjs/common'
import { OtpModule } from 'src/otp/otp.module'
import { TokenModule } from 'src/token/token.module'
import { UserCleanupService } from './user-cleanup.service'
import { UserController } from './user.controller'
import { UserService } from './user.service'

@Module({
imports: [OtpModule, TokenModule],
controllers: [UserController],
providers: [UserService],
providers: [UserService, UserCleanupService],
exports: [UserService],
})
export class UserModule {}
Loading
Loading