Public Access
refactor(auth): send login token through apiFetch
All authenticated calls now use apiFetch, and only utils/auth.js touches the stored token. The cookie login can then change these two files instead of every page.
This commit is contained in:
1 parent
085fcf15a4
commit
5ff8d48c53
18 files changed
+127
-70
No files matched your search
@@ -0,0 +1,40 @@
|
||||
// @vitest-environment jsdom
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {apiFetch} from './api.js';
|
||||
|
||||
describe('apiFetch', () => {
|
||||
beforeEach(() => {
|
||||
globalThis.fetch = vi.fn(async () => new Response(null, {status: 204}));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it('sends the stored token and keeps the other headers and options', async () => {
|
||||
localStorage.setItem('tbp_jwt', 'the-token');
|
||||
|
||||
await apiFetch('/api/x', {method: 'PUT', headers: {'Content-Type': 'application/json'}, body: '{}'});
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith('/api/x', {
|
||||
method: 'PUT',
|
||||
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer the-token'},
|
||||
body: '{}',
|
||||
});
|
||||
});
|
||||
|
||||
it('sends no Authorization header without a token', async () => {
|
||||
await apiFetch('/api/x');
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith('/api/x', {headers: undefined});
|
||||
});
|
||||
|
||||
it('reads the token on every call', async () => {
|
||||
localStorage.setItem('tbp_jwt', 'old');
|
||||
await apiFetch('/api/x');
|
||||
localStorage.setItem('tbp_jwt', 'new');
|
||||
await apiFetch('/api/x');
|
||||
|
||||
expect(fetch).toHaveBeenLastCalledWith('/api/x', {headers: {'Authorization': 'Bearer new'}});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user