67 lines
2.1 KiB
TypeScript
67 lines
2.1 KiB
TypeScript
import { afterEach, expect, it, vi } from 'vitest'
|
|
import { authGateway, safeReturnPath } from '@/application/auth'
|
|
|
|
afterEach(() => vi.unstubAllGlobals())
|
|
|
|
it('requests a CAPTCHA without Authorization and normalizes the login email', async () => {
|
|
const fetcher = vi.fn<typeof fetch>(async (input, options) => {
|
|
if (String(input).endsWith('/captcha'))
|
|
return Response.json({
|
|
code: 'OK',
|
|
data: { captchaCode: 'challenge', image: 'data:image/png;base64,x', expiresIn: 120 },
|
|
})
|
|
expect(new Headers(options?.headers).get('Authorization')).toBeNull()
|
|
expect(JSON.parse(options?.body as string)).toEqual({
|
|
email: 'admin@example.com',
|
|
captchaCode: 'challenge',
|
|
captchaAnswer: 'ABCDE',
|
|
})
|
|
return Response.json({
|
|
code: 'OK',
|
|
data: {
|
|
token: 'token-1',
|
|
tokenType: 'Bearer',
|
|
expiresIn: 86400,
|
|
user: { userCode: 'A', nickname: '管理员', email: 'admin@example.com' },
|
|
},
|
|
})
|
|
})
|
|
vi.stubGlobal('fetch', fetcher)
|
|
const challenge = await authGateway.requestCaptcha()
|
|
const session = await authGateway.signIn(' ADMIN@EXAMPLE.COM ', challenge.captchaCode, ' ABCDE ')
|
|
expect(session.user.nickname).toBe('管理员')
|
|
expect(session.token).toBe('token-1')
|
|
expect(session.expiresAt).toBeGreaterThan(Date.now())
|
|
})
|
|
|
|
it('preserves admin authentication error codes', async () => {
|
|
vi.stubGlobal(
|
|
'fetch',
|
|
vi.fn<typeof fetch>(async () =>
|
|
Response.json(
|
|
{ code: 'ADMIN_ACCESS_DENIED', message: '无权限', requestId: 'req-1' },
|
|
{ status: 403 },
|
|
),
|
|
),
|
|
)
|
|
await expect(authGateway.requestCaptcha()).rejects.toMatchObject({
|
|
code: 'ADMIN_ACCESS_DENIED',
|
|
status: 403,
|
|
requestId: 'req-1',
|
|
})
|
|
})
|
|
|
|
it('returns only to current internal routes', () => {
|
|
expect(safeReturnPath('/users')).toBe('/users')
|
|
expect(safeReturnPath('/assembly-test')).toBe('/assembly-test')
|
|
expect(safeReturnPath('/components/123')).toBe('/components/123')
|
|
for (const path of [
|
|
'/interfaces/new',
|
|
'//example.com',
|
|
'https://example.com',
|
|
'/components-malicious',
|
|
null,
|
|
])
|
|
expect(safeReturnPath(path)).toBe('/components')
|
|
})
|