authDesktopAuthorization.test.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { createPinia, setActivePinia } from 'pinia'
  2. import { beforeEach, expect, it, vi } from 'vitest'
  3. const mocks = vi.hoisted(() => ({
  4. login: vi.fn(),
  5. setup: vi.fn(),
  6. authorizeComputer: vi.fn(),
  7. }))
  8. vi.mock('@/api/auth', () => ({
  9. login: mocks.login,
  10. setup: mocks.setup,
  11. bootstrap: vi.fn(),
  12. logout: vi.fn(),
  13. fetchProfiles: vi.fn(),
  14. fetchProfileIdentities: vi.fn(),
  15. changeCredentials: vi.fn(),
  16. updateAccountAvatar: vi.fn(),
  17. }))
  18. vi.mock('@/api/serverIdentity', () => ({ fetchServerIdentity: vi.fn(), onServerIdentity: () => () => {} }))
  19. vi.mock('@/api/client', () => ({
  20. ApiError: class ApiError extends Error { status = 500 },
  21. clearApiSecurityContext: vi.fn(),
  22. onApiUnauthorized: () => () => {},
  23. }))
  24. import { useAuthStore } from '@/stores/auth'
  25. const response = (role: 'admin' | 'user') => ({
  26. authRequired: true,
  27. profiles: [],
  28. csrfToken: 'fresh-csrf',
  29. user: { id: 'user-1', username: '用户', role },
  30. })
  31. beforeEach(() => {
  32. setActivePinia(createPinia())
  33. mocks.login.mockReset()
  34. mocks.setup.mockReset()
  35. mocks.authorizeComputer.mockReset()
  36. Object.defineProperty(window, 'yaoyaoDesktop', { configurable: true, value: { authorizeComputer: mocks.authorizeComputer } })
  37. })
  38. it('re-authorizes the computer only after an explicit administrator login', async () => {
  39. mocks.login.mockResolvedValue(response('admin'))
  40. mocks.authorizeComputer.mockResolvedValue({ registered: true, hostId: 'host-1' })
  41. const auth = useAuthStore()
  42. await auth.login({ username: 'admin', password: 'secret' })
  43. expect(mocks.authorizeComputer).toHaveBeenCalledWith('fresh-csrf')
  44. expect(auth.status).toBe('authenticated')
  45. })
  46. it('does not grant computer control to a non-administrator login', async () => {
  47. mocks.login.mockResolvedValue(response('user'))
  48. const auth = useAuthStore()
  49. await auth.login({ username: 'member', password: 'secret' })
  50. expect(mocks.authorizeComputer).not.toHaveBeenCalled()
  51. expect(auth.status).toBe('authenticated')
  52. })
  53. it('keeps the administrator signed in when computer authorization fails', async () => {
  54. mocks.login.mockResolvedValue(response('admin'))
  55. mocks.authorizeComputer.mockRejectedValue(new Error('computer offline'))
  56. const auth = useAuthStore()
  57. await expect(auth.login({ username: 'admin', password: 'secret' })).resolves.toBeUndefined()
  58. expect(auth.status).toBe('authenticated')
  59. })