@cloudbase/auth 1.7.3-alpha.0 → 1.8.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.
Files changed (48) hide show
  1. package/.eslintrc.js +13 -0
  2. package/dist/cjs/constants.d.ts +0 -1
  3. package/dist/cjs/constants.js +2 -3
  4. package/dist/cjs/index.d.ts +9 -13
  5. package/dist/cjs/index.js +120 -198
  6. package/dist/cjs/providers/anonymousAuthProvider.js +25 -23
  7. package/dist/cjs/providers/base.d.ts +1 -2
  8. package/dist/cjs/providers/base.js +12 -6
  9. package/dist/cjs/providers/customAuthProvider.js +15 -14
  10. package/dist/cjs/providers/emailAuthProvider.js +27 -29
  11. package/dist/cjs/providers/phoneAuthProvider.js +22 -24
  12. package/dist/cjs/providers/usernameAuthProvider.js +17 -17
  13. package/dist/cjs/providers/weixinAuthProvider.js +31 -30
  14. package/dist/esm/constants.d.ts +0 -1
  15. package/dist/esm/constants.js +1 -2
  16. package/dist/esm/index.d.ts +9 -13
  17. package/dist/esm/index.js +121 -199
  18. package/dist/esm/providers/anonymousAuthProvider.js +25 -23
  19. package/dist/esm/providers/base.d.ts +1 -2
  20. package/dist/esm/providers/base.js +12 -6
  21. package/dist/esm/providers/customAuthProvider.js +15 -14
  22. package/dist/esm/providers/emailAuthProvider.js +27 -29
  23. package/dist/esm/providers/phoneAuthProvider.js +22 -24
  24. package/dist/esm/providers/usernameAuthProvider.js +17 -17
  25. package/dist/esm/providers/weixinAuthProvider.js +31 -30
  26. package/package.json +8 -12
  27. package/src/constants.ts +0 -2
  28. package/src/index.ts +128 -245
  29. package/src/providers/anonymousAuthProvider.ts +15 -18
  30. package/src/providers/base.ts +7 -20
  31. package/src/providers/customAuthProvider.ts +12 -15
  32. package/src/providers/emailAuthProvider.ts +21 -24
  33. package/src/providers/phoneAuthProvider.ts +22 -23
  34. package/src/providers/usernameAuthProvider.ts +10 -11
  35. package/src/providers/weixinAuthProvider.ts +45 -46
  36. package/tsconfig.esm.json +2 -19
  37. package/tsconfig.json +2 -19
  38. package/.eslintrc +0 -30
  39. package/dist/cjs/common.d.ts +0 -8
  40. package/dist/cjs/common.js +0 -64
  41. package/dist/cjs/providers/oauth2AuthProvider.d.ts +0 -61
  42. package/dist/cjs/providers/oauth2AuthProvider.js +0 -404
  43. package/dist/esm/common.d.ts +0 -8
  44. package/dist/esm/common.js +0 -61
  45. package/dist/esm/providers/oauth2AuthProvider.d.ts +0 -61
  46. package/dist/esm/providers/oauth2AuthProvider.js +0 -401
  47. package/src/common.ts +0 -21
  48. package/src/providers/oauth2AuthProvider.ts +0 -585
package/src/index.ts CHANGED
@@ -1,23 +1,18 @@
1
+ /* eslint-disable new-cap */
1
2
  import { ICloudbase } from '@cloudbase/types';
2
3
  import { events, adapters, utils, constants, helpers } from '@cloudbase/utilities';
3
4
  import { ICloudbaseCache } from '@cloudbase/types/cache';
4
5
  import { ICloudbaseRequest } from '@cloudbase/types/request';
5
6
  import { ICloudbaseAuthConfig, ICredential, IUser, IUserInfo, IAuthProvider, ILoginState } from '@cloudbase/types/auth';
6
7
  import { ICloudbaseComponent } from '@cloudbase/types/component';
7
- import { checkFromAuthV2 } from './common'
8
-
9
- import { LOGINTYPE, OAUTH2_LOGINTYPE_PREFIX } from './constants';
10
-
11
- import { AuthProvider } from './providers/base';
12
-
13
- import { OAuth2AuthProvider, IOAuth2AuthProviderOptions } from './providers/oauth2AuthProvider';
14
-
8
+ import { WeixinAuthProvider } from './providers/weixinAuthProvider';
15
9
  import { AnonymousAuthProvider } from './providers/anonymousAuthProvider';
16
10
  import { CustomAuthProvider } from './providers/customAuthProvider';
11
+ import { LOGINTYPE } from './constants';
12
+ import { AuthProvider } from './providers/base';
17
13
  import { EmailAuthProvider } from './providers/emailAuthProvider';
