insomnia/packages/insomnia-app/app/network/o-auth-2/refresh-token.js

75 lines
1.9 KiB
JavaScript
Raw Normal View History

// @flow
import * as c from './constants';
2018-06-25 17:42:50 +00:00
import { responseToObject } from './misc';
import { setDefaultProtocol } from 'insomnia-url';
import * as models from '../../models/index';
2018-06-25 17:42:50 +00:00
import { sendWithSettings } from '../network';
import { getBasicAuthHeader } from '../basic-auth/get-header';
2018-06-25 17:42:50 +00:00
export default async function(
requestId: string,
accessTokenUrl: string,
credentialsInBody: boolean,
clientId: string,
clientSecret: string,
refreshToken: string,
scope: string
): Promise<Object> {
const params = [
2018-06-25 17:42:50 +00:00
{ name: c.P_GRANT_TYPE, value: c.GRANT_TYPE_REFRESH },
{ name: c.P_REFRESH_TOKEN, value: refreshToken }
];
// Add optional params
2018-06-25 17:42:50 +00:00
scope && params.push({ name: c.P_SCOPE, value: scope });
const headers = [
2018-06-25 17:42:50 +00:00
{ name: 'Content-Type', value: 'application/x-www-form-urlencoded' },
{
name: 'Accept',
value: 'application/x-www-form-urlencoded, application/json'
}
];
if (credentialsInBody) {
2018-06-25 17:42:50 +00:00
params.push({ name: c.P_CLIENT_ID, value: clientId });
params.push({ name: c.P_CLIENT_SECRET, value: clientSecret });
} else {
headers.push(getBasicAuthHeader(clientId, clientSecret));
}
const url = setDefaultProtocol(accessTokenUrl);
const response = await sendWithSettings(requestId, {
headers,
url,
method: 'POST',
body: models.request.newBodyFormUrlEncoded(params)
});
const statusCode = response.statusCode || 0;
if (statusCode < 200 || statusCode >= 300) {
2018-06-25 17:42:50 +00:00
throw new Error(
`[oauth2] Failed to refresh token url=${url} status=${statusCode}`
);
}
const bodyBuffer = models.response.getBodyBuffer(response);
if (!bodyBuffer) {
throw new Error(`[oauth2] No body returned from ${url}`);
}
2017-07-05 21:08:57 +00:00
const results = responseToObject(bodyBuffer.toString(), [
c.P_ACCESS_TOKEN,
c.P_REFRESH_TOKEN,
c.P_EXPIRES_IN,
c.P_TOKEN_TYPE,
c.P_SCOPE,
c.P_ERROR,
c.P_ERROR_URI,
c.P_ERROR_DESCRIPTION
]);
return results;
}