2017-11-10 10:50:39 +00:00
|
|
|
// @flow
|
2017-03-23 22:10:42 +00:00
|
|
|
import * as c from './constants';
|
2017-11-26 20:45:40 +00:00
|
|
|
import {buildQueryStringFromParams, joinUrlAndQueryString} from 'insomnia-url';
|
2017-03-23 22:10:42 +00:00
|
|
|
import {responseToObject, authorizeUserInWindow} from './misc';
|
|
|
|
|
2017-11-10 10:50:39 +00:00
|
|
|
export default async function (
|
|
|
|
requestId: string,
|
|
|
|
authorizationUrl: string,
|
|
|
|
clientId: string,
|
2018-01-17 05:18:10 +00:00
|
|
|
responseType: string = c.RESPONSE_TYPE_TOKEN,
|
2017-11-10 10:50:39 +00:00
|
|
|
redirectUri: string = '',
|
|
|
|
scope: string = '',
|
|
|
|
state: string = ''
|
|
|
|
): Promise<Object> {
|
2017-03-23 22:10:42 +00:00
|
|
|
const params = [
|
2018-01-16 06:08:46 +00:00
|
|
|
{name: c.P_RESPONSE_TYPE, value: responseType},
|
2017-03-23 22:10:42 +00:00
|
|
|
{name: c.P_CLIENT_ID, value: clientId}
|
|
|
|
];
|
|
|
|
|
|
|
|
// Add optional params
|
2018-01-17 05:18:10 +00:00
|
|
|
if (responseType === c.RESPONSE_TYPE_ID_TOKEN_TOKEN) {
|
|
|
|
const nonce = Math.floor(Math.random() * 9999999999999) + 1;
|
|
|
|
params.push({name: c.P_NONCE, value: nonce});
|
2018-01-16 06:08:46 +00:00
|
|
|
}
|
2018-01-17 05:18:10 +00:00
|
|
|
|
2017-03-23 22:10:42 +00:00
|
|
|
redirectUri && params.push({name: c.P_REDIRECT_URI, value: redirectUri});
|
|
|
|
scope && params.push({name: c.P_SCOPE, value: scope});
|
|
|
|
state && params.push({name: c.P_STATE, value: state});
|
|
|
|
|
|
|
|
// Add query params to URL
|
2017-11-26 20:45:40 +00:00
|
|
|
const qs = buildQueryStringFromParams(params);
|
|
|
|
const finalUrl = joinUrlAndQueryString(authorizationUrl, qs);
|
2017-03-23 22:10:42 +00:00
|
|
|
|
2018-01-16 06:08:46 +00:00
|
|
|
const redirectedTo = await authorizeUserInWindow(finalUrl, /(access_token=)/, /(error=)/);
|
2017-03-23 22:10:42 +00:00
|
|
|
const fragment = redirectedTo.split('#')[1];
|
|
|
|
|
|
|
|
if (fragment) {
|
|
|
|
return responseToObject(fragment, [
|
|
|
|
c.P_ACCESS_TOKEN,
|
|
|
|
c.P_TOKEN_TYPE,
|
|
|
|
c.P_EXPIRES_IN,
|
|
|
|
c.P_SCOPE,
|
|
|
|
c.P_STATE,
|
|
|
|
c.P_ERROR,
|
|
|
|
c.P_ERROR_DESCRIPTION,
|
|
|
|
c.P_ERROR_URI
|
|
|
|
]);
|
|
|
|
} else {
|
|
|
|
// Bad redirect
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
}
|