69 lines
2.0 KiB
TypeScript
69 lines
2.0 KiB
TypeScript
import { describe, expect, it, vi } from 'vitest'
|
|
import type { Request, Response } from 'express'
|
|
|
|
import { getCookie, sendForbidden, sendPaymentRequired, sendUnauthorized } from './authHelpers'
|
|
|
|
function responseStub() {
|
|
const res = {
|
|
status: vi.fn(),
|
|
json: vi.fn(),
|
|
}
|
|
res.status.mockReturnValue(res)
|
|
res.json.mockReturnValue(res)
|
|
return res as unknown as Response & typeof res
|
|
}
|
|
|
|
describe('authHelpers', () => {
|
|
it('extracts and decodes a cookie value by name', () => {
|
|
const req = {
|
|
headers: {
|
|
cookie: 'theme=dark; employee_session=abc%20123%3D; other=value',
|
|
},
|
|
} as Request
|
|
|
|
expect(getCookie(req, 'employee_session')).toBe('abc 123=')
|
|
})
|
|
|
|
it('returns null when the cookie header or requested cookie is missing', () => {
|
|
expect(getCookie({ headers: {} } as Request, 'employee_session')).toBeNull()
|
|
expect(getCookie({ headers: { cookie: 'theme=dark' } } as Request, 'employee_session')).toBeNull()
|
|
})
|
|
|
|
it('sends a uniform unauthorized response', () => {
|
|
const res = responseStub()
|
|
|
|
sendUnauthorized(res, 'invalid_token', 'Invalid token')
|
|
|
|
expect(res.status).toHaveBeenCalledWith(401)
|
|
expect(res.json).toHaveBeenCalledWith({ error: 'invalid_token', message: 'Invalid token', statusCode: 401 })
|
|
})
|
|
|
|
it('sends forbidden responses with optional metadata', () => {
|
|
const res = responseStub()
|
|
|
|
sendForbidden(res, 'forbidden', 'Nope', { requiredRole: 'OWNER' })
|
|
|
|
expect(res.status).toHaveBeenCalledWith(403)
|
|
expect(res.json).toHaveBeenCalledWith({
|
|
error: 'forbidden',
|
|
message: 'Nope',
|
|
statusCode: 403,
|
|
requiredRole: 'OWNER',
|
|
})
|
|
})
|
|
|
|
it('sends payment-required responses with optional metadata', () => {
|
|
const res = responseStub()
|
|
|
|
sendPaymentRequired(res, 'subscription_suspended', 'Pay up', { billingUrl: '/billing' })
|
|
|
|
expect(res.status).toHaveBeenCalledWith(402)
|
|
expect(res.json).toHaveBeenCalledWith({
|
|
error: 'subscription_suspended',
|
|
message: 'Pay up',
|
|
statusCode: 402,
|
|
billingUrl: '/billing',
|
|
})
|
|
})
|
|
})
|