Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue 50 dont allow logged user call resources for other user #53

Draft
wants to merge 11 commits into
base: master
Choose a base branch
from
Draft
19 changes: 9 additions & 10 deletions src/controller/project/createProject.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import request from 'supertest'
import { app } from '../../app'
import { randomUUID } from 'crypto'
import { createAndAuthenticateUser } from '../../utils/tests/create-and-authenticate-user'

let userAuth: {
Expand All @@ -28,7 +27,7 @@ describe('createProject E2E', () => {
}

const createProjectResponse = await request(app.server)
.post(`/user/${userAuth.userId}/project`)
.post(`/user/project`)
.send(createProjectBody)
.set('Authorization', `Bearer ${userAuth.token}`)

Expand All @@ -37,23 +36,23 @@ describe('createProject E2E', () => {
expect(createProjectResponse.body.project.tags).toEqual(['react', 'node'])
})

it('should not be able to create a project without user', async () => {
it('should not be able to create a project without authenticate', async () => {
const createProjectBody = {
title: 'Squad40 Project',
tags: ['react', 'node'],
link: 'https://Squad40.com',
description: 'Squad40 description',
}

const userId = randomUUID()

const response = await request(app.server)
.post(`/user/${userId}/project`)
.post(`/user/project`)
.send(createProjectBody)

.set('Authorization', `Bearer ${userAuth.token}`)

expect(response.body.message).toContain('User was not Found !')
expect(response.status).toEqual(404)
expect(response.status).toEqual(401)
expect(response.body).toEqual(
expect.objectContaining({
message: 'Unauthorized',
}),
)
})
})
30 changes: 8 additions & 22 deletions src/controller/project/createProject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { z } from 'zod'
import { CreateProjectUseCase } from '../../use-cases/project/createProjectUseCase'
import { PrismaProjectRepository } from '../../repositories/prisma/prisma-project-repository'
import { PrismaUsersRepository } from '../../repositories/prisma/prisma-users-repository'
import { ResourceNotFoundError } from '../../use-cases/errors/ResourceNotFoundError'

export async function createProject(
request: FastifyRequest,
Expand All @@ -16,36 +15,23 @@ export async function createProject(
description: z.string(),
})

const createProjectParamsSchema = z.object({
userId: z.string().uuid(),
})

const { title, tags, link, description } = createProjectBodySchema.parse(
request.body,
)
const { userId } = createProjectParamsSchema.parse(request.params)

const userRepository = new PrismaUsersRepository()
const projectRepository = new PrismaProjectRepository()
const createProjectUseCase = new CreateProjectUseCase(
projectRepository,
userRepository,
)
try {
const { project } = await createProjectUseCase.execute({
userId,
title,
tags,
link,
description,
})

return response.status(201).send({ project })
} catch (error) {
if (error instanceof ResourceNotFoundError) {
return response.status(404).send({ message: 'User was not Found !' })
}
const { project } = await createProjectUseCase.execute({
userId: request.user.sub,
title,
tags,
link,
description,
})

throw error
}
return response.status(201).send({ project })
}
2 changes: 1 addition & 1 deletion src/controller/project/editProject.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ describe('edit Project E2E', () => {
}

const createProjectResponse = await request(app.server)
.post(`/user/${userAuth.userId}/project`)
.post(`/user/project`)
.send(createProjectBody)
.set('Authorization', `Bearer ${userAuth.token}`)

Expand Down
65 changes: 29 additions & 36 deletions src/controller/project/getProjectsByTags.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,71 +42,64 @@ describe('Get Projets By Tags E2E', () => {
tags: ['tag7', 'tag8', 'tag9'],
},
]
console.log('Creating projects')
for (const project of projectsToBeCreate) {
await request(app.server)
.post(`/user/${userAuth.userId}/project`)
.post(`/user/project`)
.set('Authorization', `Bearer ${userAuth.token}`)

.send(project)
}

console.log('Finish Creating projects')

console.log('Get By tags projects')

const getProjectsByTagsResponse = await request(app.server)
.post(`/projects/tags`)
.send({ tags })
.set('Authorization', `Bearer ${userAuth.token}`)

console.log('End By tags projects')
expect(getProjectsByTagsResponse.statusCode).toEqual(200)
expect(getProjectsByTagsResponse.body.projects).toHaveLength(2)
expect(getProjectsByTagsResponse.body.projects[0]).toEqual(
expect.objectContaining({
title: 'Project 01',
...projectsToBeCreate[0],
user: { name: 'John', surname: 'Doe', avatar_url: expect.any(String) },
}),
)
expect(getProjectsByTagsResponse.body.projects[1]).toEqual(
expect.objectContaining({
title: 'Project 02',
...projectsToBeCreate[1],
user: { name: 'John', surname: 'Doe', avatar_url: expect.any(String) },
}),
)
})