18
- import { PhoneAuthProvider, SIGN_METHOD } from './providers/phoneAuthProvider'
19
14
  import { UsernameAuthProvider } from './providers/usernameAuthProvider';
20
- import { WeixinAuthProvider } from './providers/weixinAuthProvider';
15
+ import { PhoneAuthProvider, SIGN_METHOD } from './providers/phoneAuthProvider';
21
16
 
22
17
  declare const cloudbase: ICloudbase;
23
18
 
@@ -97,12 +92,12 @@ class User implements IUser {
97
92
  this.avatarUrl = this._getLocalUserInfo('avatarUrl');
98
93
  this.email = this._getLocalUserInfo('email');
99
94
  this.hasPassword = Boolean(this._getLocalUserInfo('hasPassword'));
100
- this.phone = this._getLocalUserInfo('phone')
101
- this.username = this._getLocalUserInfo('username')
95
+ this.phone = this._getLocalUserInfo('phone');
96
+ this.username = this._getLocalUserInfo('username');
102
97
  this.location = {
103
98
  country: this._getLocalUserInfo('country'),
104
99
  province: this._getLocalUserInfo('province'),
105
- city: this._getLocalUserInfo('city')
100
+ city: this._getLocalUserInfo('city'),
106
101
  };
107
102
  }
