@authorizerdev/authorizer-js 1.1.4 → 1.1.6

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/src/index.ts CHANGED
@@ -1,493 +1,499 @@
1
1
  // Note: write gql query in single line to reduce bundle size
2
- import crossFetch from 'cross-fetch';
3
- import { DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS } from './constants';
4
- import * as Types from './types';
2
+ import crossFetch from 'cross-fetch'
3
+ import { DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS } from './constants'
4
+ import * as Types from './types'
5
5
  import {
6
- trimURL,
7
- hasWindow,
8
- encode,
9
- createRandomString,
10
- sha256,
11
- bufferToBase64UrlEncoded,
12
- createQueryParams,
13
- executeIframe,
14
- } from './utils';
6
+ bufferToBase64UrlEncoded,
7
+ createQueryParams,
8
+ createRandomString,
9
+ encode,
10
+ executeIframe,
11
+ hasWindow,
12
+ sha256,
13
+ trimURL,
14
+ } from './utils'
15
15
 
16
16
  // re-usable gql response fragment
17
- const userFragment = `id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled `;
18
- const authTokenFragment = `message access_token expires_in refresh_token id_token should_show_otp_screen user { ${userFragment} }`;
17
+ const userFragment = 'id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled '
18
+ const authTokenFragment = `message access_token expires_in refresh_token id_token should_show_otp_screen user { ${userFragment} }`
19
19
 
20
20
  // set fetch based on window object. Cross fetch have issues with umd build
21
- const getFetcher = () => (hasWindow() ? window.fetch : crossFetch);
21
+ const getFetcher = () => (hasWindow() ? window.fetch : crossFetch)
22
22
 
