| 1 | import { describe, it, expect, afterAll, beforeEach } from 'vitest'
|
| 2 | import request from 'supertest'
|
| 3 | import { createApp } from '@app/createApp'
|
| 4 | import { buildPrisma, cleanupTestDb, createTestUser, expectPublicUser } from '../test-helper'
|
| 5 | import { recordedJobs, resetQueueMocks } from '../mocks/queue'
|
| 6 |
|
| 7 | const app = createApp()
|
| 8 | const db = buildPrisma()
|
| 9 |
|
| 10 | afterAll(() => db.$disconnect())
|
| 11 | beforeEach(async () => {
|
| 12 | await cleanupTestDb(db)
|
| 13 |
|
| 14 | resetQueueMocks()
|
| 15 | })
|
| 16 |
|
| 17 | describe('POST /auth/login', () => {
|
| 18 | it('returns a token for valid credentials', async () => {
|
| 19 | await createTestUser(db, { email: 'login@example.com', password: 'senha123' })
|
| 20 |
|
| 21 | const res = await request(app)
|
| 22 | .post('/auth/login')
|
| 23 | .send({ email: 'login@example.com', password: 'senha123' })
|
| 24 |
|
| 25 | expect(res.status).toBe(200)
|
| 26 | expect(res.body.token).toBeTruthy()
|
| 27 | expect(res.body.user.email).toBe('login@example.com')
|
| 28 | expectPublicUser(res.body.user)
|
| 29 | })
|
| 30 |
|
| 31 | it('returns 401 for wrong password', async () => {
|
| 32 | await createTestUser(db, { email: 'login@example.com', password: 'senha123' })
|
| 33 |
|
| 34 | const res = await request(app)
|
| 35 | .post('/auth/login')
|
| 36 | .send({ email: 'login@example.com', password: 'errada' })
|
| 37 |
|
| 38 | expect(res.status).toBe(401)
|
| 39 | })
|
| 40 |
|
| 41 | it('returns 401 for unknown email', async () => {
|
| 42 | const res = await request(app)
|
| 43 | .post('/auth/login')
|
| 44 | .send({ email: 'naoexiste@example.com', password: 'qualquer' })
|
| 45 |
|
| 46 | expect(res.status).toBe(401)
|
| 47 | })
|
| 48 |
|
| 49 | it('reissues an activation code when an inactive user logs in with an expired one', async () => {
|
| 50 | const user = await createTestUser(db, { email: 'inactive@example.com', password: 'senha123' })
|
| 51 | await db.user.update({
|
| 52 | where: { id: user.id },
|
| 53 | data: {
|
| 54 | activationCode: '111111',
|
| 55 | activationCodeExpiresAt: new Date(Date.now() - 1000),
|
| 56 | },
|
| 57 | })
|
| 58 |
|
| 59 | const res = await request(app)
|
| 60 | .post('/auth/login')
|
| 61 | .send({ email: 'inactive@example.com', password: 'senha123' })
|
| 62 |
|
| 63 | expect(res.status).toBe(200)
|
| 64 |
|
| 65 | const dbUser = await db.user.findUnique({ where: { id: user.id } })
|
| 66 | expect(dbUser!.activationCode).toMatch(/^\d{6}$/)
|
| 67 | expect(dbUser!.activationCode).not.toBe('111111')
|
| 68 | expect(dbUser!.activationCodeExpiresAt!.getTime()).toBeGreaterThan(Date.now())
|
| 69 |
|
| 70 | expect(recordedJobs).toContainEqual(
|
| 71 | expect.objectContaining({
|
| 72 | queue: 'mail',
|
| 73 | name: 'mail:activate-account',
|
| 74 | data: { userId: user.id, code: dbUser!.activationCode },
|
| 75 | })
|
| 76 | )
|
| 77 | })
|
| 78 | })
|