This repository has been archived by the owner on Feb 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathutils.js
173 lines (159 loc) · 6.14 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
/*
* Copyright (c) 2017 SugarCRM Inc. Licensed by SugarCRM under the Apache 2.0 license.
*/
/**
* Root URL of SugarCRM instance to test.
* @type {string}
* @private
*/
const ROOT_URL = process.env.THORN_SERVER_URL;
if (!ROOT_URL) {
throw new Error('Please set process.env.THORN_SERVER_URL!');
}
let _ = require('lodash');
let chakram = require('chakram');
/**
* Thorn-private utility functions.
* @namespace
*/
let utils = {
/**
* Ensure that a Chakram response object is sane before using it.
* Throws an error if the response is unreasonable.
*
* @param {ChakramResponse} response Object to check.
*/
assertSaneResponse: function assertSaneResponse(response) {
if (!response) {
throw new Error('Falsy response received!');
}
if (!response.response) {
throw new Error(`Invalid response received! response: ${JSON.stringify(response)}`);
}
},
/**
* Construct a URL relative to the base URL.
* Each argument is joined with a `/`.
*
* @param {...string} pathParts URL path component.
* @return {string} The full URL.
*/
constructUrl: function constructUrl(...pathParts) {
return _.flatten([
ROOT_URL,
'rest',
pathParts,
]).join('/');
},
/**
* Log in as any user.
*
* @param {Object} options Login options.
* @param {string} options.username Username of the user to log in as.
* @param {string} options.password Password of the user to log in as.
* @param {string} options.version API version to use to log in.
* @param {string} options.xthorn Value of the X-Thorn header.
* @return {ChakramPromise} Promise that resolves to the result of the login request.
*/
login: function login(options) {
return this._oauthRequest({
credentials: {
username: options.username,
password: options.password,
grant_type: 'password',
client_id: 'sugar',
client_secret: '',
},
version: options.version,
xthorn: options.xthorn,
});
},
/**
* Refresh the user with the given refresh token.
*
* @param {Object} options Refresh options.
* @param {string} options.version API version to do the refresh request on.
* @param {string} options.token The refresh token of the user you wish to refresh.
* @param {string} options.xthorn Value of the X-Thorn header.
* @return {ChakramPromise} A promise which resolves to the Chakram refresh response.
*/
refresh: function refresh(options) {
return this._oauthRequest({
credentials: {
grant_type: 'refresh_token',
refresh_token: options.token,
client_id: 'sugar',
client_secret: '',
},
version: options.version,
xthorn: options.xthorn,
});
},
/**
* Tries a request. If it fails because of HTTP 401, do a refresh and then
* try again. If it fails because of some other HTTP status code, throw an exception.
*
* @param {function} chakramMethod Chakram request method to call.
* @param {Array} args Arguments to call the chakram request method with.
* The last member of the array must be a `params`-like object.
* @param {Object} options Additional configuration options.
* @param {string} options.refreshToken Refresh token to use if you have to do a refresh.
* @param {function} options.afterRefresh Additional tasks to be performed after
* a refresh occurs. Passed the chakram response object from the refresh.
* @param {string} options.retryVersion API version to make the retry request on.
* Non-retry requests are made on whatever version is specified by `args`.
* @param {string} options.xthorn Value of the X-Thorn header.
* @return {ChakramPromise} A promise resolving to the result of the request.
* If the first try failed, it will resolve to the result of the second,
* whether it succeeded or not.
*/
wrapRequest: function wrapRequest(chakramMethod, args, options) {
let retryVersion = options.retryVersion;
return chakramMethod.apply(chakram, args).then((response) => {
utils.assertSaneResponse(response);
if (response.response.statusCode === 200) {
return response;
}
if (response.response.statusCode !== 401) {
throw response;
}
return utils.refresh({
version: retryVersion,
token: options.refreshToken,
xthorn: options.xthorn,
}).then((response) => {
options.afterRefresh(response);
// FIXME Currently, we have to update the HTTP parameters after the refresh
// to include the OAuth Token.
// Ideally, we would not have to mess with the parameters.
let updatedArgs = _.cloneDeep(args);
let paramIndex = updatedArgs.length - 1;
updatedArgs[paramIndex].headers['OAuth-Token'] = response.body.access_token;
return chakramMethod.apply(chakram, updatedArgs);
});
});
},
/**
* Perform a request against the oauth2/token endpoint.
*
* @param {Object} options OAuth request options.
* @param {Object} options.credentials Request credentials.
* @param {string} options.version API version to make the request against.
* @param {string} options.xthorn Value of the X-Thorn header.
* @return {ChakramPromise} Promise resolving to the result of the request.
*
* @private
*/
_oauthRequest: function _oauthRequest(options) {
let url = utils.constructUrl(options.version, 'oauth2/token');
return chakram.post(url, options.credentials, {
headers: {
'X-Thorn': options.xthorn,
},
}).then((response) => {
utils.assertSaneResponse(response);
return response;
});
},
};
module.exports = utils;