23
- export * from './types';
23
+ export * from './types'
24
24
  export class Authorizer {
25
- // class variable
26
- config: Types.ConfigType;
27
- codeVerifier: string;
28
-
29
- // constructor
30
- constructor(config: Types.ConfigType) {
31
- if (!config) {
32
- throw new Error(`Configuration is required`);
33
- }
34
- this.config = config;
35
- if (!config.authorizerURL && !config.authorizerURL.trim()) {
36
- throw new Error(`Invalid authorizerURL`);
37
- }
38
- if (config.authorizerURL) {
39
- this.config.authorizerURL = trimURL(config.authorizerURL);
40
- }
41
- if (!config.redirectURL && !config.redirectURL.trim()) {
42
- throw new Error(`Invalid redirectURL`);
43
- } else {
44
- this.config.redirectURL = trimURL(config.redirectURL);
45
- }
46
-
47
- this.config.extraHeaders = {
48
- ...(config.extraHeaders || {}),
49
- 'x-authorizer-url': this.config.authorizerURL,
50
- 'Content-Type': 'application/json',
51
- };
52
- this.config.clientID = config.clientID.trim();
53
- }
54
-
55
- authorize = async (data: Types.AuthorizeInput) => {
56
- if (!hasWindow()) {
57
- throw new Error(`this feature is only supported in browser`);
58
- }
59
-
60
- const scopes = ['openid', 'profile', 'email'];
61
- if (data.use_refresh_token) {
62
- scopes.push('offline_access');
63
- }
64
-
65
- const requestData: Record<string, string> = {
66
- redirect_uri: this.config.redirectURL,
67
- response_mode: data.response_mode || 'web_message',
68
- state: encode(createRandomString()),
69
- nonce: encode(createRandomString()),
70
- response_type: data.response_type,
71
- scope: scopes.join(' '),
72
- client_id: this.config.clientID,
73
- };
74
-
75
- if (data.response_type === Types.ResponseTypes.Code) {
76
- this.codeVerifier = createRandomString();
77
- const sha = await sha256(this.codeVerifier);
78
- const codeChallenge = bufferToBase64UrlEncoded(sha);
79
- requestData.code_challenge = codeChallenge;
80
- }
81
-
82
- const authorizeURL = `${
25
+ // class variable
26
+ config: Types.ConfigType
27
+ codeVerifier: string
28
+
29
+ // constructor
30
+ constructor(config: Types.ConfigType) {
31
+ if (!config)
32
+ throw new Error('Configuration is required')
33
+
34
+ this.config = config
35
+ if (!config.authorizerURL && !config.authorizerURL.trim())
36
+ throw new Error('Invalid authorizerURL')
37
+
38
+ if (config.authorizerURL)
39
+ this.config.authorizerURL = trimURL(config.authorizerURL)
40
+
41
+ if (!config.redirectURL && !config.redirectURL.trim())
42
+ throw new Error('Invalid redirectURL')
43
+ else
44
+ this.config.redirectURL = trimURL(config.redirectURL)
45
+
46
+ this.config.extraHeaders = {
47
+ ...(config.extraHeaders || {}),
48
+ 'x-authorizer-url': this.config.authorizerURL,
49
+ 'Content-Type': 'application/json',
50
+ }
51
+ this.config.clientID = config.clientID.trim()
52
+ }
53
+
54
+ authorize = async (data: Types.AuthorizeInput) => {
55
+ if (!hasWindow())
56
+ throw new Error('this feature is only supported in browser')
57
+
58
+ const scopes = ['openid', 'profile', 'email']
59
+ if (data.use_refresh_token)
60
+ scopes.push('offline_access')
61
+
62
+ const requestData: Record<string, string> = {
63
+ redirect_uri: this.config.redirectURL,
64
+ response_mode: data.response_mode || 'web_message',
65
+ state: encode(createRandomString()),
66
+ nonce: encode(createRandomString()),
67
+ response_type: data.response_type,
68
+ scope: scopes.join(' '),
69
+ client_id: this.config.clientID,
70
+ }
71
+
72
+ if (data.response_type === Types.ResponseTypes.Code) {
73
+ this.codeVerifier = createRandomString()
74
+ const sha = await sha256(this.codeVerifier)
75
+ const codeChallenge = bufferToBase64UrlEncoded(sha)
76
+ requestData.code_challenge = codeChallenge
77
+ }
78
+
79
+ const authorizeURL = `${
83
80
  this.config.authorizerURL
84
- }/authorize?${createQueryParams(requestData)}`;
85
-
86
- if (requestData.response_mode !== 'web_message') {
87
- window.location.replace(authorizeURL);
88
- return;
89
- }
90
-
91
- try {
92
- const iframeRes = await executeIframe(
93
- authorizeURL,
94
- this.config.authorizerURL,
95
- DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS,
96
- );
97
-
98
- if (data.response_type === Types.ResponseTypes.Code) {
99
- // get token and return it
100
- const token = await this.getToken({ code: iframeRes.code });
101
- return token;
102
- }
103
-
104
- // this includes access_token, id_token & refresh_token(optionally)
105
- return iframeRes;
106
- } catch (err) {
107
- if (err.error) {
108
- window.location.replace(
81
+ }/authorize?${createQueryParams(requestData)}`
82
+
83
+ if (requestData.response_mode !== 'web_message') {
84
+ window.location.replace(authorizeURL)
85
+ return
86
+ }
87
+
88
+ try {
89
+ const iframeRes = await executeIframe(
90
+ authorizeURL,
91
+ this.config.authorizerURL,
92
+ DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS,
93
+ )
94
+
95
+ if (data.response_type === Types.ResponseTypes.Code) {
96
+ // get token and return it
97
+ const token = await this.getToken({ code: iframeRes.code })
98
+ return token
99
+ }
100
+
101
+ // this includes access_token, id_token & refresh_token(optionally)
102
+ return iframeRes
103
+ }
104
+ catch (err) {
105
+ if (err.error) {
106
+ window.location.replace(
109
107
  `${this.config.authorizerURL}/app?state=${encode(
110
108
  JSON.stringify(this.config),
111
109
  )}&redirect_uri=${this.config.redirectURL}`,
112
- );
113
- }
114
-
115
- throw err;
116
- }
117
- };
118
-
119
- browserLogin = async (): Promise<Types.AuthToken | void> => {
120
- try {
121
- const token = await this.getSession();
122
- return token;
123
- } catch (err) {
124
- if (!hasWindow()) {
125
- throw new Error(`browserLogin is only supported for browsers`);
126
- }
127
- window.location.replace(
110
+ )
111
+ }
112
+
113
+ throw err
114
+ }
115
+ }
116
+
117
+ browserLogin = async (): Promise<Types.AuthToken | void> => {
118
+ try {
119
+ const token = await this.getSession()
120
+ return token
121
+ }
122
+ catch (err) {
123
+ if (!hasWindow())
124
+ throw new Error('browserLogin is only supported for browsers')
125
+
126
+ window.location.replace(
128
127
  `${this.config.authorizerURL}/app?state=${encode(
129
128
  JSON.stringify(this.config),
130
129
  )}&redirect_uri=${this.config.redirectURL}`,
131
- );
132
- }
133
- };
134
-
135
- forgotPassword = async (
136
- data: Types.ForgotPasswordInput,
137
- ): Promise<Types.Response | void> => {
138
- if (!data.state) {
139
- data.state = encode(createRandomString());
140
- }
141
-
142
- if (!data.redirect_uri) {
143
- data.redirect_uri = this.config.redirectURL;
144
- }
145
-
146
- try {
147
- const forgotPasswordRes = await this.graphqlQuery({
148
- query: `mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }`,
149
- variables: {
150
- data,
151
- },
152
- });
153
-
154
- return forgotPasswordRes.forgot_password;
155
- } catch (error) {
156
- throw error;
157
- }
158
- };
159
-
160
- getMetaData = async (): Promise<Types.MetaData | void> => {
161
- try {
162
- const res = await this.graphqlQuery({
163
- query: `query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }`,
164
- });
165
-
166
- return res.meta;
167
- } catch (err) {
168
- throw err;
169
- }
170
- };
171
-
172
- getProfile = async (headers?: Types.Headers): Promise<Types.User | void> => {
173
- try {
174
- const profileRes = await this.graphqlQuery({
175
- query: `query { profile { ${userFragment} } }`,
176
- headers,
177
- });
178
-
179
- return profileRes.profile;
180
- } catch (error) {
181
- throw error;
182
- }
183
- };
184
-
185
- // this is used to verify / get session using cookie by default. If using nodejs pass authorization header
186
- getSession = async (
187
- headers?: Types.Headers,
188
- params?: Types.SessionQueryInput,
189
- ): Promise<Types.AuthToken> => {
190
- try {
191
- const res = await this.graphqlQuery({
192
- query: `query getSession($params: SessionQueryInput){session(params: $params) { ${authTokenFragment} } }`,
193
- headers,
194
- variables: {
195
- params,
196
- },
197
- });
198
- return res.session;
199
- } catch (err) {
200
- throw err;
201
- }
202
- };
203
-
204
- getToken = async (
205
- data: Types.GetTokenInput,
206
- ): Promise<Types.GetTokenResponse> => {
207
- if (!data.grant_type) {
208
- data.grant_type = 'authorization_code';
209
- }
210
-
211
- if (data.grant_type === 'refresh_token' && !data.refresh_token) {
212
- throw new Error(`Invalid refresh_token`);
213
- }
214
- if (data.grant_type === 'authorization_code' && !this.codeVerifier) {
215
- throw new Error(`Invalid code verifier`);
216
- }
217
-
218
- const requestData = {
219
- client_id: this.config.clientID,
220
- code: data.code || '',
221
- code_verifier: this.codeVerifier || '',
222
- grant_type: data.grant_type || '',
223
- refresh_token: data.refresh_token || '',
224
- };
225
-
226
- try {
227
- const fetcher = getFetcher();
228
- const res = await fetcher(`${this.config.authorizerURL}/oauth/token`, {
229
- method: 'POST',
230
- body: JSON.stringify(requestData),
231
- headers: {
232
- ...this.config.extraHeaders,
233
- },
234
- credentials: 'include',
235
- });
236
-
237
- const json = await res.json();
238
- if (res.status >= 400) {
239
- throw new Error(json);
240
- }
241
- return json;
242
- } catch (err) {
243
- throw err;
244
- }
245
- };
246
-
247
- // helper to execute graphql queries
248
- // takes in any query or mutation string as input
249
- graphqlQuery = async (data: Types.GraphqlQueryInput) => {
250
- const fetcher = getFetcher();
251
- const res = await fetcher(this.config.authorizerURL + '/graphql', {
252
- method: 'POST',
253
- body: JSON.stringify({
254
- query: data.query,
255
- variables: data.variables || {},
256
- }),
257
- headers: {
258
- ...this.config.extraHeaders,
259
- ...(data.headers || {}),
260
- },
261
- credentials: 'include',
262
- });
263
-
264
- const json = await res.json();
265
-
266
- if (json.errors && json.errors.length) {
267
- console.error(json.errors);
268
- throw new Error(json.errors[0].message);
269
- }
270
-
271
- return json.data;
272
- };
273
-
274
- login = async (data: Types.LoginInput): Promise<Types.AuthToken | void> => {
275
- try {
276
- const res = await this.graphqlQuery({
277
- query: `
130
+ )
131
+ }
132
+ }
133
+
134
+ forgotPassword = async (
135
+ data: Types.ForgotPasswordInput,
136
+ ): Promise<Types.Response | void> => {
137
+ if (!data.state)
138
+ data.state = encode(createRandomString())
139
+
140
+ if (!data.redirect_uri)
141
+ data.redirect_uri = this.config.redirectURL
142
+
143
+ try {
144
+ const forgotPasswordRes = await this.graphqlQuery({
145
+ query: 'mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }',
146
+ variables: {
147
+ data,
148
+ },
149
+ })
150
+ return forgotPasswordRes.forgot_password
151
+ }
152
+ catch (error) {
153
+ throw new Error(error)
154
+ }
155
+ }
156
+
157
+ getMetaData = async (): Promise<Types.MetaData | void> => {
158
+ try {
159
+ const res = await this.graphqlQuery({
160
+ query: 'query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }',
161
+ })
162
+
163
+ return res.meta
164
+ }
165
+ catch (err) {
166
+ throw new Error(err)
167
+ }
168
+ }
169
+
170
+ getProfile = async (headers?: Types.Headers): Promise<Types.User | void> => {
171
+ try {
172
+ const profileRes = await this.graphqlQuery({
173
+ query: `query { profile { ${userFragment} } }`,
174
+ headers,
175
+ })
176
+
177
+ return profileRes.profile
178
+ }
179
+ catch (error) {
180
+ throw new Error(error)
181
+ }
182
+ }
183
+
184
+ // this is used to verify / get session using cookie by default. If using nodejs pass authorization header
185
+ getSession = async (
186
+ headers?: Types.Headers,
187
+ params?: Types.SessionQueryInput,
188
+ ): Promise<Types.AuthToken> => {
189
+ try {
190
+ const res = await this.graphqlQuery({
191
+ query: `query getSession($params: SessionQueryInput){session(params: $params) { ${authTokenFragment} } }`,
192
+ headers,
193
+ variables: {
194
+ params,
195
+ },
196
+ })
197
+ return res.session
198
+ }
199
+ catch (err) {
200
+ throw new Error(err)
201
+ }
202
+ }
203
+
204
+ getToken = async (
205
+ data: Types.GetTokenInput,
206
+ ): Promise<Types.GetTokenResponse> => {
207
+ if (!data.grant_type)
208
+ data.grant_type = 'authorization_code'
209
+
210
+ if (data.grant_type === 'refresh_token' && !data.refresh_token)
211
+ throw new Error('Invalid refresh_token')
212
+
213
+ if (data.grant_type === 'authorization_code' && !this.codeVerifier)
214
+ throw new Error('Invalid code verifier')
215
+
216
+ const requestData = {
217
+ client_id: this.config.clientID,
218
+ code: data.code || '',
219
+ code_verifier: this.codeVerifier || '',
220
+ grant_type: data.grant_type || '',
221
+ refresh_token: data.refresh_token || '',
222
+ }
223
+
224
+ try {
225
+ const fetcher = getFetcher()
226
+ const res = await fetcher(`${this.config.authorizerURL}/oauth/token`, {
227
+ method: 'POST',
228
+ body: JSON.stringify(requestData),
229
+ headers: {
230
+ ...this.config.extraHeaders,
231
+ },
232
+ credentials: 'include',
233
+ })
234
+
235
+ const json = await res.json()
236
+ if (res.status >= 400)
237
+ throw new Error(json)
238
+
239
+ return json
240
+ }
241
+ catch (err) {
242
+ throw new Error(err)
243
+ }
244
+ }
245
+
246
+ // helper to execute graphql queries
247
+ // takes in any query or mutation string as input
248
+ graphqlQuery = async (data: Types.GraphqlQueryInput) => {
249
+ const fetcher = getFetcher()
250
+ const res = await fetcher(`${this.config.authorizerURL}/graphql`, {
251
+ method: 'POST',
252
+ body: JSON.stringify({
253
+ query: data.query,
254
+ variables: data.variables || {},
255
+ }),
256
+ headers: {
257
+ ...this.config.extraHeaders,
258
+ ...(data.headers || {}),
259
+ },
260
+ credentials: 'include',
261
+ })
262
+
263
+ const json = await res.json()
264
+
265
+ if (json.errors && json.errors.length) {
266
+ console.error(json.errors)
267
+ throw new Error(json.errors[0].message)
268
+ }
269
+
270
+ return json.data
271
+ }
272
+
273
+ login = async (data: Types.LoginInput): Promise<Types.AuthToken | void> => {
274
+ try {
275
+ const res = await this.graphqlQuery({
276
+ query: `
278
277
  mutation login($data: LoginInput!) { login(params: $data) { ${authTokenFragment}}}
279
278
  `,
280
- variables: { data },
281
- });
282
-
283
- return res.login;
284
- } catch (err) {
285
- throw err;
286
- }
287
- };
288
-
289
- logout = async (headers?: Types.Headers): Promise<Types.Response | void> => {
290
- try {
291
- const res = await this.graphqlQuery({
292
- query: ` mutation { logout { message } } `,
293
- headers,
294
- });
295
- return res.logout;
296
- } catch (err) {
297
- console.error(err);
298
- }
299
- };
300
-
301
- magicLinkLogin = async (
302
- data: Types.MagicLinkLoginInput,
303
- ): Promise<Types.Response> => {
304
- try {
305
- if (!data.state) {
306
- data.state = encode(createRandomString());
307
- }
308
-
309
- if (!data.redirect_uri) {
310
- data.redirect_uri = this.config.redirectURL;
311
- }
312
-
313
- const res = await this.graphqlQuery({
314
- query: `
279
+ variables: { data },
280
+ })
281
+
282
+ return res.login
283
+ }
284
+ catch (err) {
285
+ throw new Error(err)
286
+ }
287
+ }
288
+
289
+ logout = async (headers?: Types.Headers): Promise<Types.Response | void> => {
290
+ try {
291
+ const res = await this.graphqlQuery({
292
+ query: ' mutation { logout { message } } ',
293
+ headers,
294
+ })
295
+ return res.logout
296
+ }
297
+ catch (err) {
298
+ console.error(err)
299
+ }
300
+ }
301
+
302
+ magicLinkLogin = async (
303
+ data: Types.MagicLinkLoginInput,
304
+ ): Promise<Types.Response> => {
305
+ try {
306
+ if (!data.state)
307
+ data.state = encode(createRandomString())
308
+
309
+ if (!data.redirect_uri)
310
+ data.redirect_uri = this.config.redirectURL
311
+
312
+ const res = await this.graphqlQuery({
313
+ query: `
315
314
  mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }}
316
315
  `,
317
- variables: { data },
318
- });
319
-
320
- return res.magic_link_login;
321
- } catch (err) {
322
- throw err;
323
- }
324
- };
325
-
326
- oauthLogin = async (
327
- oauthProvider: string,
328
- roles?: string[],
329
- redirect_uri?: string,
330
- state?: string,
331
- ): Promise<void> => {
332
- let urlState = state;
333
- if (!urlState) {
334
- urlState = encode(createRandomString());
335
- }
336
- // @ts-ignore
337
- if (!Object.values(Types.OAuthProviders).includes(oauthProvider)) {
338
- throw new Error(
316
+ variables: { data },
317
+ })
318
+
319
+ return res.magic_link_login
320
+ }
321
+ catch (err) {
322
+ throw new Error(err)
323
+ }
324
+ }
325
+
326
+ oauthLogin = async (
327
+ oauthProvider: string,
328
+ roles?: string[],
329
+ redirect_uri?: string,
330
+ state?: string,
331
+ ): Promise<void> => {
332
+ let urlState = state
333
+ if (!urlState)
334
+ urlState = encode(createRandomString())
335
+
336
+ // @ts-expect-error
337
+ if (!Object.values(Types.OAuthProviders).includes(oauthProvider)) {
338
+ throw new Error(
339
339
  `only following oauth providers are supported: ${Object.values(
340
340
  oauthProvider,
341
341
  ).toString()}`,
342
- );
343
- }
344
- if (!hasWindow()) {
345
- throw new Error(`oauthLogin is only supported for browsers`);
346
- }
347
- window.location.replace(
342
+ )
343
+ }
344
+ if (!hasWindow())
345
+ throw new Error('oauthLogin is only supported for browsers')
346
+
347
+ window.location.replace(
348
348
  `${this.config.authorizerURL}/oauth_login/${oauthProvider}?redirect_uri=${
349
349
  redirect_uri || this.config.redirectURL
350
350
  }&state=${urlState}${
351
- roles && roles.length ? `&roles=${roles.join(',')}` : ``
351
+ (roles && roles.length) ? `&roles=${roles.join(',')}` : ''
352
352
  }`,
353
- );
354
- };
355
-
356
- resendOtp = async (
357
- data: Types.ResendOtpInput,
358
- ): Promise<Types.Response | void> => {
359
- try {
360
- const res = await this.graphqlQuery({
361
- query: `
353
+ )
354
+ }
355
+
356
+ resendOtp = async (
357
+ data: Types.ResendOtpInput,
358
+ ): Promise<Types.Response | void> => {
359
+ try {
360
+ const res = await this.graphqlQuery({
361
+ query: `
362
362
  mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }}
363
363
  `,
364
- variables: { data },
365
- });
366
-
367
- return res.resend_otp;
368
- } catch (err) {
369
- throw err;
370
- }
371
- };
372
-
373
- resetPassword = async (
374
- data: Types.ResetPasswordInput,
375
- ): Promise<Types.Response | void> => {
376
- try {
377
- const resetPasswordRes = await this.graphqlQuery({
378
- query: `mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }`,
379
- variables: {
380
- data,
381
- },
382
- });
383
- return resetPasswordRes.reset_password;
384
- } catch (error) {
385
- throw error;
386
- }
387
- };
388
-
389
- revokeToken = async (data: { refresh_token: string }) => {
390
- if (!data.refresh_token && !data.refresh_token.trim()) {
391
- throw new Error(`Invalid refresh_token`);
392
- }
393
-
394
- const fetcher = getFetcher();
395
- const res = await fetcher(this.config.authorizerURL + '/oauth/revoke', {
396
- method: 'POST',
397
- headers: {
398
- ...this.config.extraHeaders,
399
- },
400
- body: JSON.stringify({
401
- refresh_token: data.refresh_token,
402
- client_id: this.config.clientID,
403
- }),
404
- });
405
-
406
- return await res.json();
407
- };
408
-
409
- signup = async (data: Types.SignupInput): Promise<Types.AuthToken | void> => {
410
- try {
411
- const res = await this.graphqlQuery({
412
- query: `
364
+ variables: { data },
365
+ })
366
+
367
+ return res.resend_otp
368
+ }
369
+ catch (err) {
370
+ throw new Error(err)
371
+ }
372
+ }
373
+
374
+ resetPassword = async (
375
+ data: Types.ResetPasswordInput,
376
+ ): Promise<Types.Response | void> => {
377
+ try {
378
+ const resetPasswordRes = await this.graphqlQuery({
379
+ query: 'mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }',
380
+ variables: {
381
+ data,
382
+ },
383
+ })
384
+ return resetPasswordRes.reset_password
385
+ }
386
+ catch (error) {
387
+ throw new Error(error)
388
+ }
389
+ }
390
+
391
+ revokeToken = async (data: { refresh_token: string }) => {
392
+ if (!data.refresh_token && !data.refresh_token.trim())
393
+ throw new Error('Invalid refresh_token')
394
+
395
+ const fetcher = getFetcher()
396
+ const res = await fetcher(`${this.config.authorizerURL}/oauth/revoke`, {
397
+ method: 'POST',
398
+ headers: {
399
+ ...this.config.extraHeaders,
400
+ },
401
+ body: JSON.stringify({
402
+ refresh_token: data.refresh_token,
403
+ client_id: this.config.clientID,
404
+ }),
405
+ })
406
+
407
+ return await res.json()
408
+ }
409
+
410
+ signup = async (data: Types.SignupInput): Promise<Types.AuthToken | void> => {
411
+ try {
412
+ const res = await this.graphqlQuery({
413
+ query: `
413
414
  mutation signup($data: SignUpInput!) { signup(params: $data) { ${authTokenFragment}}}
414
415
  `,
415
- variables: { data },
416
- });
417
-
418
- return res.signup;
419
- } catch (err) {
420
- throw err;
421
- }
422
- };
423
-
424
- updateProfile = async (
425
- data: Types.UpdateProfileInput,
426
- headers?: Types.Headers,
427
- ): Promise<Types.Response | void> => {
428
- try {
429
- const updateProfileRes = await this.graphqlQuery({
430
- query: `mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }`,
431
- headers,
432
- variables: {
433
- data,
434
- },
435
- });
436
-
437
- return updateProfileRes.update_profile;
438
- } catch (error) {
439
- throw error;
440
- }
441
- };
442
-
443
- validateJWTToken = async (
444
- params?: Types.ValidateJWTTokenInput,
445
- ): Promise<Types.ValidateJWTTokenResponse> => {
446
- try {
447
- const res = await this.graphqlQuery({
448
- query: `query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }`,
449
- variables: {
450
- params,
451
- },
452
- });
453
-
454
- return res.validate_jwt_token;
455
- } catch (error) {
456
- throw error;
457
- }
458
- };
459
-
460
- verifyEmail = async (
461
- data: Types.VerifyEmailInput,
462
- ): Promise<Types.AuthToken | void> => {
463
- try {
464
- const res = await this.graphqlQuery({
465
- query: `
416
+ variables: { data },
417
+ })
418
+
419
+ return res.signup
420
+ }
421
+ catch (err) {
422
+ throw new Error(err)
423
+ }
424
+ }
425
+
426
+ updateProfile = async (
427
+ data: Types.UpdateProfileInput,
428
+ headers?: Types.Headers,
429
+ ): Promise<Types.Response | void> => {
430
+ try {
431
+ const updateProfileRes = await this.graphqlQuery({
432
+ query: 'mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }',
433
+ headers,
434
+ variables: {
435
+ data,
436
+ },
437
+ })
438
+
439
+ return updateProfileRes.update_profile
440
+ }
441
+ catch (error) {
442
+ throw new Error(error)
443
+ }
444
+ }
445
+
446
+ validateJWTToken = async (
447
+ params?: Types.ValidateJWTTokenInput,
448
+ ): Promise<Types.ValidateJWTTokenResponse> => {
449
+ try {
450
+ const res = await this.graphqlQuery({
451
+ query: 'query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }',
452
+ variables: {
453
+ params,
454
+ },
455
+ })
456
+
457
+ return res.validate_jwt_token
458
+ }
459
+ catch (error) {
460
+ throw new Error(error)
461
+ }
462
+ }
463
+
464
+ verifyEmail = async (
465
+ data: Types.VerifyEmailInput,
466
+ ): Promise<Types.AuthToken | void> => {
467
+ try {
468
+ const res = await this.graphqlQuery({
469
+ query: `
466
470
  mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${authTokenFragment}}}
467
471
  `,
468
- variables: { data },
469
- });
470
-
471
- return res.verify_email;
472
- } catch (err) {
473
- throw err;
474
- }
475
- };
476
-
477
- verifyOtp = async (
478
- data: Types.VerifyOtpInput,
479
- ): Promise<Types.AuthToken | void> => {
480
- try {
481
- const res = await this.graphqlQuery({
482
- query: `
472
+ variables: { data },
473
+ })
474
+
475
+ return res.verify_email
476
+ }
477
+ catch (err) {
478
+ throw new Error(err)
479
+ }
480
+ }
481
+
482
+ verifyOtp = async (
483
+ data: Types.VerifyOtpInput,
484
+ ): Promise<Types.AuthToken | void> => {
485
+ try {
486
+ const res = await this.graphqlQuery({
487
+ query: `
483
488
  mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${authTokenFragment}}}
484
489
  `,
485
- variables: { data },
486
- });
487
-
488
- return res.verify_otp;
489
- } catch (err) {
490
- throw err;
491
- }
492
- };
490
+ variables: { data },
491
+ })
492
+
493
+ return res.verify_otp
494
+ }
495
+ catch (err) {
496
+ throw new Error(err)
497
+ }
498
+ }
493
499
  }