Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion packages/faustwp-core/src/auth/authorize.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'isomorphic-fetch';
import isString from 'lodash/isString.js';
import { getWpUrl } from '../lib/getWpUrl.js';
import { getQueryParam, removeURLParam } from '../utils/index.js';
import { errorLog, getQueryParam, removeURLParam } from '../utils/index.js';
import { fetchAccessToken, getAccessToken } from './client/accessToken.js';

export interface EnsureAuthorizationOptions {
Expand Down Expand Up @@ -54,6 +54,25 @@ export async function ensureAuthorization(

const token = await fetchAccessToken(code);

if (!token && code) {
/**
* WordPress already issued a code, so the exchange itself failed, for
* example because the frontend's credentials were rejected. Sending the
* user back for another code would loop forever, so stop here, and drop
* the code so a reload starts over.
*/
window.history.replaceState(
{},
document.title,
removeURLParam(window.location.href, 'code'),
);
errorLog(
'Faust.js could not exchange the authorization code for an access token. Check your Next.js server logs.',
);

return {};
}

if (!token) {
return unauthorized;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* @jest-environment jsdom
*/

import fetchMock from 'fetch-mock';
import { ensureAuthorization } from '../../src/auth/authorize';
import * as getWpUrl from '../../src/lib/getWpUrl';
import * as log from '../../src/utils/log';

describe('ensureAuthorization() when exchanging a code fails', () => {
afterEach(() => {
fetchMock.restore();
jest.restoreAllMocks();
});

test('stops instead of sending the user back for another code', async () => {
jest.spyOn(getWpUrl, 'getWpUrl').mockReturnValue('http://test.local');
const errorSpy = jest.spyOn(log, 'errorLog').mockImplementation(() => {});
window.history.pushState({}, '', '/preview?p=1&preview=true&code=abc');
fetchMock.get('begin:/api/faust/auth/token', { status: 403, body: {} });

const result = await ensureAuthorization({
redirectUri: window.location.href,
});

expect(result).toEqual({});
expect(window.location.search).toBe('?p=1&preview=true');
expect(errorSpy).toHaveBeenCalled();
});
});
Loading