// it('should return 200 and empty object when not find projects by some tag', async () => {
// const tags = ['tagNotExist', 'tagNotExist']
it('should return 200 and empty object when not find projects by some tag', async () => {
const tags = ['tagNotExist', 'tagNotExist']

// const getProjectsByTagsResponse = await request(app.server)
// .post(`/projects/tags`)
// .send({ tags })
// .set('Authorization', `Bearer ${userAuth.token}`)
const getProjectsByTagsResponse = await request(app.server)
.post(`/projects/tags`)
.send({ tags })
.set('Authorization', `Bearer ${userAuth.token}`)

// expect(getProjectsByTagsResponse.statusCode).toEqual(200)
// expect(getProjectsByTagsResponse.body.projects).toHaveLength(0)
// })
expect(getProjectsByTagsResponse.statusCode).toEqual(200)
expect(getProjectsByTagsResponse.body.projects).toHaveLength(0)
})

// it('should be able to get all projects NOT BEING case- sensitive', async () => {
// const tags = ['tAG7', 'TAG8', 'Tag9']
it('should be able to get all projects NOT BEING case- sensitive', async () => {
const tags = ['tAG7', 'TAG8', 'Tag9']

// // Projects with tags ['tag7', 'tag8', 'tag9'] are already registered
// // once the database is set up once per file.
// Projects with tags ['tag7', 'tag8', 'tag9'] are already registered
// once the database is set up once per file.

// const getProjectsByTagsResponse = await request(app.server)
// .post(`/projects/tags`)
// .send({ tags })
// .set('Authorization', `Bearer ${userAuth.token}`)
const getProjectsByTagsResponse = await request(app.server)
.post(`/projects/tags`)
.send({ tags })
.set('Authorization', `Bearer ${userAuth.token}`)

// expect(getProjectsByTagsResponse.statusCode).toEqual(200)
// expect(getProjectsByTagsResponse.body.projects).toHaveLength(1)
// expect(getProjectsByTagsResponse.body.projects[0]).toEqual(
// expect.objectContaining({
// title: 'Project 03',
// user: { name: 'John', surname: 'Doe', avatar_url: expect.any(String) },
// }),
// )
// })
expect(getProjectsByTagsResponse.statusCode).toEqual(200)
expect(getProjectsByTagsResponse.body.projects).toHaveLength(1)
expect(getProjectsByTagsResponse.body.projects[0]).toEqual(
expect.objectContaining({
title: 'Project 03',
user: { name: 'John', surname: 'Doe', avatar_url: expect.any(String) },
}),
)
})
})
15 changes: 7 additions & 8 deletions src/controller/project/getProjectsByUserId.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import request from 'supertest'
import { app } from '../../app'
import { ProjectRepository } from '../../repositories/project-repository'
import { PrismaProjectRepository } from '../../repositories/prisma/prisma-project-repository'
import { randomUUID } from 'crypto'
import { createAndAuthenticateUser } from '../../utils/tests/create-and-authenticate-user'

let projectRepository: ProjectRepository
Expand Down Expand Up @@ -50,7 +49,7 @@ describe('Get Projets By UserId E2E', () => {
})

const getProjectsByUserIdResponse = await request(app.server)
.get(`/projects/${userAuth.userId}`)
.get(`/projects`)
.set('Authorization', `Bearer ${userAuth.token}`)

expect(getProjectsByUserIdResponse.statusCode).toEqual(200)
Expand All @@ -64,16 +63,16 @@ describe('Get Projets By UserId E2E', () => {
)
})