108
103
  /**
@@ -122,12 +117,12 @@ class User implements IUser {
122
117
  this.avatarUrl = await this._getLocalUserInfoAsync('avatarUrl');
123
118
  this.email = await this._getLocalUserInfoAsync('email');
124
119
  this.hasPassword = Boolean(await this._getLocalUserInfoAsync('hasPassword'));
125
- this.phone = await this._getLocalUserInfoAsync('phone')
126
- this.username = await this._getLocalUserInfoAsync('username')
120
+ this.phone = await this._getLocalUserInfoAsync('phone');
121
+ this.username = await this._getLocalUserInfoAsync('username');
127
122
  this.location = {
128
123
  country: await this._getLocalUserInfoAsync('country'),
129
124
  province: await this._getLocalUserInfoAsync('province'),
130
- city: await this._getLocalUserInfoAsync('city')
125
+ city: await this._getLocalUserInfoAsync('city'),
131
126
  };
132
127
  }
133
128
 
@@ -143,8 +138,8 @@ class User implements IUser {
143
138
  ' 2 - 此账户是否已经绑定自定义登录',
144
139
  ' 3 - ticket 参数是否归属当前环境',
145
140
  ' 4 - 创建 ticket 的自定义登录私钥是否过期',
146
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
147
- ]
141
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
142
+ ],
148
143
  })
149
144
  public linkWithTicket(ticket: string): Promise<void> {
150
145
  if (typeof ticket !== 'string') {
@@ -163,8 +158,8 @@ class User implements IUser {
163
158
  ' 1 - 调用 User.linkWithRedirect() 的语法或参数是否正确',
164
159
  ' 2 - 此账户是否已经绑定此第三方',
165
160
  ' 3 - 此第三方是否已经授权',
166
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
167
- ]
161
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
162
+ ],
168
163
  })
169
164
  public linkWithRedirect(provider: IAuthProvider): void {
170
165
  provider.signInWithRedirect();
@@ -177,8 +172,8 @@ class User implements IUser {
177
172
  messages: [
178
173
  '请确认以下各项:',
179
174
  ' 1 - 调用 User.getLinkedUidList() 的语法或参数是否正确',
180
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
181
- ]
175
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
176
+ ],
182
177
  })
183
178
  public async getLinkedUidList() {
184
179
  const { data } = await this._request.send('auth.getLinkedUidList', {});
@@ -192,7 +187,7 @@ class User implements IUser {
192
187
  }
193
188
  return {
194
189
  users,
195
- hasPrimaryUid
190
+ hasPrimaryUid,
196
191
  };
197
192
  }
198
193
  /**
@@ -205,8 +200,8 @@ class User implements IUser {
205
200
  messages: [
206
201
  '请确认以下各项:',
207
202
  ' 1 - 调用 User.setPrimaryUid() 的语法或参数是否正确',
208
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
209
- ]
203
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
204
+ ],
210
205
  })
211
206
  public setPrimaryUid(uid: string) {
212
207
  return this._request.send('auth.setPrimaryUid', { uid });
@@ -221,8 +216,8 @@ class User implements IUser {
221
216
  '请确认以下各项:',
222
217
  ' 1 - 调用 User.unlink() 的语法或参数是否正确',
223
218
  ' 2 - 当前账户是否已经与此登录方式解绑',
224
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
225
- ]
219
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
220
+ ],
226
221
  })
227
222
  public unlink(loginType: 'CUSTOM' | 'WECHAT-OPEN' | 'WECHAT-PUBLIC' | 'WECHAT-UNION' | 'PHONE') {
228
223
  return this._request.send('auth.unlink', { platform: loginType });
@@ -237,8 +232,8 @@ class User implements IUser {
237
232
  '请确认以下各项:',
238
233
  ' 1 - 调用 User.update() 的语法或参数是否正确',
239
234
  ' 2 - 用户信息中是否包含非法值',
240
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
241
- ]
235
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
236
+ ],
242
237
  })
243
238
  public async update(userInfo: IUserInfo): Promise<void> {
244
239
  const { nickName, gender, avatarUrl, province, country, city } = userInfo;
@@ -256,13 +251,13 @@ class User implements IUser {
256
251
  '请确认以下各项:',
257
252
  ' 1 - 调用 User.updatePassword() 的语法或参数是否正确',
258
253
  ' 3 - 新密码中是否包含非法字符',
259
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
260
- ]
254
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
255
+ ],
261
256
  })
262
257
  public updatePassword(newPassword: string, oldPassword: string) {
263
258
  return this._request.send('auth.updatePassword', {
264
259
  oldPassword,
265
- newPassword
260
+ newPassword,
266
261
  });
267
262
  }
268
263
  /**
@@ -275,13 +270,13 @@ class User implements IUser {
275
270
  '请确认以下各项:',
276
271
  ' 1 - 调用 User.updateEmail() 的语法或参数是否正确',
277
272
  ' 2 - 当前环境是否开通了邮箱密码登录',
278
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
279
- ]
273
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
274
+ ],
280
275
  })
281
276
  public updateEmail(newEmail: string, password?: string) {
282
277
  return this._request.send('auth.updateEmail', {
283
278
  newEmail,
284
- password
279
+ password,
285
280
  });
286
281
  }
287
282
  /**
@@ -294,8 +289,8 @@ class User implements IUser {
294
289
  '请确认以下各项:',
295
290
  ' 1 - 调用 User.updateUsername() 的语法或参数是否正确',
296
291
  ' 2 - 当前环境是否开通了用户名密码登录',
297
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
298
- ]
292
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
293
+ ],
299
294
  })
300
295
  public updateUsername(username: string) {
301
296
  if (typeof username !== 'string') {
@@ -303,7 +298,7 @@ class User implements IUser {
303
298
  }
304
299
 
305
300
  return this._request.send('auth.updateUsername', {
306
- username
301
+ username,
307
302
  });
308
303
  }
309
304
  /**
@@ -314,8 +309,8 @@ class User implements IUser {
314
309
  messages: [
315
310
  '请确认以下各项:',
316
311
  ' 1 - 调用 User.refresh() 的语法或参数是否正确',
317
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
318
- ]
312
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
313
+ ],
319
314
  })
320
315
  public async refresh(): Promise<IUserInfo> {
321
316
  const action = 'auth.getUserInfo';
@@ -335,13 +330,13 @@ class User implements IUser {
335
330
  '请确认以下各项:',
336
331
  ' 1 - 调用 auth().linkWithPhoneNumber() 的语法或参数是否正确',
337
332
  ' 2 - 当前环境是否开通了短信验证码登录',
338
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
339
- ]
333
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
334
+ ],
340
335
  })
341
336
  public async linkWithPhoneNumber(phoneNumber: string, phoneCode: string) {
342
337
  return this._request.send('auth.linkOrUpdatePhoneNumber', {
343
338
  phoneNumber: transformPhone(phoneNumber),
344
- phoneCode
339
+ phoneCode,
345
340
  });
346
341
  }
347
342
  /**
@@ -355,13 +350,13 @@ class User implements IUser {
355
350
  '请确认以下各项:',
356
351
  ' 1 - 调用语法或参数是否正确',
357
352
  ' 2 - 当前环境是否开通了短信验证码登录',
358
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
359
- ]
353
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
354
+ ],
360
355
  })
361
356
  public async updatePhoneNumber(phoneNumber: string, phoneCode: string) {
362
357
  return this._request.send('auth.linkOrUpdatePhoneNumber', {
363
358
  phoneNumber: transformPhone(phoneNumber),
364
- phoneCode
359
+ phoneCode,
365
360
  });
366
361
  }
367
362
 
@@ -395,15 +390,15 @@ class User implements IUser {
395
390
  'gender',
396
391
  'avatarUrl',
397
392
  'phone',
398
- 'username'
399
- ].forEach(infoKey => {
393
+ 'username',
394
+ ].forEach((infoKey) => {
400
395
  this[infoKey] = userInfo[infoKey];
401
396
  });
402
397
 
403
398
  this.location = {
404
- country: userInfo['country'],
405
- province: userInfo['province'],
406
- city: userInfo['city']
399
+ country: userInfo.country,
400
+ province: userInfo.province,
401
+ city: userInfo.city,
407
402
  };
408
403
  }
409
404
 
@@ -432,7 +427,7 @@ export class LoginState implements ILoginState {
432
427
 
433
428
  this.user = new User({
434
429
  cache,
435
- request
430
+ request,
436
431
  });
437
432
  }
438
433
 
@@ -446,7 +441,7 @@ export class LoginState implements ILoginState {
446
441
  this.credential = {
447
442
  refreshToken,
448
443
  accessToken,
449
- accessTokenExpire
444
+ accessTokenExpire,
450
445
  };
451
446
 
452
447
  this._loginType = this._cache.getStore(this._cache.keys.loginTypeKey);
@@ -462,7 +457,7 @@ export class LoginState implements ILoginState {
462
457
  this.credential = {
463
458
  refreshToken,
464
459
  accessToken,
465
- accessTokenExpire
460
+ accessTokenExpire,
466
461
  };
467
462
 
468
463
  this._loginType = await this._cache.getStoreAsync(this._cache.keys.loginTypeKey);
@@ -488,17 +483,17 @@ export class LoginState implements ILoginState {
488
483
  }
489
484
 
490
485
  get loginType() {
491
- return this._loginType
486
+ return this._loginType;
492
487
  }
493
488
 
494
489
  get isPhoneAuth() {
495
- return this.loginType === LOGINTYPE.PHONE
490
+ return this.loginType === LOGINTYPE.PHONE;
496
491
  }
497
492
  }
498
493
 
499
494
  class Auth {
500
495
  private readonly _config: ICloudbaseAuthConfig;
501
- private readonly _cache: ICloudbaseCache
496
+ private readonly _cache: ICloudbaseCache;
502
497
  private readonly _request: ICloudbaseRequest;
503
498
  private readonly _runtime: string;
504
499
  private _anonymousAuthProvider: AnonymousAuthProvider;
@@ -507,16 +502,12 @@ class Auth {
507
502
  private _emailAuthProvider: EmailAuthProvider;
508
503
  private _usernameAuthProvider: UsernameAuthProvider;
509
504
  private _phoneAuthProvider: PhoneAuthProvider;
510
- // private _fromApp: ICloudbase
511
-
512
- private _oAuth2AuthProvider: OAuth2AuthProvider;
513
505
 
514
506
  constructor(config: ICloudbaseAuthConfig & { cache: ICloudbaseCache, request: ICloudbaseRequest, runtime?: string }) {
515
507
  this._config = config;
516
508
  this._cache = config.cache;
517
509
  this._request = config.request;
518
- this._runtime = config.runtime || RUNTIME.WEB
519
- // this._fromApp = config._fromApp
510
+ this._runtime = config.runtime || RUNTIME.WEB;
520
511
 
521
512
  eventBus.on(EVENTS.LOGIN_TYPE_CHANGED, this._onLoginTypeChanged.bind(this));
522
513
  }
@@ -527,7 +518,7 @@ class Auth {
527
518
  get currentUser() {
528
519
  if (this._cache.mode === 'async') {
529
520
  // async storage的平台调用此API提示
530
- printWarn(ERRORS.INVALID_OPERATION, 'current platform\'s storage is asynchronous, please use getCurrenUser insteed');
521
+ printWarn(ERRORS.INVALID_OPERATION, 'current platform\'s storage is asynchronous, please use getCurrentUser insteed');
531
522
  return;
532
523
  }
533
524
 
@@ -535,9 +526,8 @@ class Auth {
535
526
 
536
527
  if (loginState) {
537
528
  return loginState.user || null;
538
- } else {
539
- return null;
540
529
  }
530
+ return null;
541
531
  }
542
532
 
543
533
  /**
@@ -548,6 +538,7 @@ class Auth {
548
538
  }
549
539
 
550
540
  /**
541
+ * @deprecated
551
542
  * 获取当前登录的用户信息-异步
552
543
  */
