@authorizerdev/authorizer-js 0.1.0-beta.8 → 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.
@@ -1,77 +1,123 @@
1
- declare type ConfigType = {
1
+ export declare type ConfigType = {
2
2
  authorizerURL: string;
3
- redirectURL?: string;
3
+ redirectURL: string;
4
4
  };
5
- declare type User = {
5
+ export declare type User = {
6
6
  id: string;
7
7
  email: string;
8
- firstName?: string | null;
9
- lastName?: string | null;
10
- image?: string | null;
11
- signupMethod?: string | null;
12
- emailVerifiedAt?: number | null;
8
+ preferred_username: string;
9
+ email_verified: boolean;
10
+ signup_methods: string;
11
+ given_name?: string | null;
12
+ family_name?: string | null;
13
+ middle_name?: string | null;
14
+ picture?: string | null;
15
+ gender?: string | null;
16
+ birthdate?: string | null;
17
+ phone_number?: string | null;
18
+ phone_number_verified?: boolean | null;
19
+ roles?: string[];
20
+ created_at: number;
21
+ updated_at: number;
13
22
  };
14
- declare type AuthToken = {
23
+ export declare type AuthToken = {
15
24
  message?: string;
16
- accessToken: string;
17
- accessTokenExpiresAt: number;
25
+ access_token: string;
26
+ expires_at: number;
18
27
  user?: User;
19
28
  };
20
- declare type Response = {
29
+ export declare type Response = {
21
30
  message: string;
22
31
  };
23
- declare type Headers = Record<string, string>;
24
- declare type LoginInput = {
32
+ export declare type Headers = Record<string, string>;
33
+ export declare type LoginInput = {
25
34
  email: string;
26
35
  password: string;
36
+ roles?: string[];
27
37
  };
28
- declare type SignupInput = {
38
+ export declare type SignupInput = {
29
39
  email: string;
30
40
  password: string;
31
- confirmPassword: string;
32
- firstName?: string;
33
- lastName?: string;
41
+ confirm_password: string;
42
+ given_name?: string;
43
+ family_name?: string;
44
+ middle_name?: string;
45
+ picture?: string;
46
+ gender?: string;
47
+ birthdate?: string;
48
+ phone_number?: string;
49
+ roles?: string[];
34
50
  };
35
- declare type VerifyEmailInput = {
51
+ export declare type MagicLinkLoginInput = {
52
+ email: string;
53
+ roles?: string[];
54
+ };
55
+ export declare type VerifyEmailInput = {
36
56
  token: string;
37
57
  };
38
- declare type GraphqlQueryInput = {
58
+ export declare type GraphqlQueryInput = {
39
59
  query: string;
40
60
  variables?: Record<string, any>;
41
61
  headers?: Headers;
42
62
  };
43
- declare type MetaData = {
63
+ export declare type MetaData = {
44
64
  version: string;
45
- isGoogleLoginEnabled: boolean;
46
- isFacebookLoginEnabled: boolean;
47
- isTwitterLoginEnabled: boolean;
48
- isGithubLoginEnabled: boolean;
49
- isEmailVerificationEnabled: boolean;
50
- isBasicAuthenticationEnabled: boolean;
51
- };
52
- declare type UpdateProfileInput = {
53
- oldPassword?: string;
54
- newPassword?: string;
55
- confirmNewPassword?: string;
56
- firstName?: string;
57
- lastName?: string;
58
- image?: string;
65
+ is_google_login_enabled: boolean;
66
+ is_facebook_login_enabled: boolean;
67
+ is_github_login_enabled: boolean;
68
+ is_email_verification_enabled: boolean;
69
+ is_basic_authentication_enabled: boolean;
70
+ is_magic_link_login_enabled: boolean;
71
+ };
72
+ export declare type UpdateProfileInput = {
73
+ old_password?: string;
74
+ new_password?: string;
75
+ confirm_new_password?: string;
59
76
  email?: string;
77
+ given_name?: string;
78
+ family_name?: string;
79
+ middle_name?: string;
80
+ nickname?: string;
81
+ gender?: string;
82
+ birthdate?: string;
83
+ phone_number?: string;
84
+ picture?: string;
60
85
  };
61
- declare type ForgotPasswordInput = {
86
+ export declare type ForgotPasswordInput = {
62
87
  email: string;
63
88
  };
64
- declare type ResetPasswordInput = {
89
+ export declare type ResetPasswordInput = {
65
90
  token: string;
66
91
  password: string;
67
- confirmPassword: string;
92
+ confirm_password: string;
93
+ };
94
+ export declare type SessionQueryInput = {
95
+ roles?: string[];
68
96
  };
69
- export default class Authorizer {
97
+ export declare type IsValidJWTQueryInput = {
98
+ jwt: string;
99
+ roles?: string[];
100
+ };
101
+ export declare type ValidJWTResponse = {
102
+ valid: string;
103
+ message: string;
104
+ };
105
+ export declare enum OAuthProviders {
106
+ Github = "github",
107
+ Google = "google",
108
+ Facebook = "facebook"
109
+ }
110
+ export declare class Authorizer {
70
111
  config: ConfigType;
71
112
  constructor(config: ConfigType);
72
113
  graphqlQuery: (data: GraphqlQueryInput) => Promise<any>;
73
114
  getMetaData: () => Promise<MetaData | void>;
74
- getSession: (headers?: Headers | undefined) => Promise<AuthToken>;
115
+ getSession: (headers?: Headers | undefined, params?: SessionQueryInput | undefined) => Promise<AuthToken>;
116
+ isValidJWT: (data: {
117
+ jwt: string;
118
+ roles?: string[];
119
+ }) => Promise<ValidJWTResponse>;
120
+ magicLinkLogin: (data: MagicLinkLoginInput) => Promise<Response>;
75
121
  signup: (data: SignupInput) => Promise<AuthToken | void>;
76
122
  verifyEmail: (data: VerifyEmailInput) => Promise<AuthToken | void>;
77
123
  login: (data: LoginInput) => Promise<AuthToken | void>;
@@ -79,8 +125,7 @@ export default class Authorizer {
79
125
  updateProfile: (data: UpdateProfileInput, headers?: Headers | undefined) => Promise<Response | void>;
80
126
  forgotPassword: (data: ForgotPasswordInput) => Promise<Response | void>;
81
127
  resetPassword: (data: ResetPasswordInput) => Promise<Response | void>;
82
- fingertipLogin: () => Promise<AuthToken | void>;
83
- oauthLogin: (oauthProvider: string) => Promise<void>;
128
+ browserLogin: () => Promise<AuthToken | void>;
129
+ oauthLogin: (oauthProvider: string, roles?: string[] | undefined) => Promise<void>;
84
130
  logout: (headers?: Headers | undefined) => Promise<Response | void>;
85
131
  }
86
- export {};
package/lib/esm/index.js CHANGED
@@ -1,208 +1,273 @@
1
1
  import nodeFetch from 'node-fetch';
2
2
 
3
+ /*! *****************************************************************************
4
+ Copyright (c) Microsoft Corporation.
5
+
6
+ Permission to use, copy, modify, and/or distribute this software for any
7
+ purpose with or without fee is hereby granted.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
16
+ ***************************************************************************** */
17
+
18
+ function __awaiter(thisArg, _arguments, P, generator) {
19
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
20
+ return new (P || (P = Promise))(function (resolve, reject) {
21
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
22
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
23
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
24
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
25
+ });
26
+ }
27
+
3
28
  var OAuthProviders;
4
29
  (function (OAuthProviders) {
5
30
  OAuthProviders["Github"] = "github";
6
31
  OAuthProviders["Google"] = "google";
32
+ OAuthProviders["Facebook"] = "facebook";
7
33
  })(OAuthProviders || (OAuthProviders = {}));
8
34
  const hasWindow = () => typeof window !== 'undefined';
9
- const userTokenFragment = `message accessToken accessTokenExpiresAt user { id email firstName lastName image }`;
35
+ 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 `;
36
+ const authTokenFragment = `message access_token expires_at user { ${userFragment} }`;
37
+ const trimURL = (url) => {
38
+ let trimmedData = url.trim();
39
+ const lastChar = trimmedData[trimmedData.length - 1];
40
+ if (lastChar === '/') {
41
+ trimmedData = trimmedData.slice(0, -1);
42
+ }
43
+ else {
44
+ trimmedData = trimmedData;
45
+ }
46
+ return trimmedData;
47
+ };
10
48
  class Authorizer {
11
- config;
12
49
  constructor(config) {
50
+ this.graphqlQuery = (data) => __awaiter(this, void 0, void 0, function* () {
51
+ const f = hasWindow() ? window.fetch : nodeFetch;
52
+ const res = yield f(this.config.authorizerURL + '/graphql', {
53
+ method: 'POST',
54
+ body: JSON.stringify({
55
+ query: data.query,
56
+ variables: data.variables || {},
57
+ }),
58
+ headers: Object.assign({ 'Content-Type': 'application/json' }, (data.headers || {})),
59
+ credentials: 'include',
60
+ });
61
+ const json = yield res.json();
62
+ if (json.errors && json.errors.length) {
63
+ console.error(json.errors);
64
+ throw new Error(json.errors[0].message);
65
+ }
66
+ return json.data;
67
+ });
68
+ this.getMetaData = () => __awaiter(this, void 0, void 0, function* () {
69
+ try {
70
+ const res = yield this.graphqlQuery({
71
+ query: `query { meta { version is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled } }`,
72
+ });
73
+ return res.meta;
74
+ }
75
+ catch (err) {
76
+ throw err;
77
+ }
78
+ });
79
+ this.getSession = (headers, params) => __awaiter(this, void 0, void 0, function* () {
80
+ try {
81
+ const res = yield this.graphqlQuery({
82
+ query: `query getSession($params: SessionQueryInput){session(params: $params) { ${authTokenFragment} } }`,
83
+ headers,
84
+ variables: {
85
+ params,
86
+ },
87
+ });
88
+ return res.session;
89
+ }
90
+ catch (err) {
91
+ throw err;
92
+ }
93
+ });
94
+ this.isValidJWT = (data) => __awaiter(this, void 0, void 0, function* () {
95
+ try {
96
+ const res = yield this.graphqlQuery({
97
+ query: `query isValidJWT($params: IsValidJWTQueryInput){ is_valid_jwt(params: $params) { message valid } }`,
98
+ variables: {
99
+ params: data,
100
+ },
101
+ });
102
+ return res.is_valid_jwt;
103
+ }
104
+ catch (err) {
105
+ throw err;
106
+ }
107
+ });
108
+ this.magicLinkLogin = (data) => __awaiter(this, void 0, void 0, function* () {
109
+ try {
110
+ const res = yield this.graphqlQuery({
111
+ query: `
112
+ mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }}
113
+ `,
114
+ variables: { data },
115
+ });
116
+ return res.magic_link_login;
117
+ }
118
+ catch (err) {
119
+ throw err;
120
+ }
121
+ });
122
+ this.signup = (data) => __awaiter(this, void 0, void 0, function* () {
123
+ try {
124
+ const res = yield this.graphqlQuery({
125
+ query: `
126
+ mutation signup($data: SignUpInput!) { signup(params: $data) { ${authTokenFragment}}}
127
+ `,
128
+ variables: { data },
129
+ });
130
+ return res.signup;
131
+ }
132
+ catch (err) {
133
+ throw err;
134
+ }
135
+ });
136
+ this.verifyEmail = (data) => __awaiter(this, void 0, void 0, function* () {
137
+ try {
138
+ const res = yield this.graphqlQuery({
139
+ query: `
140
+ mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${authTokenFragment}}}
141
+ `,
142
+ variables: { data },
143
+ });
144
+ return res.verify_email;
145
+ }
146
+ catch (err) {
147
+ throw err;
148
+ }
149
+ });
150
+ this.login = (data) => __awaiter(this, void 0, void 0, function* () {
151
+ try {
152
+ const res = yield this.graphqlQuery({
153
+ query: `
154
+ mutation login($data: LoginInput!) { login(params: $data) { ${authTokenFragment}}}
155
+ `,
156
+ variables: { data },
157
+ });
158
+ return res.login;
159
+ }
160
+ catch (err) {
161
+ throw err;
162
+ }
163
+ });
164
+ this.getProfile = (headers) => __awaiter(this, void 0, void 0, function* () {
165
+ try {
166
+ const profileRes = yield this.graphqlQuery({
167
+ query: `query { profile { ${userFragment} } }`,
168
+ headers,
169
+ });
170
+ return profileRes.profile;
171
+ }
172
+ catch (error) {
173
+ throw error;
174
+ }
175
+ });
176
+ this.updateProfile = (data, headers) => __awaiter(this, void 0, void 0, function* () {
177
+ try {
178
+ const updateProfileRes = yield this.graphqlQuery({
179
+ query: `mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }`,
180
+ headers,
181
+ variables: {
182
+ data,
183
+ },
184
+ });
185
+ return updateProfileRes.update_profile;
186
+ }
187
+ catch (error) {
188
+ throw error;
189
+ }
190
+ });
191
+ this.forgotPassword = (data) => __awaiter(this, void 0, void 0, function* () {
192
+ try {
193
+ const forgotPasswordRes = yield this.graphqlQuery({
194
+ query: `mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }`,
195
+ variables: {
196
+ data,
197
+ },
198
+ });
199
+ return forgotPasswordRes.forgot_password;
200
+ }
201
+ catch (error) {
202
+ throw error;
203
+ }
204
+ });
205
+ this.resetPassword = (data) => __awaiter(this, void 0, void 0, function* () {
206
+ try {
207
+ const resetPasswordRes = yield this.graphqlQuery({
208
+ query: `mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }`,
209
+ variables: {
210
+ data,
211
+ },
212
+ });
213
+ return resetPasswordRes.reset_password;
214
+ }
215
+ catch (error) {
216
+ throw error;
217
+ }
218
+ });
219
+ this.browserLogin = () => __awaiter(this, void 0, void 0, function* () {
220
+ try {
221
+ const token = yield this.getSession();
222
+ return token;
223
+ }
224
+ catch (err) {
225
+ if (!hasWindow()) {
226
+ throw new Error(`browserLogin is only supported for browsers`);
227
+ }
228
+ window.location.replace(`${this.config.authorizerURL}/app?state=${btoa(JSON.stringify(this.config))}`);
229
+ }
230
+ });
231
+ this.oauthLogin = (oauthProvider, roles) => __awaiter(this, void 0, void 0, function* () {
232
+ if (!Object.values(OAuthProviders).includes(oauthProvider)) {
233
+ throw new Error(`only following oauth providers are supported: ${Object.values(oauthProvider).toString()}`);
234
+ }
235
+ if (!hasWindow()) {
236
+ throw new Error(`oauthLogin is only supported for browsers`);
237
+ }
238
+ window.location.replace(`${this.config.authorizerURL}/oauth_login/${oauthProvider}?redirectURL=${this.config.redirectURL || window.location.origin}${roles && roles.length ? `&roles=${roles.join(',')}` : ``}`);
239
+ });
240
+ this.logout = (headers) => __awaiter(this, void 0, void 0, function* () {
241
+ try {
242
+ const res = yield this.graphqlQuery({
243
+ query: ` mutation { logout { message } } `,
244
+ headers,
245
+ });
246
+ return res.logout;
247
+ }
248
+ catch (err) {
249
+ console.log(`logout err:`, err);
250
+ console.error(err);
251
+ }
252
+ });
13
253
  if (!config) {
14
254
  throw new Error(`Configuration is required`);
15
255
  }
16
256
  this.config = config;
17
- if (!config.authorizerURL.trim()) {
257
+ if (!config.authorizerURL && !config.authorizerURL.trim()) {
18
258
  throw new Error(`Invalid authorizerURL`);
19
259
  }
20
260
  if (config.authorizerURL) {
21
- const trimmedData = config.authorizerURL.trim();
22
- const lastChar = trimmedData[trimmedData.length - 1];
23
- if (lastChar === '/') {
24
- this.config.authorizerURL = trimmedData.slice(0, -1);
25
- }
26
- else {
27
- this.config.authorizerURL = trimmedData;
28
- }
261
+ this.config.authorizerURL = trimURL(config.authorizerURL);
29
262
  }
30
- if (!config.redirectURL) {
263
+ if (!config.redirectURL && !config.redirectURL.trim()) {
31
264
  throw new Error(`Invalid redirectURL`);
32
265
  }
33
- }
34
- graphqlQuery = async (data) => {
35
- const f = hasWindow() ? window.fetch : nodeFetch;
36
- const res = await f(this.config.authorizerURL + '/graphql', {
37
- method: 'POST',
38
- body: JSON.stringify({
39
- query: data.query,
40
- variables: data.variables || {},
41
- }),
42
- headers: {
43
- 'Content-Type': 'application/json',
44
- ...(data.headers || {}),
45
- },
46
- credentials: 'include',
47
- });
48
- const json = await res.json();
49
- if (json.errors && json.errors.length) {
50
- console.error(json.errors);
51
- throw new Error(json.errors[0].message);
52
- }
53
- return json.data;
54
- };
55
- getMetaData = async () => {
56
- try {
57
- const res = await this.graphqlQuery({
58
- query: `query { meta { version isGoogleLoginEnabled isGithubLoginEnabled isBasicAuthenticationEnabled isEmailVerificationEnabled isFacebookLoginEnabled isTwitterLoginEnabled } }`,
59
- });
60
- return res.meta;
61
- }
62
- catch (err) {
63
- throw err;
64
- }
65
- };
66
- getSession = async (headers) => {
67
- try {
68
- const res = await this.graphqlQuery({
69
- query: `query {token { ${userTokenFragment} } }`,
70
- headers,
71
- });
72
- return res.token;
73
- }
74
- catch (err) {
75
- throw err;
76
- }
77
- };
78
- signup = async (data) => {
79
- try {
80
- const res = await this.graphqlQuery({
81
- query: `
82
- mutation signup($data: SignUpInput!) { signup(params: $data) { ${userTokenFragment}}}`,
83
- variables: { data },
84
- });
85
- return res.signup;
86
- }
87
- catch (err) {
88
- console.error(err);
89
- }
90
- };
91
- verifyEmail = async (data) => {
92
- try {
93
- const res = await this.graphqlQuery({
94
- query: `
95
- mutation verifyEmail($data: VerifyEmailInput!) { verifyEmail(params: $data) { ${userTokenFragment}}}`,
96
- variables: { data },
97
- });
98
- return res.verifyEmail;
99
- }
100
- catch (err) {
101
- console.error(err);
102
- }
103
- };
104
- login = async (data) => {
105
- try {
106
- const res = await this.graphqlQuery({
107
- query: `
108
- mutation login($data: LoginInput!) { login(params: $data) { ${userTokenFragment}}}`,
109
- variables: { data },
110
- });
111
- return res.login;
112
- }
113
- catch (err) {
114
- console.error(err);
266
+ else {
267
+ this.config.redirectURL = trimURL(config.redirectURL);
115
268
  }
116
- };
117
- getProfile = async (headers) => {
118
- try {
119
- const profileRes = await this.graphqlQuery({
120
- query: `query { profile { id email image firstName lastName emailVerifiedAt signupMethod } }`,
121
- headers,
122
- });
123
- return profileRes.profile;
124
- }
125
- catch (error) {
126
- throw error;
127
- }
128
- };
129
- updateProfile = async (data, headers) => {
130
- try {
131
- const updateProfileRes = await this.graphqlQuery({
132
- query: `mutation updateProfile($data: UpdateProfileInput!) { updateProfile(params: $data) { message } }`,
133
- headers,
134
- variables: {
135
- data,
136
- },
137
- });
138
- return updateProfileRes.updateProfile;
139
- }
140
- catch (error) {
141
- throw error;
142
- }
143
- };
144
- forgotPassword = async (data) => {
145
- try {
146
- const forgotPasswordRes = await this.graphqlQuery({
147
- query: `mutation forgotPassword($data: ForgotPasswordInput!) { forgotPassword(params: $data) { message } }`,
148
- variables: {
149
- data,
150
- },
151
- });
152
- return forgotPasswordRes.forgotPassword;
153
- }
154
- catch (error) {
155
- throw error;
156
- }
157
- };
158
- resetPassword = async (data) => {
159
- try {
160
- const resetPasswordRes = await this.graphqlQuery({
161
- query: `mutation resetPassword($data: ResetPasswordInput!) { resetPassword(params: $data) { message } }`,
162
- variables: {
163
- data,
164
- },
165
- });
166
- return resetPasswordRes.resetPassword;
167
- }
168
- catch (error) {
169
- throw error;
170
- }
171
- };
172
- fingertipLogin = async () => {
173
- try {
174
- const token = await this.getSession();
175
- return token;
176
- }
177
- catch (err) {
178
- if (!hasWindow()) {
179
- throw new Error(`fingertipLogin is only supported for browsers`);
180
- }
181
- window.location.href = `${this.config.authorizerURL}/app?state=${btoa(JSON.stringify(this.config))}`;
182
- }
183
- };
184
- oauthLogin = async (oauthProvider) => {
185
- if (!Object.values(OAuthProviders).includes(oauthProvider)) {
186
- throw new Error(`only following oauth providers are supported: ${Object.values(oauthProvider).toString()}`);
187
- }
188
- if (!hasWindow()) {
189
- throw new Error(`oauthLogin is only supported for browsers`);
190
- }
191
- window.location.href = `${this.config.authorizerURL}/oauth_login/${oauthProvider}`;
192
- };
193
- logout = async (headers) => {
194
- try {
195
- const res = await this.graphqlQuery({
196
- query: ` mutation { logout { message } } `,
197
- headers,
198
- });
199
- return res.logout;
200
- }
201
- catch (err) {
202
- console.error(err);
203
- }
204
- };
269
+ }
205
270
  }
206
271
 
207
- export { Authorizer as default };
272
+ export { Authorizer, OAuthProviders };
208
273
  //# sourceMappingURL=index.js.map