Skip to content

Commit a904325

Browse files
committed
fix: authenticateRequest
1 parent 187eb87 commit a904325

File tree

6 files changed

+33
-16
lines changed

6 files changed

+33
-16
lines changed

lib/graphql/index.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ async function fetch(url, options = {}) {
2727
// options.headers['oc-secret'] = process.env.OC_SECRET; // TODO
2828
options.headers['oc-application'] = 'pdf';
2929
options.headers['user-agent'] = 'opencollective-pdf/1.0 node-fetch/1.0';
30-
30+
console.log('FETCH', url, options);
3131
const result = await nodeFetch(url, options);
3232

3333
return result;
@@ -50,14 +50,16 @@ function getCustomAgent() {
5050
export const createClient = (authorizationHeaders) => {
5151
const authLink = setContext((_, { headers }) => {
5252
const newHeaders = { ...headers, ...authorizationHeaders };
53+
console.log({ headers, newHeaders });
5354
return { headers: newHeaders };
5455
});
5556

57+
console.log('URI:', getGraphqlUrl('v2'));
5658
const apiLink = new HttpLink({ uri: getGraphqlUrl('v2'), fetch });
5759
return new ApolloClient({
5860
connectToDevTools: process.browser,
5961
ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
60-
link: ApolloLink.from([authLink, apiLink]),
62+
link: authLink.concat(apiLink),
6163
cache: new InMemoryCache({
6264
// Documentation:
6365
// https://www.apollographql.com/docs/react/data/fragments/#using-fragments-with-unions-and-interfaces

lib/graphql/queries.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -234,9 +234,14 @@ export async function fetchTransactionInvoice(transactionId, authorizationHeader
234234
variables: { transactionId },
235235
fetchPolicy: 'no-cache',
236236
});
237-
} catch (e) {
238-
console.error('Query Error', JSON.stringify(e, null, 2));
239-
throw e;
237+
} catch (error) {
238+
console.error(
239+
'Query Error',
240+
JSON.stringify({
241+
response,
242+
}),
243+
);
244+
throw error;
240245
}
241246

242247
if (!response.data.transaction) {

lib/req-utils.js

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,15 @@ import { get, isEmpty } from 'lodash';
44
* To forward API Key or Authorization headers from the request to the API calls.
55
* Returns `null` if no headers are found.
66
*/
7-
export const getAuthorizationHeadersFromReq = (req) => {
7+
const getAuthorizationHeadersFromReq = (req) => {
88
const { headers, query } = req;
99
const result = {};
1010
const apiKey = get(headers, 'api-key') || get(query, 'apiKey');
1111
const personalToken = get(headers, 'personal-token') || get(query, 'personalToken') || get(query, 'app_key');
12-
const authorization = get(headers, 'authorization') || req.cookies?.authorization;
12+
const authorization = get(headers, 'authorization');
1313
if (authorization) {
14-
const parts = authorization.split(' ');
15-
const scheme = parts[0];
16-
const accessToken = parts[1];
17-
if (!/^Bearer$/i.test(scheme) || !accessToken) {
14+
const [scheme, accessToken] = authorization.split(' ');
15+
if (scheme !== 'Bearer' || !accessToken) {
1816
throw new Error('Invalid authorization header. Format should be: Authorization: Bearer [token]');
1917
}
2018

@@ -29,19 +27,19 @@ export const getAuthorizationHeadersFromReq = (req) => {
2927
result['Personal-Token'] = personalToken;
3028
}
3129

32-
return isEmpty(headers) ? null : headers;
30+
return isEmpty(headers) ? null : result;
3331
};
3432

3533
/**
3634
* Some syntax sugar around the `getAuthorizationHeadersFromReq` function, that throws for non-authenticated requests
3735
* but allows `OPTIONS` requests to pass through
3836
*/
39-
export const authenticateRequest = (ctx) => {
40-
const authorizationHeaders = getAuthorizationHeadersFromReq(ctx);
37+
export const authenticateRequest = (req) => {
38+
const authorizationHeaders = getAuthorizationHeadersFromReq(req);
4139
if (!authorizationHeaders) {
4240
// Frontend sends an OPTIONS request to check CORS, we should just return OK when that happens
43-
if (ctx.req.method === 'OPTIONS') {
44-
return {};
41+
if (req.method === 'OPTIONS') {
42+
return null;
4543
} else {
4644
throw new Error('Please provide an access token or an APP key');
4745
}

pages/expense/[id]/[filename].js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ class TransactionReceipt extends React.Component {
1212
if (isServer) {
1313
const { id } = ctx.query;
1414
const authorizationHeaders = authenticateRequest(ctx.req);
15+
if (!authorizationHeaders) {
16+
return {};
17+
}
18+
1519
const expense = await fetchExpenseInvoiceData(id, authorizationHeaders);
1620
return { expense, pageFormat: ctx.query.pageFormat };
1721
}

pages/receipts/collectives/[fromCollectiveSlug]/[toCollectiveSlug]/[isoStartDate]/[isoEndDate]/[filename].js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ class TransactionReceipt extends React.Component {
1212
if (isServer) {
1313
const { fromCollectiveSlug, toCollectiveSlug: hostSlug, isoStartDate: dateFrom, isoEndDate: dateTo } = ctx.query;
1414
const authorizationHeaders = authenticateRequest(ctx.req);
15+
if (!authorizationHeaders) {
16+
return {};
17+
}
18+
1519
const queryParams = { fromCollectiveSlug, hostSlug, dateFrom, dateTo };
1620
const response = await fetchInvoiceByDateRange(queryParams, authorizationHeaders);
1721

pages/receipts/transactions/[id]/[filename].js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ class TransactionReceipt extends React.Component {
1212
if (isServer) {
1313
const { id, pageFormat } = ctx.query;
1414
const authorizationHeaders = authenticateRequest(ctx.req);
15+
if (!authorizationHeaders) {
16+
return {};
17+
}
18+
1519
const transaction = await fetchTransactionInvoice(id, authorizationHeaders);
1620
return {
1721
pageFormat: pageFormat,

0 commit comments

Comments
 (0)