add error handling for db calls

This commit is contained in:
andres
2023-06-16 12:01:14 +02:00
parent 121fceb97a
commit 9cd6595ae2
11 changed files with 590 additions and 114 deletions

View File

@@ -41,6 +41,7 @@ model User {
verification Verification?
RevokedToken RevokedToken[]
RefreshToken RefreshToken[]
ResetPassword ResetPassword?
@@fulltext([name, email])
}
@@ -66,6 +67,17 @@ model RefreshToken {
@@index([userId])
}
model ResetPassword {
id String @id @default(cuid())
userId String @unique
resetPasswordToken String? @unique @default(uuid())
resetPasswordTokenExpiry DateTime?
resetPasswordEmailsSent Int @default(0)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId])
}
model Card {
id String @id @default(cuid())
deckId String

View File

@@ -4,6 +4,7 @@ import {
Get,
HttpCode,
HttpStatus,
Param,
Post,
Request,
Res,
@@ -24,6 +25,8 @@ import {
LogoutCommand,
RefreshTokenCommand,
ResendVerificationEmailCommand,
ResetPasswordCommand,
SendPasswordRecoveryEmailCommand,
VerifyEmailCommand,
} from './use-cases'
@@ -97,4 +100,14 @@ export class AuthController {
accessToken: newTokens.accessToken,
}
}
@Post('recover-password')
async recoverPassword(@Body('email') email: string) {
return await this.commandBus.execute(new SendPasswordRecoveryEmailCommand(email))
}
@Post('reset-password/:token')
async resetPassword(@Body('password') password: string, @Param('token') token: string) {
return await this.commandBus.execute(new ResetPasswordCommand(token, password))
}
}

View File

@@ -10,6 +10,8 @@ import {
LogoutHandler,
RefreshTokenHandler,
ResendVerificationEmailHandler,
ResetPasswordHandler,
SendPasswordRecoveryEmailHandler,
VerifyEmailHandler,
} from './use-cases'
import { AuthRepository } from './infrastructure/auth.repository'
@@ -20,6 +22,8 @@ const commandHandlers = [
LogoutHandler,
RefreshTokenHandler,
ResendVerificationEmailHandler,
ResetPasswordHandler,
SendPasswordRecoveryEmailHandler,
VerifyEmailHandler,
]

View File

