2017-11-10 10:50:39 +00:00
|
|
|
// @flow
|
2017-03-23 22:10:42 +00:00
|
|
|
import * as c from './constants';
|
|
|
|
import {responseToObject} from './misc';
|
2017-07-05 21:08:57 +00:00
|
|
|
import {getBasicAuthHeader, setDefaultProtocol} from '../../common/misc';
|
2017-11-10 10:50:39 +00:00
|
|
|
import * as network from '../network';
|
|
|
|
import * as models from '../../models/index';
|
|
|
|
|
|
|
|
export default async function (
|
|
|
|
requestId: string,
|
|
|
|
accessTokenUrl: string,
|
|
|
|
credentialsInBody: boolean,
|
|
|
|
clientId: string,
|
|
|
|
clientSecret: string,
|
|
|
|
refreshToken: string,
|
|
|
|
scope: string
|
|
|
|
): Promise<Object> {
|
2017-03-23 22:10:42 +00:00
|
|
|
const params = [
|
2017-04-20 01:37:40 +00:00
|
|
|
{name: c.P_GRANT_TYPE, value: c.GRANT_TYPE_REFRESH},
|
2017-03-23 22:10:42 +00:00
|
|
|
{name: c.P_REFRESH_TOKEN, value: refreshToken}
|
|
|
|
];
|
|
|
|
|
|
|
|
// Add optional params
|
|
|
|
scope && params.push({name: c.P_SCOPE, value: scope});
|
|
|
|
|
2017-11-10 10:50:39 +00:00
|
|
|
const headers = [
|
|
|
|
{name: 'Content-Type', value: 'application/x-www-form-urlencoded'},
|
|
|
|
{name: 'Accept', value: 'application/x-www-form-urlencoded, application/json'}
|
|
|
|
];
|
2017-03-23 22:10:42 +00:00
|
|
|
|
|
|
|
if (credentialsInBody) {
|
|
|
|
params.push({name: c.P_CLIENT_ID, value: clientId});
|
|
|
|
params.push({name: c.P_CLIENT_SECRET, value: clientSecret});
|
|
|
|
} else {
|
2017-11-10 10:50:39 +00:00
|
|
|
headers.push(getBasicAuthHeader(clientId, clientSecret));
|
2017-03-23 22:10:42 +00:00
|
|
|
}
|
|
|
|
|
2017-11-10 10:50:39 +00:00
|
|
|
const url = setDefaultProtocol(accessTokenUrl);
|
|
|
|
|
|
|
|
const {response, bodyBuffer} = await network.sendWithSettings(requestId, {
|
|
|
|
headers,
|
|
|
|
url,
|
2017-03-23 22:10:42 +00:00
|
|
|
method: 'POST',
|
2017-11-10 10:50:39 +00:00
|
|
|
body: models.request.newBodyFormUrlEncoded(params)
|
|
|
|
});
|
2017-03-23 22:10:42 +00:00
|
|
|
|
2017-11-10 10:50:39 +00:00
|
|
|
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
|
|
throw new Error(`[oauth2] Failed to refresh token url=${url} status=${response.statusCode}`);
|
|
|
|
}
|
2017-07-05 21:08:57 +00:00
|
|
|
|
2017-11-10 10:50:39 +00:00
|
|
|
const results = responseToObject(bodyBuffer.toString(), [
|
2017-03-23 22:10:42 +00:00
|
|
|
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;
|
|
|
|
}
|