Skip to content

Commit

Permalink
edit user pass routes and tests e2e
Browse files Browse the repository at this point in the history
  • Loading branch information
MatheusSanchez committed Feb 4, 2024
1 parent 6dd34ff commit 6ddfe74
Show file tree
Hide file tree
Showing 5 changed files with 117 additions and 2 deletions.
65 changes: 65 additions & 0 deletions src/controller/user/editUserPassword.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import request from 'supertest'
import { app } from '../../app'
import { createAndAuthenticateUser } from '../../utils/create-and-authenticate-user'

let userAuth: {
token: string
userId: string
}

describe('edit User Pass E2E', () => {
beforeAll(async () => {
await app.ready()
userAuth = await createAndAuthenticateUser(app)
})

afterAll(async () => {
await app.close()
})

it('should be able to edit a user pass', async () => {
const editUserPassResponse = await request(app.server)
.put(`/user/edit/pass`)
.send({
newPassword: 'newAwesomePassword',
oldPassword: '12345678',
})
.set('Authorization', `Bearer ${userAuth.token}`)

expect(editUserPassResponse.statusCode).toEqual(200)
expect(editUserPassResponse.body.user).toEqual(
expect.objectContaining({
name: 'John',
surname: 'Doe',
email: '[email protected]',
id: userAuth.userId,
}),
)

const userData = await request(app.server)
.post('/login')
.send({ email: '[email protected]', password: 'newAwesomePassword' })

expect(userData.statusCode).toEqual(200)
expect(userData.body).toEqual({
user: expect.any(Object),
token: expect.any(String),
})
})

it('should not be able to edit a user pass with the old pass wrong', async () => {
const editUserPassResponse = await request(app.server)
.put(`/user/edit/pass`)
.send({
newPassword: 'newAwesomePassword',
oldPassword: 'WRONGPASS',
})
.set('Authorization', `Bearer ${userAuth.token}`)

expect(editUserPassResponse.statusCode).toEqual(401)
expect(editUserPassResponse.body).toEqual(
expect.objectContaining({ error: 'Invalid old Password!' }),
)
})
})
39 changes: 39 additions & 0 deletions src/controller/user/editUserPassword.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { FastifyRequest, FastifyReply } from 'fastify'
import { z } from 'zod'
import { PrismaUsersRepository } from '../../repositories/prisma/prisma-users-repository'
import { EditUserPasswordUseCase } from '../../use-cases/user/editUserPasswordUseCase'
import { ResourceNotFoundError } from '../../use-cases/errors/ResourceNotFoundError'
import { InvalidCredentialsError } from '../../use-cases/errors/InvalidCredentialsError'

export async function editUserPassword(
request: FastifyRequest,
response: FastifyReply,
) {
const registerBodySchema = z.object({
oldPassword: z.string(),
newPassword: z.string().min(6),
})

const { oldPassword, newPassword } = registerBodySchema.parse(request.body)

const usersRepository = new PrismaUsersRepository()
const editUserPasswordUseCase = new EditUserPasswordUseCase(usersRepository)
try {
const { user } = await editUserPasswordUseCase.execute({
oldPassword,
newPassword,
userId: request.user.sub,
})
return response
.status(200)
.send({ user: { ...user, password_hash: undefined } })
} catch (error) {
if (error instanceof ResourceNotFoundError) {
return response.status(404).send({ error: 'User was not Found !' })
} else if (error instanceof InvalidCredentialsError) {
return response.status(401).send({ error: 'Invalid old Password!' })
}

throw error
}
}
3 changes: 3 additions & 0 deletions src/controller/user/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { editUserById } from './editUserById'
import { addImageUser } from './addImageToUser'
import FastifyMultipart from '@fastify/multipart'
import { verifyJWT } from '../middlewares/verifyJwt'
import { editUserPassword } from './editUserPassword'

export async function userRoutes(app: FastifyInstance) {
app.register(FastifyMultipart, {
Expand All @@ -18,5 +19,7 @@ export async function userRoutes(app: FastifyInstance) {
app.get('/user/:id', { onRequest: verifyJWT }, getUserById)
app.get('/user', { onRequest: verifyJWT }, getUserByEmail)
app.put('/user/:userId/edit', { onRequest: verifyJWT }, editUserById)
app.put('/user/edit/pass', { onRequest: verifyJWT }, editUserPassword)

app.post('/user/:userId/photo', { onRequest: verifyJWT }, addImageUser)
}
10 changes: 9 additions & 1 deletion src/repositories/prisma/prisma-users-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,15 @@ export class PrismaUsersRepository implements UserRepository {
password_hash,
userId,
}: editUserPasswordRequestPrisma): Promise<User> {
throw new Error('Method not implemented.')
const user = await prisma.user.update({
where: {
id: userId,
},
data: {
password_hash,
},
})
return user
}

async addPhotoUrl(userId: string, photoUrl: string): Promise<User> {
Expand Down
2 changes: 1 addition & 1 deletion src/use-cases/user/editUserPasswordUseCase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export class EditUserPasswordUseCase {
const passwordMatched = await compare(oldPassword, user.password_hash)

if (!passwordMatched) {
throw new InvalidCredentialsError('Email e/ou senha inválido.')
throw new InvalidCredentialsError()
}

const password_hash = await hash(newPassword, 6)
Expand Down

0 comments on commit 6ddfe74

Please sign in to comment.