@@ -14,7 +14,7 @@ export class LocalStrategy extends PassportStrategy(Strategy) {
async validate(email: string, password: string): Promise<any> {
const newCredentials = await this.authService.checkCredentials(email, password)
if (newCredentials.resultCode === 1) {
throw new UnauthorizedException()
throw new UnauthorizedException('Invalid credentials')
}
return newCredentials
}

View File

@@ -0,0 +1,143 @@
import { Test, TestingModule } from '@nestjs/testing'
import * as request from 'supertest'
import { HttpStatus } from '@nestjs/common'
import { AppModule } from '../../../../app.module'
import { RegistrationDto } from '../../dto/registration.dto'
describe('AuthController (e2e)', () => {
let app
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile()
app = moduleFixture.createNestApplication()
await app.init()
})
it('/POST sign-up', () => {
const registrationData: RegistrationDto = {
name: 'John',
email: 'john@gmail.com',
password: 'secret',
}
return request(app.getHttpServer())
.post('/auth/sign-up')
.send(registrationData)
.expect(HttpStatus.CREATED)
})
it('/POST sign-up (duplicate)', () => {
const registrationData: RegistrationDto = {
name: 'John',
email: 'john@gmail.com',
password: 'secret',
}
return request(app.getHttpServer())
.post('/auth/sign-up')
.send(registrationData)
.expect(HttpStatus.BAD_REQUEST)
})
it('/POST login', () => {
return request(app.getHttpServer())
.post('/auth/login')
.send({ email: 'john@gmail.com', password: 'secret' })
.expect(HttpStatus.OK)
.then(response => {
expect(response.body.accessToken).toBeDefined()
})
})
it('/POST login (invalid)', () => {
return request(app.getHttpServer())
.post('/auth/login')
.send({ email: 'john@gmail.com', password: 'wrong_password' })
.expect(HttpStatus.UNAUTHORIZED)
})
it('/GET me', async () => {
const loginResponse = await request(app.getHttpServer())
.post('/auth/login')
.send({ email: 'john@gmail.com', password: 'secret' })
.expect(HttpStatus.OK)
return request(app.getHttpServer())
.get('/auth/me')
.set('Authorization', `Bearer ${loginResponse.body.accessToken}`)
.expect(HttpStatus.OK)
})
it('/POST verify-email', async () => {
// Assuming "john@gmail.com" has a verification code "123456"
return request(app.getHttpServer())
.post('/auth/verify-email')
.send({ code: '123456' })
.expect(HttpStatus.OK)
})
it('/POST verify-email (invalid)', () => {
return request(app.getHttpServer())
.post('/auth/verify-email')
.send({ code: 'wrong_code' })
.expect(HttpStatus.UNAUTHORIZED)
})
it('/POST resend-verification-email', async () => {
// Assuming "john@gmail.com" has a user ID "1"
return request(app.getHttpServer())
.post('/auth/resend-verification-email')
.send({ userId: '1' })
.expect(HttpStatus.OK)
})
it('/POST logout', async () => {
const loginResponse = await request(app.getHttpServer())
.post('/auth/login')
.send({ email: 'john@gmail.com', password: 'secret' })
.expect(HttpStatus.OK)
return request(app.getHttpServer())
.post('/auth/logout')
.set('Cookie', [`refreshToken=${loginResponse.body.refreshToken}`])
.expect(HttpStatus.OK)
})
it('/GET refresh-token', async () => {
const loginResponse = await request(app.getHttpServer())
.post('/auth/login')
.send({ email: 'john@gmail.com', password: 'secret' })
.expect(HttpStatus.OK)
return request(app.getHttpServer())
.get('/auth/refresh-token')
.set('Cookie', [`refreshToken=${loginResponse.body.refreshToken}`])
.expect(HttpStatus.OK)
.then(response => {
expect(response.body.accessToken).toBeDefined()
})
})
it('/POST recover-password', () => {
return request(app.getHttpServer())
.post('/auth/recover-password')
.send({ email: 'john@gmail.com' })
.expect(HttpStatus.OK)
})
it('/POST reset-password/:token', () => {
// Assuming "john@gmail.com" has a password reset token "abcdef"
return request(app.getHttpServer())
.post('/auth/reset-password/abcdef')
.send({ password: 'new_password' })
.expect(HttpStatus.OK)
})
// Add more tests for the other endpoints in a similar way
afterAll(async () => {
await app.close()
})
})

View File

@@ -4,3 +4,5 @@ export * from './logout-use-case'
export * from './resend-verification-email-use-case'
export * from './refresh-token-use-case'
export * from './verify-email-use-case'
export * from './send-password-recovery-email-use-case'
export * from './reset-password-use-case'

View File

@@ -0,0 +1,40 @@
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs'
import { BadRequestException, NotFoundException } from '@nestjs/common'
import { UsersRepository } from '../../users/infrastructure/users.repository'
import { UsersService } from '../../users/services/users.service'
export class ResetPasswordCommand {
constructor(public readonly resetPasswordToken: string, public readonly newPassword: string) {}
}
@CommandHandler(ResetPasswordCommand)
export class ResetPasswordHandler implements ICommandHandler<ResetPasswordCommand> {
constructor(
private readonly usersRepository: UsersRepository,
private readonly usersService: UsersService
) {}
async execute(command: ResetPasswordCommand) {
const user = await this.usersRepository.findUserByPasswordResetToken(command.resetPasswordToken)
if (!user) {
throw new NotFoundException('Incorrect or expired password reset token')
}
if (!command.newPassword) {
throw new BadRequestException('Password is required')
}
const newPasswordHash = await this.usersService.generateHash(command.newPassword)
const updatedUser = await this.usersRepository.resetPasswordAndDeleteToken(
user.id,
newPasswordHash
)
if (!updatedUser) {
throw new NotFoundException('Incorrect or expired password reset token')
}
return null
}
}

