2017-08-21 17:43:12 +00:00
|
|
|
import {AUTH_BASIC, AUTH_BEARER, AUTH_OAUTH_2, AUTH_HAWK} from '../common/constants';
|
2017-06-01 13:18:42 +00:00
|
|
|
import {getBasicAuthHeader, getBearerAuthHeader} from '../common/misc';
|
2017-03-23 22:10:42 +00:00
|
|
|
import getOAuth2Token from './o-auth-2/get-token';
|
2017-08-21 17:43:12 +00:00
|
|
|
import * as Hawk from 'hawk';
|
2017-03-23 22:10:42 +00:00
|
|
|
|
2017-08-21 17:43:12 +00:00
|
|
|
export async function getAuthHeader (requestId, url, method, authentication) {
|
2017-03-23 22:10:42 +00:00
|
|
|
if (authentication.disabled) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (authentication.type === AUTH_BASIC) {
|
|
|
|
const {username, password} = authentication;
|
|
|
|
return getBasicAuthHeader(username, password);
|
|
|
|
}
|
|
|
|
|
2017-06-01 13:18:42 +00:00
|
|
|
if (authentication.type === AUTH_BEARER) {
|
|
|
|
const {token} = authentication;
|
|
|
|
return getBearerAuthHeader(token);
|
|
|
|
}
|
|
|
|
|
2017-03-23 22:10:42 +00:00
|
|
|
if (authentication.type === AUTH_OAUTH_2) {
|
|
|
|
const oAuth2Token = await getOAuth2Token(requestId, authentication);
|
|
|
|
if (oAuth2Token) {
|
2017-04-07 18:10:15 +00:00
|
|
|
const token = oAuth2Token.accessToken;
|
2017-08-10 19:34:33 +00:00
|
|
|
return _buildBearerHeader(token, authentication.tokenPrefix);
|
2017-03-23 22:10:42 +00:00
|
|
|
} else {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-08-21 17:43:12 +00:00
|
|
|
if (authentication.type === AUTH_HAWK) {
|
|
|
|
const {id, key, algorithm} = authentication;
|
|
|
|
|
|
|
|
const header = Hawk.client.header(
|
|
|
|
url,
|
|
|
|
method,
|
|
|
|
{credentials: {id, key, algorithm}}
|
|
|
|
);
|
|
|
|
|
|
|
|
return {
|
|
|
|
name: 'Authorization',
|
|
|
|
value: header.field
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2017-03-23 22:10:42 +00:00
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2017-08-10 19:34:33 +00:00
|
|
|
function _buildBearerHeader (accessToken, prefix) {
|
2017-03-23 22:10:42 +00:00
|
|
|
if (!accessToken) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
const name = 'Authorization';
|
2017-08-10 19:34:33 +00:00
|
|
|
const value = `${prefix || 'Bearer'} ${accessToken}`;
|
2017-03-23 22:10:42 +00:00
|
|
|
|
|
|
|
return {name, value};
|
|
|
|
}
|