@asgardeo/auth-react 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json ADDED
@@ -0,0 +1,75 @@
1
+ {
2
+ "name": "@asgardeo/auth-react",
3
+ "version": "0.2.1",
4
+ "description": "Asgardeo Auth React SDK for React Applications.",
5
+ "keywords": [
6
+ "WSO2",
7
+ "WSO2-IS",
8
+ "WSO2 Identity Server",
9
+ "WSO2 Identity Apps",
10
+ "authentication",
11
+ "OIDC",
12
+ "SDK",
13
+ "Javascript",
14
+ "Asgardeo",
15
+ "React"
16
+ ],
17
+ "main": "dist/main.js",
18
+ "types": "dist/src/index.d.ts",
19
+ "module": "dist/main.js",
20
+ "scripts": {
21
+ "lint": "tslint -t stylish --project .",
22
+ "build": "rimraf dist && npm run type-check && webpack -p --env.NODE_ENV=production",
23
+ "build:dev": "rimraf dist && npm run type-check && webpack -p --env.NODE_ENV=developement",
24
+ "type-check": "tsc --emitDeclarationOnly",
25
+ "type-check:watch": "npm run type-check -- --watch"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/asgardeo/asgardeo-auth-react-sdk.git"
30
+ },
31
+ "bugs": {
32
+ "url": "https://github.com/asgardeo/asgardeo-auth-react-sdk/issues"
33
+ },
34
+ "homepage": "https://github.com/asgardeo/asgardeo-auth-react-sdk#readme",
35
+ "author": "WSO2",
36
+ "license": "Apache-2.0",
37
+ "dependencies": {
38
+ "@asgardeo/auth-spa": "^0.2.2"
39
+ },
40
+ "devDependencies": {
41
+ "@babel/cli": "^7.10.5",
42
+ "@babel/core": "^7.11.4",
43
+ "@babel/plugin-proposal-class-properties": "^7.10.4",
44
+ "@babel/plugin-proposal-decorators": "^7.10.5",
45
+ "@babel/plugin-transform-modules-commonjs": "^7.6.0",
46
+ "@babel/preset-env": "^7.11.0",
47
+ "@babel/preset-react": "^7.6.3",
48
+ "@babel/preset-typescript": "^7.10.4",
49
+ "@babel/runtime-corejs3": "^7.11.2",
50
+ "@types/node": "^13.9.2",
51
+ "@typescript-eslint/eslint-plugin": "^2.19.2",
52
+ "@typescript-eslint/parser": "^3.10.1",
53
+ "babel-loader": "^8.1.0",
54
+ "core-js": "^3.8.3",
55
+ "eslint": "^6.8.0",
56
+ "eslint-loader": "^3.0.3",
57
+ "eslint-plugin-import": "^2.20.2",
58
+ "eslint-plugin-react": "^7.19.0",
59
+ "eslint-plugin-react-hooks": "^4.0.0",
60
+ "react": "^16.14.0",
61
+ "react-dom": "16.14.0",
62
+ "react-router-dom": "^5.2.0",
63
+ "rimraf": "^3.0.2",
64
+ "typescript": "^3.9.7",
65
+ "webpack": "^4.41.5",
66
+ "webpack-cli": "^3.3.7",
67
+ "worker-loader": "^2.0.0"
68
+ },
69
+ "peerDependencies": {
70
+ "@babel/runtime-corejs3": "^7.11.2",
71
+ "react": "^16.14.0",
72
+ "react-dom": "16.14.0",
73
+ "react-router-dom": "^5.2.0"
74
+ }
75
+ }
package/src/actions.ts ADDED
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
3
+ *
4
+ * WSO2 Inc. licenses this file to you under the Apache License,
5
+ * Version 2.0 (the "License"); you may not use this file except
6
+ * in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing,
12
+ * software distributed under the License is distributed on an
13
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ * KIND, either express or implied. See the License for the
15
+ * specific language governing permissions and limitations
16
+ * under the License.
17
+ */
18
+
19
+ /**
20
+ * AuthContext reducer actions enum.
21
+ */
22
+ export enum AuthContextReducerActionTypes {
23
+ SET_SIGN_IN = "SET_SIGN_IN",
24
+ SET_SIGN_OUT = "SET_SIGN_OUT",
25
+ SET_PROFILE_INFO = "SET_PROFILE_INFO"
26
+ }
27
+
28
+ /**
29
+ * Set Sign In State reducer action.
30
+ */
31
+ export const setSignIn = (response: any) => ({
32
+ payload: response,
33
+ type: AuthContextReducerActionTypes.SET_SIGN_IN
34
+ });
35
+
36
+ /**
37
+ * Set Sign Out State reducer action.
38
+ */
39
+ export const setSignOut = () => ({
40
+ type: AuthContextReducerActionTypes.SET_SIGN_OUT
41
+ });
42
+
43
+ /**
44
+ * Set Profile Info reducer action.
45
+ *
46
+ * @param {any} details - Profile details
47
+ */
48
+ export const setProfileInfo = (details: any) => ({
49
+ payload: details,
50
+ type: AuthContextReducerActionTypes.SET_PROFILE_INFO
51
+ });
package/src/api.ts ADDED
@@ -0,0 +1,394 @@
1
+ /**
2
+ * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
3
+ *
4
+ * WSO2 Inc. licenses this file to you under the Apache License,
5
+ * Version 2.0 (the "License"); you may not use this file except
6
+ * in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing,
12
+ * software distributed under the License is distributed on an
13
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ * KIND, either express or implied. See the License for the
15
+ * specific language governing permissions and limitations
16
+ * under the License.
17
+ */
18
+
19
+ import {
20
+ AsgardeoSPAClient,
21
+ AuthClientConfig,
22
+ BasicUserInfo,
23
+ Config,
24
+ CustomGrantConfig,
25
+ DecodedIDTokenPayload,
26
+ Hooks,
27
+ HttpClientInstance,
28
+ HttpRequestConfig,
29
+ HttpResponse,
30
+ OIDCEndpoints,
31
+ SignInConfig
32
+ } from "@asgardeo/auth-spa";
33
+ import { AuthStateInterface } from "./models";
34
+
35
+ class AuthAPI {
36
+ static DEFAULT_STATE: AuthStateInterface;
37
+
38
+ private _authState = AuthAPI.DEFAULT_STATE;
39
+ private _client: AsgardeoSPAClient;
40
+
41
+ constructor() {
42
+ this._client = AsgardeoSPAClient.getInstance();
43
+
44
+ this.getState = this.getState.bind(this);
45
+ this.init = this.init.bind(this);
46
+ this.signIn = this.signIn.bind(this);
47
+ this.signOut = this.signOut.bind(this);
48
+ this.updateState = this.updateState.bind(this);
49
+ }
50
+
51
+ /**
52
+ * Method to return Auth Client instance authentication state.
53
+ *
54
+ * @return {AuthStateInterface} Authentication State.
55
+ */
56
+ public getState(): AuthStateInterface {
57
+ return this._authState;
58
+ }
59
+
60
+ /**
61
+ * Method to initialize the AuthClient instance.
62
+ *
63
+ * @param {Config} config - `dispatch` function from React Auth Context.
64
+ */
65
+ public init(config: AuthClientConfig<Config>): Promise<boolean> {
66
+ return this._client.initialize(config);
67
+ }
68
+
69
+ /**
70
+ * Method to handle user Sign In requests.
71
+ *
72
+ * @param {any} dispatch - `dispatch` function from React Auth Context.
73
+ * @param {AuthStateInterface} state - Current authentication state in React Auth Context.
74
+ * @param {any} callback - Action to trigger on successful sign in.
75
+ */
76
+ public async signIn(
77
+ dispatch: (state: AuthStateInterface) => void,
78
+ state: AuthStateInterface,
79
+ config: SignInConfig,
80
+ authorizationCode: string,
81
+ sessionState: string,
82
+ callback?: (response: BasicUserInfo) => void
83
+ ): Promise<void> {
84
+ this._client.on(Hooks.SignIn, (response) => {
85
+ const stateToUpdate = {
86
+ allowedScopes: response.allowedScopes,
87
+ displayName: response.displayName,
88
+ email: response.email,
89
+ isAuthenticated: true,
90
+ isLoading: false,
91
+ username: response.username
92
+ };
93
+
94
+ this.updateState(stateToUpdate);
95
+
96
+ dispatch({ ...state, ...stateToUpdate });
97
+
98
+ if (callback) {
99
+ callback(response);
100
+ }
101
+ });
102
+ await this._client.signIn(config, authorizationCode, sessionState);
103
+ }
104
+
105
+ /**
106
+ * Method to handle user Sign Out requests.
107
+ *
108
+ * @param {any} dispatch - `dispatch` function from React Auth Context.
109
+ * @param {AuthStateInterface} state - Current authentication state in React Auth Context.
110
+ * @param {any} callback - Action to trigger on successful sign out.
111
+ */
112
+ public signOut(
113
+ dispatch: (state: AuthStateInterface) => void,
114
+ state: AuthStateInterface,
115
+ callback?: () => void
116
+ ): void {
117
+ this._client.on(Hooks.SignOut, () => {
118
+ const stateToUpdate = AuthAPI.DEFAULT_STATE;
119
+
120
+ this.updateState(stateToUpdate);
121
+
122
+ dispatch({ ...state, ...stateToUpdate });
123
+
124
+ if (callback) {
125
+ callback();
126
+ }
127
+ });
128
+
129
+ this._client.signOut();
130
+ }
131
+
132
+ /**
133
+ * Method to update Auth Client instance authentication state.
134
+ *
135
+ * @param {AuthStateInterface} state - State values to update in authentication state.
136
+ */
137
+ public updateState(state: AuthStateInterface): void {
138
+ this._authState = { ...this._authState, ...state };
139
+ }
140
+
141
+ /**
142
+ * This method returns a Promise that resolves with the basic user information obtained from the ID token.
143
+ *
144
+ * @return {Promise<BasicUserInfo>} - A promise that resolves with the user information.
145
+ */
146
+ public async getBasicUserInfo(): Promise<BasicUserInfo> {
147
+ return this._client.getBasicUserInfo();
148
+ }
149
+
150
+ /**
151
+ * This method sends an API request to a protected endpoint.
152
+ * The access token is automatically attached to the header of the request.
153
+ * This is the only way by which protected endpoints can be accessed
154
+ * when the web worker is used to store session information.
155
+ *
156
+ * @param {HttpRequestConfig} config - The config object containing attributes necessary to send a request.
157
+ *
158
+ * @return {Promise<HttpResponse>} - Returns a Promise that resolves with the response to the request.
159
+ */
160
+ public async httpRequest(config: HttpRequestConfig): Promise<HttpResponse<any>> {
161
+ return this._client.httpRequest(config);
162
+ }
163
+
164
+ /**
165
+ * This method sends multiple API requests to a protected endpoint.
166
+ * The access token is automatically attached to the header of the request.
167
+ * This is the only way by which multiple requests can be sent to protected endpoints
168
+ * when the web worker is used to store session information.
169
+ *
170
+ * @param {HttpRequestConfig[]} config - The config object containing attributes necessary to send a request.
171
+ *
172
+ * @return {Promise<HttpResponse[]>} - Returns a Promise that resolves with the responses to the requests.
173
+ */
174
+ public async httpRequestAll(configs: HttpRequestConfig[]): Promise<HttpResponse<any>[]> {
175
+ return this._client.httpRequestAll(configs);
176
+ }
177
+
178
+ /**
179
+ * This method allows you to send a request with a custom grant.
180
+ *
181
+ * @param {CustomGrantRequestParams} config - The request parameters.
182
+ *
183
+ * @return {Promise<HttpResponse<any> | SignInResponse>} - A Promise that resolves with
184
+ * the value returned by the custom grant request.
185
+ */
186
+ public requestCustomGrant(
187
+ config: CustomGrantConfig,
188
+ callback: (response: BasicUserInfo | HttpResponse<any>) => void,
189
+ dispatch: (state: AuthStateInterface) => void
190
+ ): void {
191
+ this._client.on(
192
+ Hooks.CustomGrant,
193
+ (response: BasicUserInfo | HttpResponse<any>) => {
194
+ if (config.returnsSession) {
195
+ dispatch({ ...(response as BasicUserInfo), isAuthenticated: true, isLoading: false });
196
+ }
197
+
198
+ callback && callback(response);
199
+ },
200
+ config.id
201
+ );
202
+ this._client.requestCustomGrant(config);
203
+ }
204
+
205
+ /**
206
+ * This method ends a user session. The access token is revoked and the session information is destroyed.
207
+ *
208
+ * @return {Promise<boolean>} - A promise that resolves with `true` if the process is successful.
209
+ */
210
+ public async revokeAccessToken(dispatch: (state: AuthStateInterface) => void): Promise<boolean> {
211
+ return this._client.revokeAccessToken().then(() => {
212
+ dispatch(AuthAPI.DEFAULT_STATE);
213
+ return true;
214
+ });
215
+ }
216
+
217
+ /**
218
+ * This method returns a Promise that resolves with an object containing the service endpoints.
219
+ *
220
+ * @return {Promise<ServiceResourcesType} - A Promise that resolves with an object containing the service endpoints.
221
+ */
222
+ public async getOIDCServiceEndpoints(): Promise<OIDCEndpoints> {
223
+ return this._client.getOIDCServiceEndpoints();
224
+ }
225
+
226
+ /**
227
+ * This methods returns the Axios http client.
228
+ *
229
+ * @return {HttpClientInstance} - The Axios HTTP client.
230
+ */
231
+ public async getHttpClient(): Promise<HttpClientInstance> {
232
+ return this._client.getHttpClient();
233
+ }
234
+
235
+ /**
236
+ * This method decodes the payload of the id token and returns it.
237
+ *
238
+ * @return {Promise<DecodedIDTokenPayloadInterface>} - A Promise that resolves with
239
+ * the decoded payload of the id token.
240
+ */
241
+ public async getDecodedIDToken(): Promise<DecodedIDTokenPayload> {
242
+ return this._client.getDecodedIDToken();
243
+ }
244
+
245
+ /**
246
+ * This method returns the ID token.
247
+ *
248
+ * @return {Promise<string>} - A Promise that resolves with the id token.
249
+ */
250
+ public async getIDToken(): Promise<string> {
251
+ return this._client.getIDToken();
252
+ }
253
+
254
+ /**
255
+ * This method return a Promise that resolves with the access token.
256
+ *
257
+ * **This method will not return the access token if the storage type is set to `webWorker`.**
258
+ *
259
+ * @return {Promise<string>} - A Promise that resolves with the access token.
260
+ */
261
+ public async getAccessToken(): Promise<string> {
262
+ return this._client.getAccessToken();
263
+ }
264
+
265
+ /**
266
+ * This method refreshes the access token.
267
+ *
268
+ * @return {TokenResponseInterface} - A Promise that resolves with an object containing
269
+ * information about the refreshed access token.
270
+ */
271
+ public async refreshAccessToken(): Promise<BasicUserInfo> {
272
+ return this._client.refreshAccessToken();
273
+ }
274
+
275
+ /**
276
+ * This method specifies if the user is authenticated or not.
277
+ *
278
+ * @return {Promise<boolean>} - A Promise that resolves with `true` if teh user is authenticated.
279
+ */
280
+ public async isAuthenticated(): Promise<boolean> {
281
+ return this._client.isAuthenticated();
282
+ }
283
+
284
+ /**
285
+ * This method enables callback functions attached to the http client.
286
+ *
287
+ * @return {Promise<boolean>} - A promise that resolves with True.
288
+ *
289
+ */
290
+ public async enableHttpHandler(): Promise<boolean> {
291
+ return this._client.enableHttpHandler();
292
+ }
293
+
294
+ /**
295
+ * This method disables callback functions attached to the http client.
296
+ *
297
+ * @return {Promise<boolean>} - A promise that resolves with True.
298
+ */
299
+ public async disableHttpHandler(): Promise<boolean> {
300
+ return this._client.disableHttpHandler();
301
+ }
302
+
303
+ /**
304
+ * This method updates the configuration that was passed into the constructor when instantiating this class.
305
+ *
306
+ * @param {Partial<AuthClientConfig<T>>} config - A config object to update the SDK configurations with.
307
+ */
308
+ public async updateConfig(config: Partial<AuthClientConfig<Config>>): Promise<void> {
309
+ return this._client.updateConfig(config);
310
+ }
311
+
312
+ /**
313
+ * This method attaches a callback function to an event hook that fires the callback when the event happens.
314
+ *
315
+ * @param {Hooks.CustomGrant} hook - The name of the hook.
316
+ * @param {(response?: any) => void} callback - The callback function.
317
+ * @param {string} id (optional) - The id of the hook. This is used when multiple custom grants are used.
318
+ *
319
+ */
320
+ public on(hook: Hooks.CustomGrant, callback: (response?: any) => void, id: string): Promise<void>;
321
+ public on(
322
+ hook:
323
+ | Hooks.RevokeAccessToken
324
+ | Hooks.HttpRequestError
325
+ | Hooks.HttpRequestFinish
326
+ | Hooks.HttpRequestStart
327
+ | Hooks.HttpRequestSuccess
328
+ | Hooks.Initialize
329
+ | Hooks.SignIn
330
+ | Hooks.SignOut,
331
+ callback: (response?: any) => void
332
+ ): Promise<void>;
333
+ public on(hook: Hooks, callback: (response?: any) => void, id?: string): Promise<void> {
334
+ if (hook === Hooks.CustomGrant) {
335
+ return this._client.on(hook, callback, id);
336
+ }
337
+
338
+ return this._client.on(hook, callback);
339
+ }
340
+
341
+ /**
342
+ * This method allows you to sign in silently.
343
+ * First, this method sends a prompt none request to see if there is an active user session in the identity server.
344
+ * If there is one, then it requests the access token and stores it. Else, it returns false.
345
+ *
346
+ * @return {Promise<BasicUserInfo | boolean>} - A Promise that resolves with the user information after signing in
347
+ * or with `false` if the user is not signed in.
348
+ *
349
+ * @example
350
+ *```
351
+ * client.trySignInSilently()
352
+ *```
353
+ */
354
+ public async trySignInSilently(
355
+ state: AuthStateInterface,
356
+ dispatch: (state: AuthStateInterface) => void
357
+ ): Promise<BasicUserInfo | boolean | undefined> {
358
+ return this._client.trySignInSilently().then((response: BasicUserInfo | boolean) => {
359
+ if (response) {
360
+ const basicUserInfo = response as BasicUserInfo;
361
+ const stateToUpdate = {
362
+ allowedScopes: basicUserInfo.allowedScopes,
363
+ displayName: basicUserInfo.displayName,
364
+ email: basicUserInfo.email,
365
+ isAuthenticated: true,
366
+ isLoading: false,
367
+ username: basicUserInfo.username
368
+ };
369
+
370
+ this.updateState(stateToUpdate);
371
+
372
+ dispatch({ ...state, ...stateToUpdate });
373
+
374
+ return response;
375
+ }
376
+
377
+ this.updateState({ ...state, isLoading: false });
378
+ dispatch({ ...state, isLoading: false });
379
+
380
+ return false;
381
+ });
382
+ }
383
+ }
384
+
385
+ AuthAPI.DEFAULT_STATE = {
386
+ allowedScopes: "",
387
+ displayName: "",
388
+ email: "",
389
+ isAuthenticated: false,
390
+ isLoading: true,
391
+ username: ""
392
+ };
393
+
394
+ export default AuthAPI;