View File

@@ -0,0 +1,40 @@
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs'
import { NotFoundException } from '@nestjs/common'
import { UsersRepository } from '../../users/infrastructure/users.repository'
import { UsersService } from '../../users/services/users.service'
import { v4 as uuidv4 } from 'uuid'
export class SendPasswordRecoveryEmailCommand {
constructor(public readonly email: string) {}
}
@CommandHandler(SendPasswordRecoveryEmailCommand)
export class SendPasswordRecoveryEmailHandler
implements ICommandHandler<SendPasswordRecoveryEmailCommand>
{
constructor(
private readonly usersRepository: UsersRepository,
private readonly usersService: UsersService
) {}
async execute(command: SendPasswordRecoveryEmailCommand) {
const user = await this.usersRepository.findUserByEmail(command.email)
if (!user) {
throw new NotFoundException('User not found')
}
const token = uuidv4()
const updatedUser = await this.usersRepository.createPasswordResetToken(user.id, token)
await this.usersService.sendPasswordRecoveryEmail({
email: updatedUser.user.email,
name: updatedUser.user.name,
passwordRecoveryToken: updatedUser.resetPasswordToken,
})
if (!updatedUser) {
throw new NotFoundException('User not found')
}
return null
}
}

View File

@@ -5,7 +5,12 @@ import {
UserViewType,
VerificationWithUser,
} from '../../../types/types'
import { Injectable } from '@nestjs/common'
import {
BadRequestException,
Injectable,
InternalServerErrorException,
Logger,
} from '@nestjs/common'
import { addHours } from 'date-fns'
import { v4 as uuidv4 } from 'uuid'
import { PrismaService } from '../../../prisma.service'
@@ -16,157 +21,329 @@ import { Prisma } from '@prisma/client'
export class UsersRepository {
constructor(private prisma: PrismaService) {}
private readonly logger = new Logger(UsersRepository.name)
async getUsers(
currentPage: number,
itemsPerPage: number,
searchNameTerm: string,
searchEmailTerm: string
): Promise<EntityWithPaginationType<UserViewType>> {
const where = {
name: {
search: searchNameTerm || undefined,
},
email: {
search: searchEmailTerm || undefined,
},
}
const [totalItems, users] = await this.prisma.$transaction([
this.prisma.user.count({ where }),
this.prisma.user.findMany({
where,
skip: (currentPage - 1) * itemsPerPage,
take: itemsPerPage,
}),
])
const totalPages = Math.ceil(totalItems / itemsPerPage)
const usersView = users.map(u => pick(u, ['id', 'name', 'email', 'isEmailVerified']))
return {
totalPages,
currentPage,
itemsPerPage,
totalItems,
items: usersView,
try {
const where = {
name: {
search: searchNameTerm || undefined,
},
email: {
search: searchEmailTerm || undefined,
},
}
const [totalItems, users] = await this.prisma.$transaction([
this.prisma.user.count({ where }),
this.prisma.user.findMany({
where,
skip: (currentPage - 1) * itemsPerPage,
take: itemsPerPage,
}),
])
const totalPages = Math.ceil(totalItems / itemsPerPage)
const usersView = users.map(u => pick(u, ['id', 'name', 'email', 'isEmailVerified']))
return {
totalPages,
currentPage,
itemsPerPage,
totalItems,
items: usersView,
}
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
if (e.code === 'P2025') {
throw new BadRequestException({ message: 'Invalid page number', field: 'page' })
}
}
this.logger.error(e?.message || e)
throw new InternalServerErrorException(e)
}
}
async createUser(newUser: CreateUserInput): Promise<User | null> {
return await this.prisma.user.create({
data: {
email: newUser.email,
password: newUser.password,
name: newUser.name,
verification: {
create: {
verificationToken: newUser.verificationToken,
verificationTokenExpiry: newUser.verificationTokenExpiry,
try {
return await this.prisma.user.create({
data: {
email: newUser.email,
password: newUser.password,
name: newUser.name,
verification: {
create: {
verificationToken: newUser.verificationToken,
verificationTokenExpiry: newUser.verificationTokenExpiry,
},
},
},
},
include: {
verification: true,
},
})
include: {
verification: true,
},
})
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
if (e.code === 'P2002') {
throw new BadRequestException({ message: 'Email already exists', field: 'email' })
}
}
this.logger.error(e?.message || e)
throw new InternalServerErrorException(e)
}
}
async deleteUserById(id: string): Promise<boolean> {
const result = await this.prisma.user.delete({
where: {
id,
},
})
return result.isDeleted
try {
const result = await this.prisma.user.delete({
where: {
id,
},
})
return result.isDeleted
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
if (e.code === 'P2015') {
throw new BadRequestException({ message: 'User not found', field: 'id' })
}
}
this.logger.error(e?.message || e)
throw new InternalServerErrorException(e)
}
}
async deleteAllUsers(): Promise<boolean> {
const result = await this.prisma.user.deleteMany()
return result.count > 0
async deleteAllUsers(): Promise<number> {
try {
const result = await this.prisma.user.deleteMany()
return result.count
} catch (e) {
this.logger.error(e?.message || e)
throw new InternalServerErrorException(e)
}
}
async findUserById(id: string, include?: Prisma.UserInclude) {
const user = await this.prisma.user.findUnique({
where: { id },
include,
})
if (!user) {
return null
}
try {
const user = await this.prisma.user.findUnique({
where: { id },
include,
})
if (!user) {
return null
}
return user as Prisma.UserGetPayload<{ include: typeof include }>
return user as Prisma.UserGetPayload<{ include: typeof include }>
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
if (e.code === 'P2015') {
throw new BadRequestException({ message: 'User not found', field: 'id' })
}
}
this.logger.error(e?.message || e)
throw new InternalServerErrorException(e)
}
}
async findUserByEmail(email: string): Promise<User | null> {
const user = await this.prisma.user.findUnique({
where: { email },
include: { verification: true },
})
try {
const user = await this.prisma.user.findUnique({
where: { email },
include: { verification: true },
})
if (!user) {
return null
if (!user) {
return null
}
return user
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
if (e.code === 'P2015') {
throw new BadRequestException({ message: 'User not found', field: 'email' })
}
}
this.logger.error(e?.message || e)
throw new InternalServerErrorException(e)
}
return user
}
async findUserByVerificationToken(token: string): Promise<VerificationWithUser | null> {
const verification = await this.prisma.verification.findUnique({
where: {
verificationToken: token,
},
include: {
user: true,
},
})
if (!verification) {
return null
try {
const verification = await this.prisma.verification.findUnique({
where: {
verificationToken: token,
},
include: {
user: true,
},
})
if (!verification) {
return null
}
return verification
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
if (e.code === 'P2015') {
throw new BadRequestException({ message: 'Verification not found', field: 'token' })
}
}
this.logger.error(e?.message || e)
throw new InternalServerErrorException(e)
}
return verification
}
async updateEmailVerification(id: string) {
const result = await this.prisma.verification.update({
where: {
userId: id,
},
data: {
isEmailVerified: true,
user: {
update: {
isEmailVerified: true,
try {
const result = await this.prisma.verification.update({
where: {
userId: id,
},
data: {
isEmailVerified: true,
user: {
update: {
isEmailVerified: true,
},
},
},
},
})
return result.isEmailVerified
})
return result.isEmailVerified
} catch (e) {
this.logger.error(e?.message || e)
throw new InternalServerErrorException(e)
}
}
async updateVerificationToken(id: string) {
return await this.prisma.verification.update({
where: {
userId: id,
},
data: {
verificationToken: uuidv4(),
verificationTokenExpiry: addHours(new Date(), 24),
},
include: {
user: true,
},
})
try {
return await this.prisma.verification.update({
where: {
userId: id,
},
data: {
verificationToken: uuidv4(),
verificationTokenExpiry: addHours(new Date(), 24),
},
include: {
user: true,
},
})
} catch (e) {
this.logger.error(e?.message || e)
throw new InternalServerErrorException(e)
}
}
async createPasswordResetToken(id: string, token: string) {
try {
return await this.prisma.resetPassword.upsert({
where: {
userId: id,
},
update: {
resetPasswordToken: token,
resetPasswordTokenExpiry: addHours(new Date(), 1),
resetPasswordEmailsSent: {
increment: 1,
},
},
create: {
resetPasswordToken: token,
resetPasswordTokenExpiry: addHours(new Date(), 1),
resetPasswordEmailsSent: 1,
user: {
connect: {
id,
},
},
},
include: {
user: true,
},
})
} catch (e) {
this.logger.error(e?.message || e)
throw new InternalServerErrorException(e)
}
}
async findUserByPasswordResetToken(token: string): Promise<User | null> {
try {
const resetPassword = await this.prisma.resetPassword.findUnique({
where: {
resetPasswordToken: token,
},
include: {
user: true,
},
})
if (!resetPassword) {
return null
}
return resetPassword.user
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
if (e.code === 'P2015') {
throw new BadRequestException({ message: 'Invalid token', field: 'token' })
}
}
this.logger.error(e?.message || e)
throw new InternalServerErrorException(e)
}
}
async resetPasswordAndDeleteToken(userId: string, password: string) {
try {
return await this.prisma.$transaction([
this.prisma.resetPassword.update({
where: {
userId: userId,
},
data: {
resetPasswordToken: null,
resetPasswordTokenExpiry: null,
resetPasswordEmailsSent: {
increment: 1,
},
},
include: {
user: true,
},
}),
this.prisma.user.update({
where: {
id: userId,
},
data: {
password,
},
}),
])
} catch (e) {
this.logger.error(e?.message || e)
throw new InternalServerErrorException(e)
}
}
async revokeToken(id: string, token: string): Promise<User | null> {
const revokedToken = await this.prisma.revokedToken.create({
data: {
token: token,
userId: id,
},
include: {
user: true,
},
})
if (!revokedToken.user) {
return null
try {
const revokedToken = await this.prisma.revokedToken.create({
data: {
token: token,
userId: id,
},
include: {
user: true,
},
})
if (!revokedToken.user) {
return null
}
return revokedToken.user
} catch (e) {
this.logger.error(e?.message || e)
throw new InternalServerErrorException(e)
}
return revokedToken.user
}
}

View File

@@ -21,8 +21,9 @@ export class UsersService {
return await this.usersRepository.deleteUserById(id)
}
async deleteAllUsers(): Promise<boolean> {
return await this.usersRepository.deleteAllUsers()
async deleteAllUsers(): Promise<{ deleted: number }> {
const deleted = await this.usersRepository.deleteAllUsers()
return { deleted }
}
public async sendConfirmationEmail({
@@ -42,6 +43,27 @@ export class UsersService {
html: `<b>Hello ${name}!</b><br/>Please confirm your email by clicking on the link below:<br/><a href="http://localhost:3000/confirm-email/${verificationToken}">Confirm email</a>`,
subject: 'E-mail confirmation',
})
} catch (e) {
this.logger.error(e?.message || e)
}
}
public async sendPasswordRecoveryEmail({
email,
name,
passwordRecoveryToken,
}: {
email: string
name: string
passwordRecoveryToken: string
}) {
try {
await this.emailService.sendMail({
from: 'Andrii <andrii@andrii.es>',
to: email,
html: `<b>Hello ${name}!</b><br/>To recover your password follow this link:<br/><a href="http://localhost:3000/confirm-email/${passwordRecoveryToken}">Confirm email</a>. If it doesn't work, copy and paste the following link in your browser:<br/>http://localhost:3000/confirm-email/${passwordRecoveryToken} `,
subject: 'Password recovery',
})
} catch (e) {
this.logger.error(e)
}

View File

@@ -3,6 +3,29 @@ import { PrismaClient } from '@prisma/client'
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
// constructor() {
// super({
// log: [
// {
// emit: 'stdout',
// level: 'query',
// },
// {
// emit: 'stdout',
// level: 'error',
// },
// {
// emit: 'stdout',
// level: 'info',
// },
// {
// emit: 'stdout',
// level: 'warn',
// },
// ],
// })
// }
async onModuleInit() {
await this.$connect()
}