-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathAuth.ts
More file actions
350 lines (334 loc) · 12 KB
/
Auth.ts
File metadata and controls
350 lines (334 loc) · 12 KB
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/* eslint-disable no-var */
import axios, { CancelToken } from 'axios'
import { AccessToken } from '../models/AccessToken'
import Configuration from '../Configuration'
import { ApiRole } from '../models/ApiRole'
import paramsSerializer from '../utils/ParamsSerializer'
import { RequiredDeep } from '../models/RequiredDeep'
import OrderCloudError from '../utils/OrderCloudError'
class Auth {
constructor() {
if (typeof axios === 'undefined') {
throw new Error(
'Ordercloud is missing required peer dependency axios. This must be installed and loaded before the OrderCloud SDK'
)
}
/**
* @ignore
* not part of public api, don't include in generated docs
*/
this.Anonymous = this.Anonymous.bind(this)
this.ClientCredentials = this.ClientCredentials.bind(this)
this.ElevatedLogin = this.ElevatedLogin.bind(this)
this.Login = this.Login.bind(this)
this.RefreshToken = this.RefreshToken.bind(this)
}
/**
* @description this workflow is most appropriate for client apps where user is a human, ie a registered user
*
* @param username of the user logging in
* @param password of the user logging in
* @param client_id of the application the user is logging into
* @param scope optional roles being requested, if omitted will return all assigned roles
* @param customRoles optional custom roles being requested - string array
* @param requestOptions.cancelToken Provide an [axios cancelToken](https://github.com/axios/axios#cancellation) that can be used to cancel the request.
* @param requestOptions.requestType Provide a value that can be used to identify the type of request. Useful for error logs.
*/
public async Login(
username: string,
password: string,
clientID: string,
scope?: ApiRole[],
customRoles?: string[],
requestOptions: {
cancelToken?: CancelToken
requestType?: string
} = {}
): Promise<RequiredDeep<AccessToken>> {
if (scope && !Array.isArray(scope)) {
throw new Error('scope must be a string array')
}
if (customRoles != null && !Array.isArray(customRoles)) {
throw new Error('custom roles must be defined as a string array')
}
let _scope: string | undefined
if (scope?.length && !customRoles?.length) {
_scope = scope.join(' ')
} else if (!scope?.length && customRoles?.length) {
_scope += ` ${customRoles.join(' ')}`
} else if (scope?.length && customRoles?.length) {
_scope = `${scope.join(' ')} ${customRoles.join(' ')}`
}
const body = {
grant_type: 'password',
username,
password,
client_id: clientID,
scope: _scope,
}
const configuration = Configuration.Get()
const response = await axios
.post(
`${configuration.baseApiUrl}/oauth/token`,
paramsSerializer.serialize(body),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
},
adapter: configuration.axiosAdapter,
...requestOptions,
}
)
.catch(e => {
if (e.response) {
throw new OrderCloudError(e)
}
throw e
})
return response.data
}
/**
* @description similar to login except client secret is also required, adding another level of security
*
* @param clientSecret of the application
* @param username of the user logging in
* @param password of the user logging in
* @param clientID of the application the user is logging into
* @param scope roles being requested - space delimited string or array
* @param customRoles optional custom roles being requested - string array
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
* @param requestOptions.cancelToken Provide an [axios cancelToken](https://github.com/axios/axios#cancellation) that can be used to cancel the request.
* @param requestOptions.requestType Provide a value that can be used to identify the type of request. Useful for error logs.
*/
public async ElevatedLogin(
clientSecret: string,
username: string,
password: string,
clientID: string,
scope?: ApiRole[],
customRoles?: string[],
requestOptions: {
cancelToken?: CancelToken
requestType?: string
} = {}
): Promise<RequiredDeep<AccessToken>> {
if (scope && !Array.isArray(scope)) {
throw new Error('scope must be a string array')
}
if (customRoles != null && !Array.isArray(customRoles)) {
throw new Error('custom roles must be defined as a string array')
}
let _scope: string | undefined
if (scope?.length && !customRoles?.length) {
_scope = scope.join(' ')
} else if (!scope?.length && customRoles?.length) {
_scope += ` ${customRoles.join(' ')}`
} else if (scope?.length && customRoles?.length) {
_scope = `${scope.join(' ')} ${customRoles.join(' ')}`
}
const body = {
grant_type: 'password',
scope: _scope,
client_id: clientID,
username,
password,
client_secret: clientSecret,
}
const configuration = Configuration.Get()
const response = await axios
.post(
`${configuration.baseApiUrl}/oauth/token`,
paramsSerializer.serialize(body),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
},
adapter: configuration.axiosAdapter,
...requestOptions,
}
)
.catch(e => {
if (e.response) {
throw new OrderCloudError(e)
}
throw e
})
return response.data
}
/**
* @description this workflow is best suited for a backend system
*
* @param clientSecret of the application
* @param clientID of the application the user is logging into
* @param scope roles being requested - space delimited string or array
* @param customRoles optional custom roles being requested - string array
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
* @param requestOptions.cancelToken Provide an [axios cancelToken](https://github.com/axios/axios#cancellation) that can be used to cancel the request.
* @param requestOptions.requestType Provide a value that can be used to identify the type of request. Useful for error logs.
*/
public async ClientCredentials(
clientSecret: string,
clientID: string,
scope?: ApiRole[],
customRoles?: string[],
requestOptions: {
cancelToken?: CancelToken
requestType?: string
} = {}
): Promise<RequiredDeep<AccessToken>> {
if (scope && !Array.isArray(scope)) {
throw new Error('scope must be a string array')
}
if (customRoles != null && !Array.isArray(customRoles)) {
throw new Error('custom roles must be defined as a string array')
}
let _scope: string | undefined
if (scope?.length && !customRoles?.length) {
_scope = scope.join(' ')
} else if (!scope?.length && customRoles?.length) {
_scope += ` ${customRoles.join(' ')}`
} else if (scope?.length && customRoles?.length) {
_scope = `${scope.join(' ')} ${customRoles.join(' ')}`
}
const body = {
grant_type: 'client_credentials',
scope: _scope,
client_id: clientID,
client_secret: clientSecret,
}
const configuration = Configuration.Get()
const response = await axios
.post(
`${configuration.baseApiUrl}/oauth/token`,
paramsSerializer.serialize(body),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
},
adapter: configuration.axiosAdapter,
...requestOptions,
}
)
.catch(e => {
if (e.response) {
throw new OrderCloudError(e)
}
throw e
})
return response.data
}
/**
* @description extend your users' session by getting a new access token with a refresh token. refresh tokens must be enabled in the dashboard
*
* @param refreshToken of the application
* @param clientID of the application the user is logging into
* @param requestOptions.cancelToken Provide an [axios cancelToken](https://github.com/axios/axios#cancellation) that can be used to cancel the request.
* @param requestOptions.requestType Provide a value that can be used to identify the type of request. Useful for error logs.
*/
public async RefreshToken(
refreshToken: string,
clientID: string,
requestOptions: {
cancelToken?: CancelToken
requestType?: string
} = {}
): Promise<RequiredDeep<AccessToken>> {
const body = {
grant_type: 'refresh_token',
client_id: clientID,
refresh_token: refreshToken,
}
const configuration = Configuration.Get()
const response = await axios
.post(
`${configuration.baseApiUrl}/oauth/token`,
paramsSerializer.serialize(body),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
},
adapter: configuration.axiosAdapter,
...requestOptions,
}
)
.catch(e => {
if (e.response) {
throw new OrderCloudError(e)
}
throw e
})
return response.data
}
/**
* @description allow users to browse your catalog without signing in - must have anonymous template user set in dashboard
*
* @param clientID of the application the user is logging into
* @param scope roles being requested - space delimited string or array
* @param customRoles optional custom roles being requested - string array
* @param requestOptions.anonuserid Provide an externally generated id to track this user session, used specifically for the tracking events feature for integrating with Send and Discover
* @param requestOptions.cancelToken Provide an [axios cancelToken](https://github.com/axios/axios#cancellation) that can be used to cancel the request.
* @param requestOptions.requestType Provide a value that can be used to identify the type of request. Useful for error logs.
*/
public async Anonymous(
clientID: string,
scope?: ApiRole[],
customRoles?: string[],
requestOptions: {
anonuserid?: string
cancelToken?: CancelToken
requestType?: string
} = {}
): Promise<RequiredDeep<AccessToken>> {
if (scope && !Array.isArray(scope)) {
throw new Error('scope must be a string array')
}
if (customRoles != null && !Array.isArray(customRoles)) {
throw new Error('custom roles must be defined as a string array')
}
let _scope: string | undefined
if (scope?.length && !customRoles?.length) {
_scope = scope.join(' ')
} else if (!scope?.length && customRoles?.length) {
_scope += ` ${customRoles.join(' ')}`
} else if (scope?.length && customRoles?.length) {
_scope = `${scope.join(' ')} ${customRoles.join(' ')}`
}
const body = {
grant_type: 'client_credentials',
client_id: clientID,
scope: _scope,
}
if (requestOptions.anonuserid) {
body['anonuserid'] = requestOptions.anonuserid
delete requestOptions['anonuserid']
}
const configuration = Configuration.Get()
const response = await axios
.post(
`${configuration.baseApiUrl}/oauth/token`,
paramsSerializer.serialize(body),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
},
adapter: configuration.axiosAdapter,
...requestOptions,
}
)
.catch(e => {
if (e.response) {
throw new OrderCloudError(e)
}
throw e
})
return response.data
}
}
export default new Auth()