Commit 81fedf45 authored by tom's avatar tom

fix csrf request

parent e55e987f
import { compile } from 'path-to-regexp';
import appConfig from 'configs/app/config';
import { RESOURCES } from './resources';
import type { ApiResource, ResourceName } from './resources';
export default function buildUrlNode(
_resource: ApiResource | ResourceName,
pathParams?: Record<string, string | undefined>,
queryParams?: Record<string, string | number | undefined>,
) {
const resource: ApiResource = typeof _resource === 'string' ? RESOURCES[_resource] : _resource;
const baseUrl = resource.endpoint || appConfig.api.endpoint;
const basePath = resource.basePath !== undefined ? resource.basePath : appConfig.api.basePath;
const path = basePath + resource.path;
const url = new URL(compile(path)(pathParams), baseUrl);
queryParams && Object.entries(queryParams).forEach(([ key, value ]) => {
value && url.searchParams.append(key, String(value));
});
return url.toString();
}
...@@ -2,25 +2,20 @@ import type { NextApiRequest } from 'next'; ...@@ -2,25 +2,20 @@ import type { NextApiRequest } from 'next';
import type { RequestInit, Response } from 'node-fetch'; import type { RequestInit, Response } from 'node-fetch';
import nodeFetch from 'node-fetch'; import nodeFetch from 'node-fetch';
import appConfig from 'configs/app/config';
import { httpLogger } from 'lib/api/logger'; import { httpLogger } from 'lib/api/logger';
import * as cookies from 'lib/cookies'; import * as cookies from 'lib/cookies';
export default function fetchFactory( export default function fetchFactory(
_req: NextApiRequest, _req: NextApiRequest,
apiEndpoint: string = appConfig.api.endpoint,
) { ) {
// first arg can be only a string // first arg can be only a string
// FIXME migrate to RequestInfo later if needed // FIXME migrate to RequestInfo later if needed
return function fetch(path: string, init?: RequestInit): Promise<Response> { return function fetch(url: string, init?: RequestInit): Promise<Response> {
const csrfToken = _req.headers['x-csrf-token']?.toString();
const headers = { const headers = {
accept: 'application/json', accept: 'application/json',
'content-type': 'application/json', 'content-type': 'application/json',
cookie: `${ cookies.NAMES.API_TOKEN }=${ _req.cookies[cookies.NAMES.API_TOKEN] }`, cookie: `${ cookies.NAMES.API_TOKEN }=${ _req.cookies[cookies.NAMES.API_TOKEN] }`,
...(csrfToken ? { 'x-csrf-token': csrfToken } : {}),
}; };
const url = new URL(path, apiEndpoint);
httpLogger.logger.info({ httpLogger.logger.info({
message: 'Trying to call API', message: 'Trying to call API',
...@@ -28,7 +23,7 @@ export default function fetchFactory( ...@@ -28,7 +23,7 @@ export default function fetchFactory(
req: _req, req: _req,
}); });
return nodeFetch(url.toString(), { return nodeFetch(url, {
headers, headers,
...init, ...init,
}); });
......
import type { NextApiRequest, NextApiResponse } from 'next'; import type { NextApiRequest, NextApiResponse } from 'next';
import buildUrl from 'lib/api/buildUrl'; import buildUrlNode from 'lib/api/buildUrlNode';
import { httpLogger } from 'lib/api/logger'; import { httpLogger } from 'lib/api/logger';
import fetchFactory from 'lib/api/nodeFetch'; import fetchFactory from 'lib/api/nodeFetch';
export default async function csrfHandler(_req: NextApiRequest, res: NextApiResponse) { export default async function csrfHandler(_req: NextApiRequest, res: NextApiResponse) {
httpLogger(_req, res); httpLogger(_req, res);
const url = buildUrl('csrf'); const url = buildUrlNode('csrf');
const response = await fetchFactory(_req)(url); const response = await fetchFactory(_req)(url);
if (response.status === 200) { if (response.status === 200) {
......
...@@ -2,6 +2,7 @@ import _pick from 'lodash/pick'; ...@@ -2,6 +2,7 @@ import _pick from 'lodash/pick';
import _pickBy from 'lodash/pickBy'; import _pickBy from 'lodash/pickBy';
import type { NextApiRequest, NextApiResponse } from 'next'; import type { NextApiRequest, NextApiResponse } from 'next';
import appConfig from 'configs/app/config';
import fetchFactory from 'lib/api/nodeFetch'; import fetchFactory from 'lib/api/nodeFetch';
const handler = async(_req: NextApiRequest, res: NextApiResponse) => { const handler = async(_req: NextApiRequest, res: NextApiResponse) => {
...@@ -10,8 +11,12 @@ const handler = async(_req: NextApiRequest, res: NextApiResponse) => { ...@@ -10,8 +11,12 @@ const handler = async(_req: NextApiRequest, res: NextApiResponse) => {
return; return;
} }
const response = await fetchFactory(_req, _req.headers['x-endpoint']?.toString())( const url = new URL(
_req.url.replace(/^\/node-api\/proxy/, ''), _req.url.replace(/^\/node-api\/proxy/, ''),
_req.headers['x-endpoint']?.toString() || appConfig.api.endpoint,
);
const response = await fetchFactory(_req)(
url.toString(),
_pickBy(_pick(_req, [ 'body', 'method' ]), Boolean), _pickBy(_pick(_req, [ 'body', 'method' ]), Boolean),
); );
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment