forked from authorizerdev/authorizer-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
446 lines (393 loc) · 11.3 KB
/
Copy pathindex.ts
File metadata and controls
446 lines (393 loc) · 11.3 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
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
// Note: write gql query in single line to reduce bundle size
import nodeFetch from 'node-fetch';
import { DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS } from './constants';
import * as Types from './types';
import {
trimURL,
hasWindow,
encode,
createRandomString,
sha256,
bufferToBase64UrlEncoded,
createQueryParams,
executeIframe,
} from './utils';
// re-usable gql response fragment
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 `;
const authTokenFragment = `message access_token expires_in refresh_token id_token user { ${userFragment} }`;
const getFetcher = () => (hasWindow() ? window.fetch : nodeFetch);
export * from './types';
export class Authorizer {
// class variable
config: Types.ConfigType;
codeVerifier: string;
// constructor
constructor(config: Types.ConfigType) {
if (!config) {
throw new Error(`Configuration is required`);
}
this.config = config;
if (!config.authorizerURL && !config.authorizerURL.trim()) {
throw new Error(`Invalid authorizerURL`);
}
if (config.authorizerURL) {
this.config.authorizerURL = trimURL(config.authorizerURL);
}
if (!config.redirectURL && !config.redirectURL.trim()) {
throw new Error(`Invalid redirectURL`);
} else {
this.config.redirectURL = trimURL(config.redirectURL);
}
this.config.extraHeaders = {
...(config.extraHeaders || {}),
'x-authorizer-url': this.config.authorizerURL,
'Content-Type': 'application/json',
};
this.config.clientID = config.clientID.trim();
}
revokeToken = async (data: { refresh_token: string }) => {
if (!data.refresh_token && !data.refresh_token.trim()) {
throw new Error(`Invalid refresh_token`);
}
const fetcher = getFetcher();
const res = await fetcher(this.config.authorizerURL + '/oauth/revoke', {
method: 'POST',
headers: {
...this.config.extraHeaders,
},
body: JSON.stringify({
refresh_token: data.refresh_token,
client_id: this.config.clientID,
}),
});
return await res.json();
};
getToken = async (
data: Types.GetTokenInput,
): Promise<Types.GetTokenResponse> => {
if (!data.grant_type) {
data.grant_type = 'authorization_code';
}
if (data.grant_type === 'refresh_token' && !data.refresh_token) {
throw new Error(`Invalid refresh_token`);
}
if (data.grant_type === 'authorization_code' && !this.codeVerifier) {
throw new Error(`Invalid code verifier`);
}
const requestData = {
client_id: this.config.clientID,
code: data.code || '',
code_verifier: this.codeVerifier || '',
grant_type: data.grant_type || '',
refresh_token: data.refresh_token || '',
};
try {
const fetcher = getFetcher();
const res = await fetcher(`${this.config.authorizerURL}/oauth/token`, {
method: 'POST',
body: JSON.stringify(requestData),
headers: {
...this.config.extraHeaders,
},
credentials: 'include',
});
const json = await res.json();
if (res.status >= 400) {
throw new Error(json);
}
return json;
} catch (err) {
throw err;
}
};
authorize = async (data: Types.AuthorizeInput) => {
if (!hasWindow()) {
throw new Error(`this feature is only supported in browser`);
}
const scopes = ['openid', 'profile', 'email'];
if (data.use_refresh_token) {
scopes.push('offline_access');
}
const requestData: Record<string, string> = {
redirect_uri: this.config.redirectURL,
response_mode: data.response_mode || 'web_message',
state: encode(createRandomString()),
nonce: encode(createRandomString()),
response_type: data.response_type,
scope: scopes.join(' '),
client_id: this.config.clientID,
};
if (data.response_type === Types.ResponseTypes.Code) {
this.codeVerifier = createRandomString();
const sha = await sha256(this.codeVerifier);
const codeChallenge = bufferToBase64UrlEncoded(sha);
requestData.code_challenge = codeChallenge;
}
const authorizeURL = `${
this.config.authorizerURL
}/authorize?${createQueryParams(requestData)}`;
try {
const iframeRes = await executeIframe(
authorizeURL,
this.config.authorizerURL,
DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS,
);
if (data.response_type === Types.ResponseTypes.Code) {
// get token and return it
const token = await this.getToken({ code: iframeRes.code });
return token;
}
// this includes access_token, id_token & refresh_token(optionally)
return iframeRes;
} catch (err) {
if (err.error) {
window.location.replace(
`${this.config.authorizerURL}/app?state=${encode(
JSON.stringify(this.config),
)}&redirect_uri=${this.config.redirectURL}`,
);
}
throw err;
}
};
// helper to execute graphql queries
// takes in any query or mutation string as input
graphqlQuery = async (data: Types.GraphqlQueryInput) => {
// set fetch based on window object. Isomorphic fetch doesn't support credentail: true
// hence cookie based auth might not work so it is imp to use window.fetch in that case
const fetcher = getFetcher();
const res = await fetcher(this.config.authorizerURL + '/graphql', {
method: 'POST',
body: JSON.stringify({
query: data.query,
variables: data.variables || {},
}),
headers: {
...this.config.extraHeaders,
...(data.headers || {}),
},
credentials: 'include',
});
const json = await res.json();
if (json.errors && json.errors.length) {
console.error(json.errors);
throw new Error(json.errors[0].message);
}
return json.data;
};
getMetaData = async (): Promise<Types.MetaData | void> => {
try {
const res = await this.graphqlQuery({
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_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }`,
});
return res.meta;
} catch (err) {
throw err;
}
};
// this is used to verify / get session using cookie by default. If using nodejs pass authorization header
getSession = async (
headers?: Types.Headers,
params?: Types.SessionQueryInput,
): Promise<Types.AuthToken> => {
try {
const res = await this.graphqlQuery({
query: `query getSession($params: SessionQueryInput){session(params: $params) { ${authTokenFragment} } }`,
headers,
variables: {
params,
},
});
return res.session;
} catch (err) {
throw err;
}
};
magicLinkLogin = async (
data: Types.MagicLinkLoginInput,
): Promise<Types.Response> => {
try {
if (!data.state) {
data.state = encode(createRandomString());
}
if (!data.redirect_uri) {
data.redirect_uri = this.config.redirectURL;
}
const res = await this.graphqlQuery({
query: `
mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }}
`,
variables: { data },
});
return res.magic_link_login;
} catch (err) {
throw err;
}
};
signup = async (data: Types.SignupInput): Promise<Types.AuthToken | void> => {
try {
const res = await this.graphqlQuery({
query: `
mutation signup($data: SignUpInput!) { signup(params: $data) { ${authTokenFragment}}}
`,
variables: { data },
});
return res.signup;
} catch (err) {
throw err;
}
};
verifyEmail = async (
data: Types.VerifyEmailInput,
): Promise<Types.AuthToken | void> => {
try {
const res = await this.graphqlQuery({
query: `
mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${authTokenFragment}}}
`,
variables: { data },
});
return res.verify_email;
} catch (err) {
throw err;
}
};
login = async (data: Types.LoginInput): Promise<Types.AuthToken | void> => {
try {
const res = await this.graphqlQuery({
query: `
mutation login($data: LoginInput!) { login(params: $data) { ${authTokenFragment}}}
`,
variables: { data },
});
return res.login;
} catch (err) {
throw err;
}
};
getProfile = async (headers?: Types.Headers): Promise<Types.User | void> => {
try {
const profileRes = await this.graphqlQuery({
query: `query { profile { ${userFragment} } }`,
headers,
});
return profileRes.profile;
} catch (error) {
throw error;
}
};
updateProfile = async (
data: Types.UpdateProfileInput,
headers?: Types.Headers,
): Promise<Types.Response | void> => {
try {
const updateProfileRes = await this.graphqlQuery({
query: `mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }`,
headers,
variables: {
data,
},
});
return updateProfileRes.update_profile;
} catch (error) {
throw error;
}
};
forgotPassword = async (
data: Types.ForgotPasswordInput,
): Promise<Types.Response | void> => {
if (!data.state) {
data.state = encode(createRandomString());
}
if (!data.redirect_uri) {
data.redirect_uri = this.config.redirectURL;
}
try {
const forgotPasswordRes = await this.graphqlQuery({
query: `mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }`,
variables: {
data,
},
});
return forgotPasswordRes.forgot_password;
} catch (error) {
throw error;
}
};
resetPassword = async (
data: Types.ResetPasswordInput,
): Promise<Types.Response | void> => {
try {
const resetPasswordRes = await this.graphqlQuery({
query: `mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }`,
variables: {
data,
},
});
return resetPasswordRes.reset_password;
} catch (error) {
throw error;
}
};
browserLogin = async (): Promise<Types.AuthToken | void> => {
try {
const token = await this.getSession();
return token;
} catch (err) {
if (!hasWindow()) {
throw new Error(`browserLogin is only supported for browsers`);
}
window.location.replace(
`${this.config.authorizerURL}/app?state=${encode(
JSON.stringify(this.config),
)}&redirect_uri=${this.config.redirectURL}`,
);
}
};
oauthLogin = async (
oauthProvider: string,
roles?: string[],
): Promise<void> => {
if (!Object.keys(Types.OAuthProviders).includes(oauthProvider)) {
throw new Error(
`only following oauth providers are supported: ${Object.values(
oauthProvider,
).toString()}`,
);
}
if (!hasWindow()) {
throw new Error(`oauthLogin is only supported for browsers`);
}
window.location.replace(
`${this.config.authorizerURL}/oauth_login/${oauthProvider}?redirectURL=${
this.config.redirectURL
}${roles && roles.length ? `&roles=${roles.join(',')}` : ``}`,
);
};
logout = async (headers?: Types.Headers): Promise<Types.Response | void> => {
try {
const res = await this.graphqlQuery({
query: ` mutation { logout { message } } `,
headers,
});
return res.logout;
} catch (err) {
console.error(err);
}
};
validateJWTToken = async (
params?: Types.ValidateJWTTokenInput,
): Promise<Types.ValidateJWTTokenResponse> => {
try {
const res = await this.graphqlQuery({
query: `query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid } }`,
variables: {
params,
},
});
return res.validate_jwt_token;
} catch (error) {
throw error;
}
};
}