553
544
  @catchErrorsDecorator({
@@ -555,24 +546,30 @@ class Auth {
555
546
  messages: [
556
547
  '请确认以下各项:',
557
548
  ' 1 - 调用 auth().getCurrenUser() 的语法或参数是否正确',
558
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
559
- ]
549
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
550
+ ],
560
551
  })
561
552
  public async getCurrenUser() {
562
- const { _fromApp } = this._config
563
- const authObj = await checkFromAuthV2(_fromApp)
564
- const { authType, instance } = authObj
565
- if (authType === 'oauth') {
566
- return await instance.getUserInfo()
567
- }
568
-
553
+ return await this.getCurrentUser();
554
+ }
555
+ /**
556
+ * 获取当前登录的用户信息-异步
557
+ */
558
+ @catchErrorsDecorator({
559
+ title: '获取用户信息失败',
560
+ messages: [
561
+ '请确认以下各项:',
562
+ ' 1 - 调用 auth().getCurrentUser() 的语法或参数是否正确',
563
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
564
+ ],
565
+ })
566
+ public async getCurrentUser() {
569
567
  const loginState = await this.getLoginState();
570
568
  if (loginState) {
571
569
  await loginState.user.checkLocalInfoAsync();
572
570
  return loginState.user || null;
573
- } else {
574
- return null;
575
571
  }
572
+ return null;
576
573
  }
