This repository has been archived by the owner on Nov 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 60
/
baseConfig.js
477 lines (431 loc) · 17.1 KB
/
baseConfig.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
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
/* eslint-disable max-lines */
import {PLATFORM} from 'aurelia-pal';
import {join} from 'aurelia-path';
import extend from 'extend';
import {logger} from './logger';
export class BaseConfig {
/**
* Prepends baseUrl to a given url
* @param {string} url The relative url to append
* @return {string} joined baseUrl and url
*/
joinBase(url: string): string {
return join(this.baseUrl, url);
}
/**
* Merge current settings with incoming settings
* @param {Object} incoming Settings object to be merged into the current configuration
*/
configure(incoming: {}): Config {
for (let key in incoming) {
if (incoming.hasOwnProperty(key)) {
const value = incoming[key];
if (value !== undefined) {
if (Array.isArray(value) || typeof value !== 'object' || value === null) {
this[key] = value;
} else {
extend(true, this[key], value);
}
}
}
}
}
getOptionsForTokenRequests(options?:{} = {}): {} {
return extend(true, {}, {headers: this.defaultHeadersForTokenRequests}, options);
}
/* ----------- default config ----------- */
// Used internally. The used Rest instance; set during configuration (see index.js)
client: Rest = null;
// If using aurelia-api:
// =====================
// This is the name of the endpoint used for any requests made in relation to authentication (login, logout, etc.). An empty string selects the default endpoint of aurelia-api.
endpoint: string = null;
// When authenticated, these endpoints will have the token added to the header of any requests (for authorization). Accepts an array of endpoint names. An empty string selects the default endpoint of aurelia-api.
configureEndpoints: Array<string> = null;
// SPA related options
// ===================
// The SPA url to which the user is redirected after a successful login
loginRedirect = '#/';
// The SPA url to which the user is redirected after a successful logout
logoutRedirect = '#/';
// The SPA route used when an unauthenticated user tries to access an SPA page that requires authentication
loginRoute = '/login';
// Whether or not an authentication token is provided in the response to a successful signup
loginOnSignup = true;
// If loginOnSignup == false: The SPA url to which the user is redirected after a successful signup (else loginRedirect is used)
signupRedirect = '#/login';
// The SPA url to load when the token expires
expiredRedirect = '#/';
// The SPA url to load when the authentication status changed in other tabs/windows (detected through storageEvents)
storageChangedRedirect = '#/';
// API related options
// ===================
// The base url used for all authentication related requests, including provider.url below.
// This appends to the httpClient/endpoint base url, it does not override it.
baseUrl = '';
// The API endpoint to which login requests are sent
loginUrl = '/auth/login';
// The API endpoint to which logout requests are sent (not needed for jwt)
logoutUrl = null;
// The HTTP method used for 'unlink' requests (Options: 'get' or 'post')
logoutMethod = 'get';
// The API endpoint to which signup requests are sent
signupUrl = '/auth/signup';
// The API endpoint used in profile requests (inc. `find/get` and `update`)
profileUrl = '/auth/me';
// The method used to update the profile ('put' or 'patch')
profileMethod = 'put';
// The API endpoint used with oAuth to unlink authentication
unlinkUrl = '/auth/unlink/';
// The HTTP method used for 'unlink' requests (Options: 'get' or 'post')
unlinkMethod = 'get';
// The API endpoint to which refreshToken requests are sent. null = loginUrl
refreshTokenUrl = null;
// Token Options
// =============
// The header property used to contain the authToken in the header of API requests that require authentication
authHeader = 'Authorization';
// The token name used in the header of API requests that require authentication
authTokenType = 'Bearer';
// Logout when the token is invalidated by the server
logoutOnInvalidToken = false;
// The the property from which to get the access token after a successful login or signup. Can also be dotted eg "accessTokenProp.accessTokenName"
accessTokenProp = 'access_token';
// If the property defined by `accessTokenProp` is an object:
// ------------------------------------------------------------
//This is the property from which to get the token `{ "accessTokenProp": { "accessTokenName" : '...' } }`
accessTokenName = 'token';
// This allows the token to be a further object deeper `{ "accessTokenProp": { "accessTokenRoot" : { "accessTokenName" : '...' } } }`
accessTokenRoot = false;
// Refresh Token Options
// =====================
// Option to turn refresh tokens On/Off
useRefreshToken = false;
// The option to enable/disable the automatic refresh of Auth tokens using Refresh Tokens
autoUpdateToken = true;
// Oauth Client Id
clientId = false;
// Oauth Client secret
clientSecret = null;
// The the property from which to get the refresh token after a successful token refresh. Can also be dotted eg "refreshTokenProp.refreshTokenProp"
refreshTokenProp = 'refresh_token';
// The property name used to send the existing token when refreshing `{ "refreshTokenSubmitProp": '...' }`
refreshTokenSubmitProp = 'refresh_token';
// Option to maintain unchanged response properties This allows to work with a single refresh_token that was received once and the expiration only is extend
keepOldResponseProperties = false;
// If the property defined by `refreshTokenProp` is an object:
// -----------------------------------------------------------
// This is the property from which to get the token `{ "refreshTokenProp": { "refreshTokenName" : '...' } }`
refreshTokenName = 'token';
// This allows the refresh token to be a further object deeper `{ "refreshTokenProp": { "refreshTokenRoot" : { "refreshTokenName" : '...' } } }`
refreshTokenRoot = false;
// The property name from which to get the user authentication token. Can also be dotted idTokenProp.idTokenName
idTokenProp = 'id_token';
// This is the property from which to get the id token `{ "idTokenProp": { "idTokenName" : '...' } }`
idTokenName = 'token';
// This allows the id_token to be a further object deeper `{ "idTokenProp": { "idTokenRoot" : { "idTokenName" : '...' } } }`
idTokenRoot = false;
// Miscellaneous Options
// =====================
// Whether to enable the fetch interceptor which automatically adds the authentication headers
// (or not... e.g. if using a session based API or you want to override the default behaviour)
httpInterceptor = true;
// For OAuth only: Tell the API whether or not to include token cookies in the response (for session based APIs)
withCredentials = true;
// Controls how the popup is shown for different devices (Options: 'browser' or 'mobile')
platform = 'browser';
// Determines the `PLATFORM` property name upon which aurelia-authentication data is stored (Default: `PLATFORM.localStorage`)
storage = 'localStorage';
// The key used for storing the authentication response locally
storageKey = 'aurelia_authentication';
// full page reload if authorization changed in another tab (recommended to set it to 'true')
storageChangedReload = false;
// optional function to extract the expiration date. Takes the server response as parameter and returns NumericDate = number of seconds! since 1 January 1970 00:00:00 UTC (Unix Epoch)
// eg (expires_in in sec): getExpirationDateFromResponse = serverResponse => new Date().getTime() / 1000 + serverResponse.expires_in;
getExpirationDateFromResponse = null;
// optional function to extract the access token from the response. Takes the server response as parameter and returns a token
// eg: getAccessTokenFromResponse = serverResponse => serverResponse.data[0].access_token;
getAccessTokenFromResponse = null;
// optional function to extract the refresh token from the response. Takes the server response as parameter and returns a token
// eg: getRefreshTokenFromResponse = serverResponse => serverResponse.data[0].refresh_token;
getRefreshTokenFromResponse = null;
// List of value-converters to make global
globalValueConverters = ['authFilterValueConverter'];
// Default headers for login and token-update endpoint
defaultHeadersForTokenRequests = {
'Content-Type': 'application/json'
}
//OAuth provider specific related configuration
// ============================================
providers = {
facebook: {
name : 'facebook',
url : '/auth/facebook',
authorizationEndpoint: 'https://www.facebook.com/v2.5/dialog/oauth',
redirectUri : PLATFORM.location.origin + '/',
requiredUrlParams : ['display', 'scope'],
scope : ['email'],
scopeDelimiter : ',',
display : 'popup',
oauthType : '2.0',
popupOptions : {width: 580, height: 400}
},
google: {
name : 'google',
url : '/auth/google',
authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',
redirectUri : PLATFORM.location.origin,
requiredUrlParams : ['scope'],
optionalUrlParams : ['display', 'state'],
scope : ['profile', 'email'],
scopePrefix : 'openid',
scopeDelimiter : ' ',
display : 'popup',
oauthType : '2.0',
popupOptions : {width: 452, height: 633},
state : randomState
},
github: {
name : 'github',
url : '/auth/github',
authorizationEndpoint: 'https://github.com/login/oauth/authorize',
redirectUri : PLATFORM.location.origin,
optionalUrlParams : ['scope'],
scope : ['user:email'],
scopeDelimiter : ' ',
oauthType : '2.0',
popupOptions : {width: 1020, height: 618}
},
instagram: {
name : 'instagram',
url : '/auth/instagram',
authorizationEndpoint: 'https://api.instagram.com/oauth/authorize',
redirectUri : PLATFORM.location.origin,
requiredUrlParams : ['scope'],
scope : ['basic'],
scopeDelimiter : '+',
oauthType : '2.0'
},
linkedin: {
name : 'linkedin',
url : '/auth/linkedin',
authorizationEndpoint: 'https://www.linkedin.com/uas/oauth2/authorization',
redirectUri : PLATFORM.location.origin,
requiredUrlParams : ['state'],
scope : ['r_emailaddress'],
scopeDelimiter : ' ',
state : 'STATE',
oauthType : '2.0',
popupOptions : {width: 527, height: 582}
},
twitter: {
name : 'twitter',
url : '/auth/twitter',
authorizationEndpoint: 'https://api.twitter.com/oauth/authenticate',
redirectUri : PLATFORM.location.origin,
oauthType : '1.0',
popupOptions : {width: 495, height: 645}
},
twitch: {
name : 'twitch',
url : '/auth/twitch',
authorizationEndpoint: 'https://api.twitch.tv/kraken/oauth2/authorize',
redirectUri : PLATFORM.location.origin,
requiredUrlParams : ['scope'],
scope : ['user_read'],
scopeDelimiter : ' ',
display : 'popup',
oauthType : '2.0',
popupOptions : {width: 500, height: 560}
},
live: {
name : 'live',
url : '/auth/live',
authorizationEndpoint: 'https://login.live.com/oauth20_authorize.srf',
redirectUri : PLATFORM.location.origin,
requiredUrlParams : ['display', 'scope'],
scope : ['wl.emails'],
scopeDelimiter : ' ',
display : 'popup',
oauthType : '2.0',
popupOptions : {width: 500, height: 560}
},
yahoo: {
name : 'yahoo',
url : '/auth/yahoo',
authorizationEndpoint: 'https://api.login.yahoo.com/oauth2/request_auth',
redirectUri : PLATFORM.location.origin,
scope : [],
scopeDelimiter : ',',
oauthType : '2.0',
popupOptions : {width: 559, height: 519}
},
bitbucket: {
name : 'bitbucket',
url : '/auth/bitbucket',
authorizationEndpoint: 'https://bitbucket.org/site/oauth2/authorize',
redirectUri : PLATFORM.location.origin + '/',
requiredUrlParams : ['scope'],
scope : ['email'],
scopeDelimiter : ' ',
oauthType : '2.0',
popupOptions : {width: 1028, height: 529}
},
azure_ad: {
name : 'azure_ad',
url : '/auth/azure_ad',
authorizationEndpoint: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
redirectUri : PLATFORM.location.origin,
logoutEndpoint : 'https://login.microsoftonline.com/common/oauth2/v2.0/logout',
postLogoutRedirectUri: PLATFORM.location.origin,
requiredUrlParams : ['scope'],
scope : ['user.read'],
scopeDelimiter : ' ',
oauthType : '2.0'
},
auth0: {
name : 'auth0',
oauthType : 'auth0-lock',
clientId : 'your_client_id',
clientDomain: 'your_domain_url',
display : 'popup',
lockOptions : {},
responseType: 'token',
state : randomState
}
};
/* deprecated defaults */
/**
* @deprecated
*/
_authToken = 'Bearer';
/**
* @deprecated
*/
_responseTokenProp = 'access_token';
/**
* @deprecated
*/
_tokenName = 'token';
/**
* @deprecated
*/
_tokenRoot = false;
/**
* @deprecated
*/
_tokenPrefix = 'aurelia';
/**
* @deprecated
*/
_logoutOnInvalidtoken = false;
/* deprecated methods and parameters */
/**
* @param {string} authToken
* @deprecated
*/
set authToken(authToken) {
logger.warn('BaseConfig.authToken is deprecated. Use BaseConfig.authTokenType instead.');
this._authTokenType = authToken;
this.authTokenType = authToken;
return authToken;
}
get authToken() {
return this._authTokenType;
}
/**
* @param {string} responseTokenProp
* @deprecated
*/
set responseTokenProp(responseTokenProp) {
logger.warn('BaseConfig.responseTokenProp is deprecated. Use BaseConfig.accessTokenProp instead.');
this._responseTokenProp = responseTokenProp;
this.accessTokenProp = responseTokenProp;
return responseTokenProp;
}
get responseTokenProp() {
return this._responseTokenProp;
}
/**
* @param {string} tokenRoot
* @deprecated
*/
set tokenRoot(tokenRoot) {
logger.warn('BaseConfig.tokenRoot is deprecated. Use BaseConfig.accessTokenRoot instead.');
this._tokenRoot = tokenRoot;
this.accessTokenRoot = tokenRoot;
return tokenRoot;
}
get tokenRoot() {
return this._tokenRoot;
}
/**
* @param {string} tokenName
* @deprecated
*/
set tokenName(tokenName) {
logger.warn('BaseConfig.tokenName is deprecated. Use BaseConfig.accessTokenName instead.');
this._tokenName = tokenName;
this.accessTokenName = tokenName;
return tokenName;
}
get tokenName() {
return this._tokenName;
}
/**
* @param {string} tokenPrefix
* @deprecated
*/
set tokenPrefix(tokenPrefix) {
logger.warn('BaseConfig.tokenPrefix is obsolete. Use BaseConfig.storageKey instead.');
this._tokenPrefix = tokenPrefix;
return tokenPrefix;
}
get tokenPrefix() {
return this._tokenPrefix || 'aurelia';
}
/**
* @deprecated
*/
get current() {
logger.warn('Getter BaseConfig.current is deprecated. Use BaseConfig directly instead.');
return this;
}
set current(_) {
throw new Error('Setter BaseConfig.current has been removed. Use BaseConfig directly instead.');
}
/**
* @deprecated
*/
get _current() {
logger.warn('Getter BaseConfig._current is deprecated. Use BaseConfig directly instead.');
return this;
}
set _current(_) {
throw new Error('Setter BaseConfig._current has been removed. Use BaseConfig directly instead.');
}
/**
* @param {string} logoutOnInvalidtoken
* @deprecated
*/
set logoutOnInvalidtoken(logoutOnInvalidtoken) {
logger.warn('BaseConfig.logoutOnInvalidtoken is obsolete. Use BaseConfig.logoutOnInvalidToken instead.');
this._logoutOnInvalidtoken = logoutOnInvalidtoken;
this.logoutOnInvalidToken = logoutOnInvalidtoken;
return logoutOnInvalidtoken;
}
get logoutOnInvalidtoken() {
return this._logoutOnInvalidtoken;
}
}
/**
* RandomState
*
* @returns {number}
*/
function randomState() {
let rand = Math.random()
.toString(36)
.substr(2);
return encodeURIComponent(rand);
}