| 1 | import { describe, it, expect, afterAll, beforeEach } from 'vitest'
|
| 2 | import request from 'supertest'
|
| 3 | import { createApp } from '@app/createApp'
|
| 4 | import {
|
| 5 | buildPrisma,
|
| 6 | cleanupTestDb,
|
| 7 | createTestUser,
|
| 8 | generateTestToken,
|
| 9 | } from '../test-helper'
|
| 10 |
|
| 11 | const app = createApp()
|
| 12 | const db = buildPrisma()
|
| 13 |
|
| 14 | afterAll(() => db.$disconnect())
|
| 15 | beforeEach(() => cleanupTestDb(db))
|
| 16 |
|
| 17 | describe('GET /auth/verify', () => {
|
| 18 | it('returns the token payload and a safe slice of the user', async () => {
|
| 19 | const user = await createTestUser(db, {
|
| 20 | email: 'verify@example.com',
|
| 21 | firstName: 'Pedro',
|
| 22 | })
|
| 23 |
|
| 24 | const token = generateTestToken(user.id, user.email)
|
| 25 |
|
| 26 | const res = await request(app)
|
| 27 | .get('/auth/verify')
|
| 28 | .set('Authorization', `Bearer ${token}`)
|
| 29 |
|
| 30 | expect(res.status).toBe(200)
|
| 31 | expect(res.body.valid).toBe(true)
|
| 32 | expect(res.body.userId).toBe(user.id)
|
| 33 | expect(res.body.email).toBe('verify@example.com')
|
| 34 | expect(res.body.user.firstName).toBe('Pedro')
|
| 35 | expect(res.body.user.encryptedPassword).toBeUndefined()
|
| 36 | })
|
| 37 |
|
| 38 | it('returns 401 without an authorization header', async () => {
|
| 39 | const res = await request(app).get('/auth/verify')
|
| 40 | expect(res.status).toBe(401)
|
| 41 | })
|
| 42 |
|
| 43 | it('returns 401 for a malformed token', async () => {
|
| 44 | const res = await request(app)
|
| 45 | .get('/auth/verify')
|
| 46 | .set('Authorization', 'Bearer not.a.jwt')
|
| 47 |
|
| 48 | expect(res.status).toBe(401)
|
| 49 | })
|
| 50 |
|
| 51 | it('returns 404 when the token is valid but the user is gone', async () => {
|
| 52 | const token = generateTestToken(999999, 'ghost@example.com')
|
| 53 |
|
| 54 | const res = await request(app)
|
| 55 | .get('/auth/verify')
|
| 56 | .set('Authorization', `Bearer ${token}`)
|
| 57 |
|
| 58 | expect(res.status).toBe(404)
|
| 59 | })
|
| 60 | })
|