577
574
  /**
578
575
  * 获取当前登录类型-异步
@@ -583,7 +580,7 @@ class Auth {
583
580
  public async getAccessToken() {
584
581
  return {
585
582
  accessToken: (await this._request.getAccessToken()).accessToken,
586
- env: this._config.env
583
+ env: this._config.env,
587
584
  };
588
585
  }
589
586
  public weixinAuthProvider({ appid, scope, state }): WeixinAuthProvider {
@@ -592,7 +589,7 @@ class Auth {
592
589
  ...this._config,
593
590
  cache: this._cache,
594
591
  request: this._request,
595
- runtime: this._runtime
592
+ runtime: this._runtime,
596
593
  }, appid, scope, state);
597
594
  }
598
595
  return this._weixinAuthProvider;
@@ -603,7 +600,6 @@ class Auth {
603
600
  ...this._config,
604
601
  cache: this._cache,
605
602
  request: this._request,
606
- // _fromApp: this._fromApp
607
603
  });
608
604
  }
609
605
  return this._anonymousAuthProvider;
@@ -613,7 +609,7 @@ class Auth {
613
609
  this._customAuthProvider = new CustomAuthProvider({
614
610
  ...this._config,
615
611
  cache: this._cache,
616
- request: this._request
612
+ request: this._request,
617
613
  });
618
614
  }
619
615
  return this._customAuthProvider;
@@ -623,7 +619,7 @@ class Auth {
623
619
  this._emailAuthProvider = new EmailAuthProvider({
624
620
  ...this._config,
625
621
  cache: this._cache,
626
- request: this._request
622
+ request: this._request,
627
623
  });
628
624
  }
629
625
  return this._emailAuthProvider;
@@ -633,7 +629,7 @@ class Auth {
633
629
  this._usernameAuthProvider = new UsernameAuthProvider({
634
630
  ...this._config,
635
631
  cache: this._cache,
636
- request: this._request
632
+ request: this._request,
637
633
  });
638
634
  }
639
635
  return this._usernameAuthProvider;
@@ -644,53 +640,11 @@ class Auth {
644
640
  this._phoneAuthProvider = new PhoneAuthProvider({
645
641
  ...this._config,
646
642
  cache: this._cache,
647
- request: this._request
643
+ request: this._request,
648
644
  });
649
645
  }
650
646
  return this._phoneAuthProvider;
651
647
  }
652
-
653
- /**
654
- * oAuth2AuthProvider
655
- * options
656
- * {
657
- * providerId: 'google',
658
- * scope: 'openid+email+profile',
659
- * redirectUri: 'https://'
660
- * }
661
- * @param {Object} options
662
- * @param {string} options.providerId - 供应商Id,如 WeChat、Google、Github 等
663
- * @param {string} options.clientId - 客户端Id,平台提供的客户端标识Id
664
- * @param {string} [options.responseType=token] - 响应类型:token、code
665
- * @param {string} options.scope - 权限范围
666
- * @param {string} options.redirectUri - 授权成功回调地址
667
- * @param {boolean} options.syncProfile - 是否同步用户 Profile 信息
668
- * @param {boolean} options.forceDisableSignUp - 是否强制关闭用户注册
669
- * @returns
670
- */
671
- public oAuth2AuthProvider(options: IOAuth2AuthProviderOptions = {}): OAuth2AuthProvider {
672
- if (!this._oAuth2AuthProvider) {
673
- this._oAuth2AuthProvider = new OAuth2AuthProvider({
674
- ...this._config,
675
- cache: this._cache,
676
- request: this._request,
677
- runtime: this._runtime
678
- }, options)
679
- }
680
- return this._oAuth2AuthProvider
681
- }
682
-
683
- /**
684
- * signWithOAuth2Popup - OAuth2弹窗登录
685
- */
686
- public signWithOAuth2Popup() {
687
- this._oAuth2AuthProvider.signInWithPopup()
688
- }
689
-
690
- public signInWithOAuth2Modal(elemId: string) {
691
- this._oAuth2AuthProvider.signInWithModal(elemId)
692
- }
693
-
694
648
  /**
695
649
  * 用户名密码登录
696
650
  * @param username
@@ -708,8 +662,8 @@ class Auth {
708
662
  messages: [
709
663
  '请确认以下各项:',
710
664
  ' 1 - 调用 auth().isUsernameRegistered() 的语法或参数是否正确',
711
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
712
- ]
665
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
666
+ ],
713
667
  })
714
668
  public async isUsernameRegistered(username: string): Promise<boolean> {
715
669
  if (typeof username !== 'string') {
@@ -717,7 +671,7 @@ class Auth {
717
671
  }
718
672
 
719
673
  const { data } = await this._request.send('auth.isUsernameRegistered', {
720
- username
674
+ username,
721
675
  });
722
676
  return data?.isRegistered;
723
677
  }
@@ -753,83 +707,39 @@ class Auth {
753
707
  '请确认以下各项:',
754
708
  ' 1 - 调用 auth().signOut() 的语法或参数是否正确',
755
709
  ' 2 - 当前用户是否为匿名登录(匿名登录不支持signOut)',
756
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
757
- ]
710
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
711
+ ],
758
712
  })
759
713
  public async signOut() {
760
- // 兼容 oauth
761
- const { _fromApp } = this._config
762
- const authObj = await checkFromAuthV2(_fromApp)
763
- const { authType, instance } = authObj
764
- if (authType === 'oauth') {
765
- return await instance.signOut()
766
- }
767
-
768
- const loginType = await this.getLoginType()
714
+ // const loginType = await this.getLoginType();
769
715
  // if (loginType === LOGINTYPE.ANONYMOUS) {
770
716
  // throw new Error(JSON.stringify({
771
717
  // code: ERRORS.INVALID_OPERATION,
772
718
  // msg: 'anonymous user doesn\'t support signOut action'
773
- // }))
719
+ // }));
774
720
  // }
775
- const { refreshTokenKey, accessTokenKey, accessTokenExpireKey } = this._cache.keys
721
+ const { refreshTokenKey, accessTokenKey, accessTokenExpireKey } = this._cache.keys;
722
+ const action = 'auth.logout';
776
723
 
777
724
  const refresh_token = await this._cache.getStoreAsync(refreshTokenKey);
778
725
  if (!refresh_token) {
779
- return
780
- }
781
-
782
- if (loginType.startsWith(OAUTH2_LOGINTYPE_PREFIX)) {
783
- const accessToken = await this._cache.getStoreAsync(accessTokenKey)
784
- const accessTokenExpire = Number(await this._cache.getStoreAsync(accessTokenExpireKey))
785
- if (accessToken) {
786
- if (Date.now() < accessTokenExpire) {
787
- const resp = await this._request.fetch('/auth/v1/revoke', {
788
- method: 'POST',
789
- headers: {
790
- 'Accept': 'application/json',
791
- 'Content-Type': 'application/json'
792
- },
793
- body: JSON.stringify({
794
- token: accessToken
795
- })
796
- })
797
- const seqIdFromHeader = resp.headers.get('SeqId') || resp.headers.get('RequestId')
798
- if (resp.status >= 400 && resp.status < 500) {
799
- const body: any = await resp.json()
800
- const seqId = body.request_id || seqIdFromHeader
801
- throw new Error(`[OAuth2AuthProvider][status:${resp.status}][${body.error}(${body.error_code})] ${body.error_description} (${seqId})`)
802
- }
803
- else if (resp.status >= 500) {
804
- const body: any = await resp.json()
805
- const seqId = body.request_id || seqIdFromHeader
806
- throw new Error(`[OAuth2AuthProvider][status:${resp.status}][${body.error}(${body.error_code})] ${body.error_description} (${seqId})`)
807
- }
808
- }
809
- else {
810
- // console.warn(`[SignOut] accesstoken expired`)
811
- }
812
- }
813
- else {
814
- // console.warn(`[SignOut] accesstoken not exists`)
815
- }
816
- }
817
- else {
818
- await this._request.send('auth.logout', { refresh_token })
726
+ return;
819
727
  }
728
+ const res = await this._request.send(action, { refresh_token });
820
729
 
821
- this._cache.removeStoreAsync(refreshTokenKey)
822
- this._cache.removeStoreAsync(accessTokenKey)
823
- this._cache.removeStoreAsync(accessTokenExpireKey)
730
+ this._cache.removeStoreAsync(refreshTokenKey);
731
+ this._cache.removeStoreAsync(accessTokenKey);
732
+ this._cache.removeStoreAsync(accessTokenExpireKey);
824
733
 
825
- eventBus.fire(EVENTS.LOGIN_STATE_CHANGED)
734
+ eventBus.fire(EVENTS.LOGIN_STATE_CHANGED);
826
735
  eventBus.fire(EVENTS.LOGIN_TYPE_CHANGED, {
827
736
  env: this._config.env,
828
737
  loginType: LOGINTYPE.NULL,
829
- persistence: this._config.persistence
830
- })
738
+ persistence: this._config.persistence,
739
+ });
740
+
831
741
 
832
- return true
742
+ return res;
833
743
  }
834
744
  public async onLoginStateChanged(callback: Function) {
835
745
  eventBus.on(EVENTS.LOGIN_STATE_CHANGED, async () => {
@@ -859,14 +769,6 @@ class Auth {
859
769
  * 获取本地登录态-同步
860
770
  */