it('should not be able to project that user does not exist', async () => {
const getProjectsByUserIdResponse = await request(app.server)
.get(`/projects/${randomUUID()}`)
.set('Authorization', `Bearer ${userAuth.token}`)
it('should not be able to get projects without authenticate', async () => {
const getProjectsByUserIdResponse = await request(app.server).get(
`/projects`,
)

expect(getProjectsByUserIdResponse.statusCode).toEqual(404)
expect(getProjectsByUserIdResponse.statusCode).toEqual(401)

expect(getProjectsByUserIdResponse.body).toEqual(
expect.objectContaining({
error: 'User was not Found !',
message: 'Unauthorized',
}),
)
})
Expand Down
18 changes: 3 additions & 15 deletions src/controller/project/getProjectsByUserId.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { FastifyReply, FastifyRequest } from 'fastify'
import { z } from 'zod'
import { PrismaUsersRepository } from '../../repositories/prisma/prisma-users-repository'
import { GetProjectsByUserIdUseCase } from '../../use-cases/project/getProjectsByUserIdUseCase'
import { PrismaProjectRepository } from '../../repositories/prisma/prisma-project-repository'
import { ResourceNotFoundError } from '../../use-cases/errors/ResourceNotFoundError'

export async function getProjectsByUserId(
request: FastifyRequest,
Expand All @@ -16,18 +14,8 @@ export async function getProjectsByUserId(
userRepository,
)

const GetProjectByUserIdParamsSchema = z.object({
userId: z.string().uuid(),
const { projects } = await getProjectByUserId.execute({
userId: request.user.sub,
})

const { userId } = GetProjectByUserIdParamsSchema.parse(request.params)

try {
const { projects } = await getProjectByUserId.execute({ userId })
return response.status(200).send({ projects })
} catch (error) {
if (error instanceof ResourceNotFoundError) {
return response.status(404).send({ error: 'User was not Found !' })
}
}
return response.status(200).send({ projects })
}
4 changes: 2 additions & 2 deletions src/controller/project/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ export async function projectRoutes(app: FastifyInstance) {
})

app.post('/projects/tags', { onRequest: verifyJWT }, getProjectsByTags)
app.get('/projects/:userId', { onRequest: verifyJWT }, getProjectsByUserId)
app.get('/projects', { onRequest: verifyJWT }, getProjectsByUserId)
app.get('/project/:projectId', { onRequest: verifyJWT }, getProjectsById)

app.post(
'/project/:projectId/photo',
{ onRequest: verifyJWT },
addImageProject,
)
app.post('/user/:userId/project', { onRequest: verifyJWT }, createProject)
app.post('/user/project', { onRequest: verifyJWT }, createProject)

app.put('/project/:projectId/edit', { onRequest: verifyJWT }, editProject)
app.delete('/project/:projectId', { onRequest: verifyJWT }, deleteProjectById)
Expand Down
56 changes: 15 additions & 41 deletions src/controller/session/authUser.spec.ts
Original file line number Diff line number Diff line change
@@ -1,79 +1,53 @@
import { afterAll, beforeAll, describe, expect, test } from 'vitest'
import { app } from '../../app'
import request from 'supertest'

import { createAndAuthenticateUser } from '../../utils/tests/create-and-authenticate-user'
let userAuth: {
token: string
userId: string
}
describe('User Login E2E', () => {
beforeAll(async () => {
await app.ready()
userAuth = await createAndAuthenticateUser(app)
})

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

test('should be able to login', async () => {
const email = '[email protected]'
const name = 'John'
const surname = 'Doe'
const password = 'password'

await request(app.server).post('/user').send({
email,
name,
surname,
password,
})
const email = '[email protected]'
const password = '12345678'

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

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

test('should not be able to login because the password is incorrect', async () => {
const email = '[email protected]'
const name = 'John'
const surname = 'Doe'
const password = 'password'
const wrongPassword = 'wrongPassword'

await request(app.server).post('/user').send({
email,
name,
surname,
password,
})

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

expect(userData.statusCode).toEqual(401)
expect(userData.body.user).toEqual(expect.objectContaining({}))
})

test('should not be able to login because the email is incorrect', async () => {
const email = '[email protected]'
const wrongEmail = '[email protected]'
const name = 'John'
const surname = 'Doe'
const password = 'password'

await request(app.server).post('/user').send({
email,
name,
surname,
password,
})
const email = '[email protected]'
const password = '12345678'

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

expect(userData.statusCode).toEqual(401)
expect(userData.body.user).toEqual(expect.objectContaining({}))
Expand Down
Loading
Loading