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 nest-cli.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
"deleteOutDir": true,
"plugins": ["@nestjs/swagger"]
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"@nestjs/jwt": "^11.0.2",
"@nestjs/mapped-types": "*",
"@nestjs/platform-express": "^11.0.1",
"@nestjs/swagger": "^11.2.6",
"@nestjs/throttler": "^6.5.0",
"@prisma/adapter-pg": "^7.4.0",
"@prisma/client": "^7.4.2",
Expand Down
52 changes: 52 additions & 0 deletions pnpm-lock.yaml

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

2 changes: 2 additions & 0 deletions src/app.controller.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { Controller, Get } from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
import { AppService } from './app.service'
import { Public } from './auth/decorator'

@ApiTags('App')
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
Expand Down
8 changes: 8 additions & 0 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
Post,
UseGuards,
} from '@nestjs/common'
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'
import { OtpService } from 'src/otp/otp.service'
import { TokenService } from 'src/token/token.service'
import { CreateUserDto } from 'src/user/dto'
Expand All @@ -22,6 +23,7 @@ import {
} from './dto'
import { RefreshTokenGuard } from './guard'

@ApiTags('Auth')
@Controller('auth')
export class AuthController {
constructor(
Expand All @@ -43,13 +45,15 @@ export class AuthController {
return this.authService.login(loginDto)
}

@ApiBearerAuth()
@HttpCode(HttpStatus.OK)
@Post('logout-all')
logoutAll(@User('sub') userId: number) {
return this.authService.logoutFromAllDevices(userId)
}

@Public()
@ApiBearerAuth()
@UseGuards(RefreshTokenGuard)
@HttpCode(HttpStatus.OK)
@Post('refresh-token')
Expand All @@ -61,13 +65,15 @@ export class AuthController {
}

@Public()
@ApiBearerAuth()
@UseGuards(RefreshTokenGuard)
@HttpCode(HttpStatus.OK)
@Post('revoke-refresh-token')
revokeRefreshToken(@User('rtid') refreshTokenId: string) {
return this.tokenService.revokeRefreshToken(refreshTokenId)
}

@ApiBearerAuth()
@Patch('change-email')
changeEmail(
@User('email') oldEmail: string,
Expand All @@ -76,6 +82,7 @@ export class AuthController {
return this.authService.changeEmail(oldEmail, changeEmailDto)
}

@ApiBearerAuth()
@Patch('change-password')
changePassword(
@User('email') email: string,
Expand All @@ -97,6 +104,7 @@ export class AuthController {
return this.otpService.emailOtp(emailOtpDto.email)
}

@ApiBearerAuth()
@HttpCode(HttpStatus.OK)
@Post('guarded-email-otp')
guardedEmailOtp(@User('email') email: string) {
Expand Down
10 changes: 9 additions & 1 deletion src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
NotFoundException,
} from '@nestjs/common'
import * as argon from 'argon2'
import { UserAlreadyExistsException } from 'src/custom-exceptions'
import { PrismaService } from 'src/infra/prisma/prisma.service'
import { OtpService } from 'src/otp/otp.service'
import { TokenService } from 'src/token/token.service'
Expand All @@ -27,6 +28,13 @@ export class AuthService {
) {}

public async signup(createUserDto: CreateUserDto) {
// validate if a user exists with the same email
const existingUser = await this.prisma.user.findUnique({
where: { email: createUserDto.email },
select: { email: true },
})
if (existingUser)
throw new UserAlreadyExistsException('email', existingUser.email)
const { emailVerifiedCode, ...dto } = createUserDto
await this.otpService.verifyCode(dto.email, emailVerifiedCode)
const user = await this.usersService.createUser(dto)
Expand All @@ -44,7 +52,7 @@ export class AuthService {
// if user does not exist, throw exception
if (!user) throw new NotFoundException('User not found')
// check user is not active (deleted)
if (user.deleted) throw new ForbiddenException('User inactive')
if (user.deleted) throw new ForbiddenException('User account inactive')
// compare password
const pwMatches = await argon.verify(user.password, loginDto.password)
// if the password incorrect, throw exception
Expand Down
5 changes: 5 additions & 0 deletions src/auth/dto/change-email.dto.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import { ApiProperty, ApiSchema } from '@nestjs/swagger'
import { IsEmail, IsNotEmpty, IsString } from 'class-validator'

@ApiSchema({ name: 'ChangeEmailRequest' })
export class ChangeEmailDto {
@ApiProperty({ example: 'new_email@example.com' })
@IsEmail()
@IsNotEmpty()
newEmail: string

@ApiProperty({ example: '019cdba1-96a7-7471-be71-42636407ce41' })
@IsString()
@IsNotEmpty()
oldEmailVerifiedCode: string

@ApiProperty({ example: '019cdba1-96a7-7471-be71-42636407ce41' })
@IsString()
@IsNotEmpty()
newEmailVerifiedCode: string
Expand Down
5 changes: 5 additions & 0 deletions src/auth/dto/change-password.dto.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import { ApiProperty, ApiSchema } from '@nestjs/swagger'
import { IsNotEmpty, IsString } from 'class-validator'

@ApiSchema({ name: 'ChangePasswordRequest' })
export class ChangePasswordDto {
@ApiProperty({ example: 'oldPassword123' })
@IsString()
@IsNotEmpty()
oldPassword: string

@ApiProperty({ example: 'newPassword123' })
@IsString()
@IsNotEmpty()
newPassword: string

@ApiProperty({ example: '019cdba1-96a7-7471-be71-42636407ce41' })
@IsString()
@IsNotEmpty()
emailVerifiedCode: string
Expand Down
5 changes: 5 additions & 0 deletions src/auth/dto/forgot-password.dto.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import { ApiProperty, ApiSchema } from '@nestjs/swagger'
import { IsNotEmpty, IsString } from 'class-validator'

@ApiSchema({ name: 'ForgotPasswordRequest' })
export class ForgotPasswordDto {
@ApiProperty({ example: 'user@example.com' })
@IsString()
@IsNotEmpty()
email: string

@ApiProperty({ example: 'newPassword123' })
@IsString()
@IsNotEmpty()
newPassword: string

@ApiProperty({ example: '019cdba1-96a7-7471-be71-42636407ce41' })
@IsString()
@IsNotEmpty()
emailVerifiedCode: string
Expand Down
10 changes: 10 additions & 0 deletions src/auth/dto/login.dto.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@
import { ApiProperty, ApiSchema } from '@nestjs/swagger'
import { IsEmail, IsNotEmpty, IsString } from 'class-validator'

@ApiSchema({ name: 'LoginRequest' })
export class LoginDto {
@ApiProperty({
example: 'user@example.com',
description: 'The email address of the user',
})
@IsEmail()
@IsNotEmpty()
email: string

@ApiProperty({
example: 'password123',
description: 'The password of the user',
})
@IsString()
@IsNotEmpty()
password: string
Expand Down
6 changes: 6 additions & 0 deletions src/auth/dto/otp.dto.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
import { ApiProperty, ApiSchema } from '@nestjs/swagger'
import { IsEmail, IsNotEmpty, IsString } from 'class-validator'

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

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

@ApiProperty({ example: '123456' })
@IsString()
@IsNotEmpty()
otp: string
Expand Down
6 changes: 3 additions & 3 deletions src/auth/guard/auth.guard.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ describe('AuthGuard', () => {
mockPrisma.user.findUnique.mockResolvedValue(null)

await expect(guard.canActivate(context)).rejects.toThrow(
new NotFoundException('User not exists'),
new NotFoundException('Your account not exists'),
)
})

Expand All @@ -115,7 +115,7 @@ describe('AuthGuard', () => {
mockPrisma.user.findUnique.mockResolvedValue({ deleted: true })

await expect(guard.canActivate(context)).rejects.toThrow(
new ForbiddenException('User inactive'),
new ForbiddenException('Your account is inactive'),
)
})

Expand All @@ -129,7 +129,7 @@ describe('AuthGuard', () => {
}) // user version 2

await expect(guard.canActivate(context)).rejects.toThrow(
new UnauthorizedException('Token revoked'),
new UnauthorizedException('Access token revoked'),
)
})

Expand Down
6 changes: 3 additions & 3 deletions src/auth/guard/auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,12 @@ export class AuthGuard implements CanActivate {
where: { id: payload.sub },
select: { email: true, role: true, tokenVersion: true, deleted: true },
})
if (!user) throw new NotFoundException('User not exists')
if (!user) throw new NotFoundException('Your account not exists')
// check user is not active (deleted)
if (user.deleted) throw new ForbiddenException('User inactive')
if (user.deleted) throw new ForbiddenException('Your account is inactive')

if (user.tokenVersion !== payload.version) {
throw new UnauthorizedException('Token revoked')
throw new UnauthorizedException('Access token revoked')
}

request[REQUEST_USER_KEY] = {
Expand Down
1 change: 1 addition & 0 deletions src/custom-exceptions/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './user-already-exists.exception'
10 changes: 10 additions & 0 deletions src/custom-exceptions/user-already-exists.exception.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { HttpException, HttpStatus } from '@nestjs/common'

export class UserAlreadyExistsException extends HttpException {
constructor(fieldName: string, fieldValue: string) {
super(
`User with ${fieldName} '${fieldValue}' already exists`,
HttpStatus.CONFLICT,
)
}
}
Loading
Loading