861
771
  public hasLoginState(): ILoginState | null {
862
- // 兼容oauth 逻辑,判断当前登录体系 auth or oauth
863
- const { _fromApp } = this._config
864
- const oauthInstance = _fromApp.oauthInstance
865
- const oauthLoginState = oauthInstance?.hasLoginStateSync()
866
- if (oauthLoginState) {
867
- return oauthLoginState
868
- }
869
-
870
772
  if (this._cache.mode === 'async') {
871
773
  // async storage的平台调用此API提示
872
774
  printWarn(ERRORS.INVALID_OPERATION, 'current platform\'s storage is asynchronous, please use getLoginState insteed');
@@ -879,13 +781,12 @@ class Auth {
879
781
  const loginState = new LoginState({
880
782
  envId: this._config.env,
881
783
  cache: this._cache,
882
- request: this._request
784
+ request: this._request,
883
785
  });
884
786
  loginState.checkLocalState();
885
787
  return loginState;
886
- } else {
887
- return null;
888
788
  }
789
+ return null;
889
790
  }
890
791
  /**
891
792
  * 获取本地登录态-异步
@@ -896,38 +797,22 @@ class Auth {
896
797
  messages: [
897
798
  '请确认以下各项:',
898
799
  ' 1 - 调用 auth().getLoginState() 的语法或参数是否正确',
899
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
900
- ]
800
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
801
+ ],
901
802
  })
902
803
  public async getLoginState() {
903
- // 检查当前登录体系 auth or oauth
904
- // const { _fromApp } = this._config
905
- // const authObj = await checkFromAuthV1OrV2(_fromApp)
906
- // const { authType, instance } = authObj
907
- // if (authType === 'oauth') {
908
- // return await instance.getLoginState()
909
- // }
910
- const { _fromApp } = this._config
911
- const oauthInstance = _fromApp.oauthInstance || (_fromApp as any).oauth()
912
- const oauthLoginState = oauthInstance && await oauthInstance.getLoginState()
913
- if (oauthLoginState) {
914
- return oauthLoginState
915
- }
916
-
917
- // auth 体系走默认逻辑
918
804
  const { refreshTokenKey } = this._cache.keys;
919
805
  const refreshToken = await this._cache.getStoreAsync(refreshTokenKey);
920
806
  if (refreshToken) {
921
807
  const loginState = new LoginState({
922
808
  envId: this._config.env,
923
809
  cache: this._cache,
924
- request: this._request
810
+ request: this._request,
925
811
  });
926
812
  await loginState.checkLocalStateAsync();
927
813
  return loginState;
928
- } else {
929
- return null;
930
814
  }
815
+ return null;
931
816
  }
932
817
 
933
818
  public shouldRefreshAccessToken(hook) {
@@ -940,8 +825,8 @@ class Auth {
940
825
  '请确认以下各项:',
941
826
  ' 1 - 是否已登录',
942
827
  ' 2 - 调用 auth().getUserInfo() 的语法或参数是否正确',
943
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
944
- ]
828
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
829
+ ],
945
830
  })
946
831
  public async getUserInfo(): Promise<any> {
947
832
  const action = 'auth.getUserInfo';
@@ -949,12 +834,11 @@ class Auth {
949
834
  const res = await this._request.send(action, {});
950
835
  if (res.code) {
951
836
  return res;
952
- } else {
953
- return {
954
- ...res.data,
955
- requestId: res.seqId
956
- };
957
837
  }
838
+ return {
839
+ ...res.data,
840
+ requestId: res.seqId,
841
+ };
958
842
  }
959
843
  /**
960
844
  * 获取Http鉴权header,用于云接入 HTTP 访问云函数时的鉴权
@@ -964,7 +848,7 @@ class Auth {
964
848
  const refreshToken = this._cache.getStore(refreshTokenKey);
965
849
  const accessToken = this._cache.getStore(accessTokenKey);
966
850
  return {
967
- 'x-cloudbase-credentials': accessToken + '/@@/' + refreshToken
851
+ 'x-cloudbase-credentials': `${accessToken}/@@/${refreshToken}`,
968
852
  };
969
853
  }
970
854
  /**
@@ -978,7 +862,7 @@ class Auth {
978
862
  const refreshToken = await this._cache.getStoreAsync(refreshTokenKey);
979
863
  const accessToken = await this._cache.getStoreAsync(accessTokenKey);
980
864
  return {
981
- 'x-cloudbase-credentials': accessToken + '/@@/' + refreshToken
865
+ 'x-cloudbase-credentials': `${accessToken}/@@/${refreshToken}`,
982
866
  };
983
867
  }
984
868
 
@@ -993,14 +877,14 @@ class Auth {
993
877
  '请确认以下各项:',
994
878
  ' 1 - 调用语法或参数是否正确',
995
879
  ' 2 - 当前环境是否开通了短信验证码登录',
996
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
997
- ]
880
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
881
+ ],
998
882
  })
999
883
  public async sendPhoneCode(phoneNumber: string): Promise<boolean> {
1000
884
  const { data } = await this._request.send('auth.sendPhoneCode', {
1001
- phoneNumber: transformPhone(phoneNumber)
885
+ phoneNumber: transformPhone(phoneNumber),
1002
886
  });
1003
- return data.SendStatus === 'Ok'
887
+ return data.SendStatus === 'Ok';
1004
888
  }
1005
889
 
1006
890
  /**
@@ -1033,7 +917,7 @@ class Auth {
1033
917
  }) {
1034
918
  return this.phoneAuthProvider().signIn({
1035
919
  ...param,
1036
- signMethod: SIGN_METHOD.FORCERESETPWD
920
+ signMethod: SIGN_METHOD.FORCERESETPWD,
1037
921
  });
1038
922
  }
1039
923
 
@@ -1058,7 +942,7 @@ const EVENTS = {
1058
942
  // 匿名账户被转正后触发
1059
943
  ANONYMOUS_CONVERTED: 'anonymousConverted',
1060
944
  // access token刷新后触发
1061
- ACCESS_TOKEN_REFRESHD: 'refreshAccessToken'
945
+ ACCESS_TOKEN_REFRESHD: 'refreshAccessToken',
1062
946
  };
1063
947
 
1064
948
  const component: ICloudbaseComponent = {
@@ -1071,10 +955,10 @@ const component: ICloudbaseComponent = {
1071
955
  EVENTS.LOGIN_STATE_EXPIRED,
1072
956
  EVENTS.LOGIN_STATE_CHANGED,
1073
957
  EVENTS.ACCESS_TOKEN_REFRESHD,
1074
- EVENTS.ANONYMOUS_CONVERTED
1075
- ]
958
+ EVENTS.ANONYMOUS_CONVERTED,
959
+ ],
1076
960
  },
1077
- entity: function (config: Pick<ICloudbaseAuthConfig, 'region' | 'persistence'> = { region: '', persistence: 'local' }) {
961
+ entity(config: Pick<ICloudbaseAuthConfig, 'region' | 'persistence'> = { region: '', persistence: 'local' }) {
1078
962
  if (this.authInstance) {
1079
963
  printWarn(ERRORS.INVALID_OPERATION, 'every cloudbase instance should has only one auth object');
1080
964
  return this.authInstance;
@@ -1083,7 +967,7 @@ const component: ICloudbaseComponent = {
1083
967
  // 如不明确指定persistence则优先取各平台adapter首选,其次session
1084
968
  const newPersistence = config.persistence || adapter.primaryStorage;
1085
969
  if (newPersistence && (newPersistence !== this.config.persistence)) {
1086
- this.updateConfig({ persistence: newPersistence })
970
+ this.updateConfig({ persistence: newPersistence });
1087
971
  }
1088
972
 
1089
973
  const { env, persistence, debug } = this.config;
@@ -1094,12 +978,11 @@ const component: ICloudbaseComponent = {
1094
978
  debug,
1095
979
  cache: this.cache,
1096
980
  request: this.request,
1097
- runtime: runtime,
1098
- _fromApp: this
981
+ runtime,
1099
982
  });
1100
983
  return this.authInstance;
1101
- }
1102
- }
984
+ },
985
+ };
1103
986
 
1104
987
  try {
1105
988
  // 尝试自动注册至全局变量cloudbase
@@ -1112,7 +995,7 @@ export {
1112
995
  Auth,
1113
996
  AuthProvider,
1114
997
  EVENTS,
1115
- eventBus
998
+ eventBus,
1116
999
  };
1117
1000
  /**
1118
1001
  * @api 手动注册至cloudbase app
@@ -1145,9 +1028,9 @@ export function registerProvider(name: string, provider: IProvider) {
1145
1028
  if (!this[privateName]) {
1146
1029
  this[privateName] = new provider({
1147
1030
  ...options,
1148
- ...this._config
1031
+ ...this._config,
1149
1032
  });
1150
1033
  }
1151
1034
  return this[privateName];
1152
1035
  };
1153
- }
1036
+ }