fix: add authorization token to generate code (#1792)

fixes #1791
This commit is contained in:
Leonardo Ferreira Lima 2024-06-19 07:39:21 -03:00 committed by GitHub
parent b432e94a4e
commit a0df5138b3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 39 additions and 2 deletions

View File

@ -9,6 +9,7 @@ import { CopyToClipboard } from 'react-copy-to-clipboard';
import toast from 'react-hot-toast';
import { IconCopy } from '@tabler/icons';
import { findCollectionByItemUid } from '../../../../../../../utils/collections/index';
import { getAuthHeaders } from '../../../../../../../utils/codegenerator/auth';
const CodeView = ({ language, item }) => {
const { displayedTheme } = useTheme();
@ -20,10 +21,16 @@ const CodeView = ({ language, item }) => {
item.uid
);
const headers = [...(collection?.root?.request?.headers || []), ...(requestHeaders || [])];
const collectionRootAuth = collection?.root?.request?.auth;
const requestAuth = item.draft ? get(item, 'draft.request.auth') : get(item, 'request.auth');
const headers = [
...getAuthHeaders(collectionRootAuth, requestAuth),
...(collection?.root?.request?.headers || []),
...(requestHeaders || [])
];
let snippet = '';
try {
snippet = new HTTPSnippet(buildHarRequest({ request: item.request, headers })).convert(target, client);
} catch (e) {

View File

@ -0,0 +1,30 @@
import get from 'lodash/get';
export const getAuthHeaders = (collectionRootAuth, requestAuth) => {
const auth = collectionRootAuth && ['inherit', 'none'].includes(requestAuth.mode) ? collectionRootAuth : requestAuth;
switch (auth.mode) {
case 'basic':
const username = get(auth, 'basic.username');
const password = get(auth, 'basic.password');
const basicToken = Buffer.from(`${username}:${password}`).toString('base64');
return [
{
enabled: true,
name: 'Authorization',
value: `Basic ${basicToken}`
}
];
case 'bearer':
return [
{
enabled: true,
name: 'Authorization',
value: `Bearer ${get(auth, 'bearer.token')}`
}
];
default:
return [];
}
};