-
Notifications
You must be signed in to change notification settings - Fork 42
/
index.js
304 lines (260 loc) · 7.6 KB
/
index.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
/*
* Copyright (c) 2019-Present, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/
import { NativeModules, Platform, NativeEventEmitter } from 'react-native';
import { assertIssuer, assertClientId, assertRedirectUri } from '@okta/configuration-validation';
import { OktaAuth } from '@okta/okta-auth-js';
import Url from 'url-parse';
import { version, peerDependencies } from './package.json';
// eslint-disable-next-line camelcase
import { jwtDecode } from 'jwt-decode';
// Fixes auth-js warning:
// `Memory storage can only support simple single user use case on server side.`
// OKTA-434739
const memoryState = {};
const storageProvider = {
getItem: function(key) {
return memoryState[key];
},
setItem: function(key, val) {
memoryState[key] = val;
},
removeItem: function(key) {
delete memoryState[key];
}
};
let authClient;
class OktaAuthError extends Error {
constructor(code, message, detail) {
super(message);
this.code = code;
this.detail = detail;
}
}
class OktaStatusError extends Error {
constructor(message, status) {
super(message);
this.status = status;
}
}
/* eslint-disable max-params */
export function createConfigWithCallbacks(
issuer,
clientId,
redirectUri,
endSessionRedirectUri,
discoveryUri,
scopes,
requireHardwareBackedKeyStore,
androidChromeTabColor,
httpConnectionTimeout,
httpReadTimeout,
browserMatchAll = false,
oktaAuthConfig = {},
onSuccess,
onError
) {
assertIssuer(discoveryUri);
assertClientId(clientId);
assertRedirectUri(redirectUri);
assertRedirectUri(endSessionRedirectUri);
const { origin } = new Url(discoveryUri);
oktaAuthConfig = {
...oktaAuthConfig,
storageManager: {
token: {
storageProvider: storageProvider
}
},
issuer: issuer || origin,
clientId,
redirectUri,
scopes
};
authClient = new OktaAuth(oktaAuthConfig);
const reactNativeVersion = peerDependencies['react-native'];
const userAgentTemplate = `okta-react-native/${version} $UPSTREAM_SDK react-native/${reactNativeVersion} ${Platform.OS}/${Platform.Version}`;
if (authClient._oktaUserAgent) {
authClient._oktaUserAgent.addEnvironment(userAgentTemplate.replace('$UPSTREAM_SDK ', ''));
}
httpConnectionTimeout = httpConnectionTimeout || 15;
httpReadTimeout = httpReadTimeout || 10;
if (Platform.OS === 'ios') {
scopes = scopes.join(' ');
NativeModules.OktaSdkBridge.createConfig(
clientId,
redirectUri,
endSessionRedirectUri,
discoveryUri,
scopes,
userAgentTemplate,
httpConnectionTimeout,
onSuccess,
onError
);
} else {
const timeouts = {
httpConnectionTimeout,
httpReadTimeout,
};
NativeModules.OktaSdkBridge.createConfig(
clientId,
redirectUri,
endSessionRedirectUri,
discoveryUri,
scopes,
userAgentTemplate,
requireHardwareBackedKeyStore,
androidChromeTabColor,
timeouts,
browserMatchAll,
onSuccess,
onError
);
}
}
/* eslint-enable max-params */
export const createConfig = async({
issuer,
clientId,
redirectUri,
endSessionRedirectUri,
discoveryUri,
scopes,
requireHardwareBackedKeyStore,
androidChromeTabColor,
httpConnectionTimeout,
httpReadTimeout,
browserMatchAll = false,
oktaAuthConfig = {}
}) => {
return await new Promise((resolve, reject) => {
createConfigWithCallbacks(
issuer,
clientId,
redirectUri,
endSessionRedirectUri,
discoveryUri,
scopes,
requireHardwareBackedKeyStore,
androidChromeTabColor,
httpConnectionTimeout,
httpReadTimeout,
browserMatchAll,
oktaAuthConfig,
successResponse => {
resolve(successResponse);
},
(errorCode, localizedMessage, stackTrace) => {
reject([errorCode, localizedMessage, stackTrace]);
}
);
});
};
export const getAuthClient = () => {
if (!authClient) {
throw new OktaAuthError(
'-100',
'OktaOidc client isn\'t configured, check if you have created a configuration with createConfig'
);
}
return authClient;
};
export const signIn = async(options) => {
// Custom sign in
if (options && typeof options === 'object') {
return getAuthClient().signInWithCredentials(options)
.then((transaction) => {
const { status, sessionToken } = transaction;
if (status !== 'SUCCESS') {
throw new OktaStatusError(
'Transaction status other than "SUCCESS" has been returned. Check transaction.status and handle accordingly.',
status
);
}
return authenticate({ sessionToken });
})
.then(token => {
if (!token) {
throw new Error('Failed to get accessToken');
}
return token;
})
.catch(error => {
throw new OktaAuthError('-1000', 'Sign in was not authorized', error);
});
}
// Browser sign in - Legacy support for non breaking.
return signInWithBrowser();
};
export const signInWithBrowser = async(options = {}) => {
if (typeof options.noSSO === 'boolean') {
options.noSSO = options.noSSO.toString();
}
return NativeModules.OktaSdkBridge.signIn(options);
};
export const signOut = async() => {
return NativeModules.OktaSdkBridge.signOut();
};
export const authenticate = async({sessionToken}) => {
return NativeModules.OktaSdkBridge.authenticate(sessionToken);
};
export const getAccessToken = async() => {
return NativeModules.OktaSdkBridge.getAccessToken();
};
export const getIdToken = async() => {
return NativeModules.OktaSdkBridge.getIdToken();
};
export const getUser = async() => {
return NativeModules.OktaSdkBridge.getUser()
.then(data => {
if (typeof data === 'string') {
try {
return JSON.parse(data);
} catch (e) {
throw new OktaAuthError('-600', 'Okta Oidc error', e);
}
}
return data;
});
};
export const getUserFromIdToken = async() => {
let idTokenResponse = await getIdToken();
return jwtDecode(idTokenResponse.id_token);
};
export const isAuthenticated = async() => {
return NativeModules.OktaSdkBridge.isAuthenticated();
};
export const revokeAccessToken = async() => {
return NativeModules.OktaSdkBridge.revokeAccessToken();
};
export const revokeIdToken = async() => {
return NativeModules.OktaSdkBridge.revokeIdToken();
};
export const revokeRefreshToken = async() => {
return NativeModules.OktaSdkBridge.revokeRefreshToken();
};
export const introspectAccessToken = async() => {
return NativeModules.OktaSdkBridge.introspectAccessToken();
};
export const introspectIdToken = async() => {
return NativeModules.OktaSdkBridge.introspectIdToken();
};
export const introspectRefreshToken = async() => {
return NativeModules.OktaSdkBridge.introspectRefreshToken();
};
export const refreshTokens = async() => {
return NativeModules.OktaSdkBridge.refreshTokens();
};
export const clearTokens = async() => {
return NativeModules.OktaSdkBridge.clearTokens();
};
export const EventEmitter = new NativeEventEmitter(NativeModules.OktaSdkBridge);