@cloudbase/auth 2.25.3 → 2.25.4

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,10 +1,9 @@
1
1
  import type { ICloudbase, ICloudbaseConfig, ICloudbasePlatformInfo } from '@cloudbase/types'
2
2
  import type { ICloudbaseCache } from '@cloudbase/types/cache'
3
3
  import type { ICloudbaseRequest } from '@cloudbase/types/request'
4
- import type { ICloudbaseAuthConfig, IUser, IUserInfo, ILoginState } from '@cloudbase/types/auth'
4
+ import type { ICloudbaseAuthConfig, IUser, ILoginState } from '@cloudbase/types/auth'
5
5
  import type { ICloudbaseComponent } from '@cloudbase/types/component'
6
- import type { GrantProviderTokenResponse, ProviderSubType } from '@cloudbase/oauth/dist/cjs/auth/models'
7
- import type { authModels, AuthOptions, Credentials } from '@cloudbase/oauth'
6
+ import type { AuthOptions, Credentials } from '@cloudbase/oauth'
8
7
  import {
9
8
  CloudbaseOAuth,
10
9
  AUTH_API_PREFIX,
@@ -12,8 +11,9 @@ import {
12
11
  EVENTS,
13
12
  AUTH_STATE_CHANGED_TYPE,
14
13
  OAUTH_TYPE,
15
- weappJwtDecodeAll,
14
+ weAppJwtDecodeAll,
16
15
  AuthError,
16
+ authModels,
17
17
  } from '@cloudbase/oauth'
18
18
  import { useAuthAdapter } from './adapter'
19
19
  import {
@@ -272,7 +272,7 @@ export class User implements IUser {
272
272
  `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
273
273
  ],
274
274
  })
275
- public async refresh(params?: { version?: string; query?: any }): Promise<IUserInfo> {
275
+ public async refresh(params?: { version?: string; query?: any }): Promise<authModels.UserInfo> {
276
276
  const newUserInfo = await this.oauthInstance.authApi.getUserInfo(params)
277
277
  if ((newUserInfo as any).code === 'INVALID_ACCESS_TOKEN') {
278
278
  this.setLocalUserInfo({})
@@ -513,7 +513,7 @@ class Auth {
513
513
  if (loginState) {
514
514
  const userInfo = loginState.user.getLocalUserInfo() as authModels.UserInfo
515
515
  await loginState.user.checkLocalInfoAsync()
516
- return { ...loginState.user, ...userInfo }
516
+ return { ...loginState.user, ...userInfo } as unknown as authModels.UserInfo & Partial<User>
517
517
  }
518
518
  return null
519
519
  }
@@ -564,7 +564,7 @@ class Auth {
564
564
  const wxInfo = wx.getAccountInfoSync().miniProgram
565
565
 
566
566
  const mainFunc = async (code) => {
567
- let result: GrantProviderTokenResponse | undefined = undefined
567
+ let result: authModels.GrantProviderTokenResponse | undefined = undefined
568
568
  let credentials: Credentials | undefined = undefined
569
569
 
570
570
  try {
@@ -639,7 +639,7 @@ class Auth {
639
639
  const wxInfo = wx.getAccountInfoSync().miniProgram
640
640
 
641
641
  const mainFunc = async (code) => {
642
- let result: GrantProviderTokenResponse | undefined = undefined
642
+ let result: authModels.GrantProviderTokenResponse | undefined = undefined
643
643
 
644
644
  try {
645
645
  result = await this.oauthInstance.authApi.grantProviderToken({
@@ -682,82 +682,6 @@ class Auth {
682
682
  return
683
683
  }
684
684
 
685
- /**
686
- * 小程序openId静默登录
687
- * @returns {Promise<LoginState>}
688
- * @memberof Auth
689
- */
690
- // @catchErrorsDecorator({
691
- // title: '小程序openId静默登录失败',
692
- // messages: [
693
- // '请确认以下各项:',
694
- // ' 1 - 当前环境是否开启了小程序openId静默登录',
695
- // ' 2 - 调用 auth().signInWithOpenId() 的语法或参数是否正确',
696
- // `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
697
- // ],
698
- // })
699
- // public async signInWithOpenId({ useWxCloud = true } = {}): Promise<LoginState> {
700
- // if (!adapterForWxMp.isMatch()) {
701
- // throw Error('wx api undefined')
702
- // }
703
- // const wxInfo = wx.getAccountInfoSync().miniProgram
704
-
705
- // const mainFunc = async (code) => {
706
- // let result: GrantProviderTokenResponse | undefined = undefined
707
- // let credentials: Credentials | undefined = undefined
708
-
709
- // try {
710
- // result = await this.oauthInstance.authApi.grantProviderToken(
711
- // {
712
- // provider_id: wxInfo?.appId,
713
- // provider_code: code,
714
- // provider_params: {
715
- // provider_code_type: 'open_id',
716
- // appid: wxInfo?.appId,
717
- // },
718
- // },
719
- // useWxCloud,
720
- // )
721
-
722
- // if ((result as any)?.error_code || !result.provider_token) {
723
- // throw result
724
- // }
725
-
726
- // credentials = await this.oauthInstance.authApi.signInWithProvider(
727
- // { provider_token: result.provider_token },
728
- // useWxCloud,
729
- // )
730
-
731
- // if ((credentials as any)?.error_code) {
732
- // throw credentials
733
- // }
734
- // } catch (error) {
735
- // throw error
736
- // }
737
- // await this.oauthInstance.oauth2client.setCredentials(credentials as Credentials)
738
- // }
739
-
740
- // await new Promise((resolve, reject) => {
741
- // wx.login({
742
- // success: async (res: { code: string }) => {
743
- // try {
744
- // await mainFunc(res.code)
745
- // resolve(true)
746
- // } catch (error) {
747
- // reject(error)
748
- // }
749
- // },
750
- // fail: (res: any) => {
751
- // const error = new Error(res?.errMsg)
752
- // ;(error as any).code = res?.errno
753
- // reject(error)
754
- // },
755
- // })
756
- // })
757
-
758
- // return this.createLoginState()
759
- // }
760
-
761
685
  /**
762
686
  * 小程序unionId静默登录
763
687
  * @returns {Promise<LoginState>}
@@ -1044,29 +968,6 @@ class Auth {
1044
968
  return exist
1045
969
  }
1046
970
 
1047
- /**
1048
- * 登出
1049
- */
1050
- // @catchErrorsDecorator({
1051
- // title: '用户登出失败',
1052
- // messages: [
1053
- // '请确认以下各项:',
1054
- // ' 1 - 调用 auth().signOut() 的语法或参数是否正确',
1055
- // ' 2 - 当前用户是否为匿名登录(匿名登录不支持signOut)',
1056
- // `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
1057
- // ],
1058
- // })
1059
- // public async signOut(params?: authModels.SignoutRequest): Promise<void | authModels.SignoutReponse> {
1060
- // const { userInfoKey } = this.cache.keys
1061
- // const res = await this.oauthInstance.authApi.signOut(params)
1062
- // await this.cache.removeStoreAsync(userInfoKey)
1063
-
1064
- // eventBus.fire(EVENTS.LOGIN_STATE_CHANGED, { eventType: LOGIN_STATE_CHANGED_TYPE.SIGN_OUT })
1065
-
1066
- // eventBus.fire(EVENTS.AUTH_STATE_CHANGED, { event: AUTH_STATE_CHANGED_TYPE.SIGNED_OUT })
1067
- // return res
1068
- // }
1069
-
1070
971
  /**
1071
972
  * 获取本地登录态-同步
1072
973
  */
@@ -1075,7 +976,7 @@ class Auth {
1075
976
  // async storage的平台调用此API提示
1076
977
  printWarn(
1077
978
  ERRORS.INVALID_OPERATION,
1078
- 'current platform\'s storage is asynchronous, please use getLoginState insteed',
979
+ 'current platform\'s storage is asynchronous, please use getLoginState instead',
1079
980
  )
1080
981
  return
1081
982
  }
@@ -1263,7 +1164,7 @@ class Auth {
1263
1164
  public async onLoginStateChanged(callback: Function) {
1264
1165
  this.config.eventBus?.on(EVENTS.LOGIN_STATE_CHANGED, async (params) => {
1265
1166
  // getLoginState会重复触发getCredentials,导致死循环,所以getCredentials出错不再出发getLoginState
1266
- const loginState = params?.data?.eventType !== LOGIN_STATE_CHANGED_TYPE.CREDENTIALS_ERROR ? await this.getLoginState() : {}
1167
+ const loginState = params?.data?.eventType !== LOGIN_STATE_CHANGED_TYPE.CREDENTIALS_ERROR ? await this.getLoginState() : {}
1267
1168
  callback.call(this, { ...params, ...loginState })
1268
1169
  })
1269
1170
  // 立刻执行一次回调
@@ -1302,7 +1203,7 @@ class Auth {
1302
1203
  `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`,
1303
1204
  ],
1304
1205
  })
1305
- public async getProviderSubType(): Promise<ProviderSubType> {
1206
+ public async getProviderSubType(): Promise<authModels.ProviderSubType> {
1306
1207
  return this.oauthInstance.authApi.getProviderSubType()
1307
1208
  }
1308
1209
 
@@ -1343,6 +1244,12 @@ class Auth {
1343
1244
  username: rawUsername = '',
1344
1245
  bindInfo = undefined,
1345
1246
  loginType = '',
1247
+ }: {
1248
+ verificationInfo?: authModels.GetVerificationResponse
1249
+ verificationCode?: string
1250
+ username?: string
1251
+ bindInfo?: any
1252
+ loginType?: string
1346
1253
  }): Promise<LoginState> {
1347
1254
  try {
1348
1255
  // 1. 验证验证码
@@ -1452,7 +1359,7 @@ class Auth {
1452
1359
  }
1453
1360
  }
1454
1361
 
1455
- // ========== SbaseApi methods merged below ==========
1362
+ // ========== new auth api methods merged below ==========
1456
1363
 
1457
1364
  /**
1458
1365
  * https://supabase.com/docs/reference/javascript/auth-signinanonymously
@@ -1481,7 +1388,7 @@ class Auth {
1481
1388
  * @param params
1482
1389
  * @returns Promise<SignUpRes>
1483
1390
  */
1484
- async signUp(params: authModels.SignUpRequest): Promise<SignUpRes> {
1391
+ async signUp(params: authModels.SignUpRequest & { phone?: string }): Promise<SignUpRes> {
1485
1392
  if (params.phone_number || params.verification_code || params.verification_token || params.provider_token) {
1486
1393
  await this.oauthInstance.authApi.signUp(params)
1487
1394
  return this.createLoginState() as any
@@ -1547,7 +1454,7 @@ class Auth {
1547
1454
  *
1548
1455
  * @param params
1549
1456
  */
1550
- async signOut(params?: authModels.SignoutRequest): Promise<void | authModels.SignoutReponse> {
1457
+ async signOut(params?: authModels.SignoutRequest,): Promise<authModels.SignoutResponse & { data: Object; error: AuthError }> {
1551
1458
  try {
1552
1459
  const { userInfoKey } = this.cache.keys
1553
1460
  const res = await this.oauthInstance.authApi.signOut(params)
@@ -1816,21 +1723,11 @@ class Auth {
1816
1723
  }
1817
1724
  }
1818
1725
 
1819
- // https://supabase.com/docs/reference/javascript/auth-signinwithsso
1820
- async signInWithSSO() {
1821
- //
1822
- }
1823
-
1824
- // https://supabase.com/docs/reference/javascript/auth-signinwithweb3
1825
- async signInWithWeb3() {
1826
- //
1827
- }
1828
-
1829
1726
  // https://supabase.com/docs/reference/javascript/auth-getclaims
1830
1727
  async getClaims(): Promise<GetClaimsRes> {
1831
1728
  try {
1832
1729
  const { accessToken } = await this.getAccessToken()
1833
- const parsedToken = weappJwtDecodeAll(accessToken)
1730
+ const parsedToken = weAppJwtDecodeAll(accessToken)
1834
1731
  return { data: parsedToken, error: null }
1835
1732
  } catch (error) {
1836
1733
  return { data: {}, error: new AuthError(error) }
@@ -1890,12 +1787,14 @@ class Auth {
1890
1787
 
1891
1788
  await this.oauthInstance.authApi.resetPassword({
1892
1789
  email: isEmail ? emailOrPhone : undefined,
1893
- phone: !isEmail ? emailOrPhone : undefined,
1790
+ phone_number: !isEmail ? emailOrPhone : undefined,
1894
1791
  new_password: attributes.password,
1895
1792
  verification_token: verificationTokenRes.verification_token,
1896
1793
  })
1897
1794
 
1898
- this.config.eventBus?.fire(EVENTS.AUTH_STATE_CHANGED, { event: AUTH_STATE_CHANGED_TYPE.PASSWORD_RECOVERY })
1795
+ this.config.eventBus?.fire(EVENTS.AUTH_STATE_CHANGED, {
1796
+ event: AUTH_STATE_CHANGED_TYPE.PASSWORD_RECOVERY,
1797
+ })
1899
1798
 
1900
1799
  const res = await this.signInWithPassword({
1901
1800
  email: isEmail ? emailOrPhone : undefined,
@@ -2087,7 +1986,7 @@ class Auth {
2087
1986
  // 发送验证码
2088
1987
  const verificationInfo = await this.getVerification(verificationParams)
2089
1988
 
2090
- Object.keys(restParams).length > 0 && await this.updateUserBasicInfo(restParams)
1989
+ Object.keys(restParams).length > 0 && (await this.updateUserBasicInfo(restParams))
2091
1990
 
2092
1991
  extraRes = {
2093
1992
  messageId: verificationInfo.verification_id,
@@ -2158,7 +2057,7 @@ class Auth {
2158
2057
  try {
2159
2058
  const providers = await this.oauthInstance.authApi.getProviders()
2160
2059
 
2161
- return { data: { identities: providers?.data?.filter(v => !!v.bind) }, error: null }
2060
+ return { data: { identities: providers?.data?.filter(v => !!v.bind) as unknown as GetUserIdentitiesRes['data']['identities'] }, error: null }
2162
2061
  } catch (error) {
2163
2062
  return { data: {}, error: new AuthError(error) }
2164
2063
  }
@@ -2325,7 +2224,7 @@ class Auth {
2325
2224
  refresh_token: { required: true, message: 'Refresh token is required' },
2326
2225
  })
2327
2226
 
2328
- await this.oauthInstance.oauth2client.refreshToken(params, { throwOnError: true })
2227
+ await this.oauthInstance.oauth2client.refreshToken(params, { throwError: true })
2329
2228
 
2330
2229
  const { data: { session } = {} } = await this.getSession()
2331
2230
 
@@ -2588,13 +2487,13 @@ class Auth {
2588
2487
  return {
2589
2488
  id: userId,
2590
2489
  aud: 'authenticated',
2591
- role: userInfo.groups,
2490
+ role: userInfo.groups.map(group => (typeof group === 'string' ? group : group.id)),
2592
2491
  email: email || '',
2593
2492
  email_confirmed_at: userInfo?.email_verified ? userInfo.created_at : userInfo.created_at,
2594
2493
  phone,
2595
2494
  phone_confirmed_at: phone ? userInfo.created_at : undefined,
2596
2495
  confirmed_at: userInfo.created_at,
2597
- last_sign_in_at: userInfo.last_sign_in_at,
2496
+ last_sign_in_at: (userInfo as any).last_sign_in_at,
2598
2497
  app_metadata: {
2599
2498
  provider: userInfo.loginType?.toLowerCase() || 'cloudbase',
2600
2499
  providers: [userInfo.loginType?.toLowerCase() || 'cloudbase'],
@@ -2626,7 +2525,7 @@ class Auth {
2626
2525
  provider: p.id || 'cloudbase',
2627
2526
  created_at: userInfo.created_at,
2628
2527
  updated_at: userInfo.updated_at,
2629
- last_sign_in_at: userInfo.last_sign_in_at,
2528
+ last_sign_in_at: (userInfo as any).last_sign_in_at,
2630
2529
  })) || [],
2631
2530
  created_at: userInfo.created_at,
2632
2531
  updated_at: userInfo.updated_at,
@@ -2656,7 +2555,6 @@ class Auth {
2656
2555
  }
2657
2556
  }
2658
2557
 
2659
-
2660
2558
  private async init(): Promise<{ error: Error | null }> {
2661
2559
  try {
2662
2560
  const credentials: Credentials = await this.oauthInstance.oauth2client.localCredentials.getCredentials()
@@ -2677,7 +2575,7 @@ Partial<AuthOptions> & {
2677
2575
  }
2678
2576
 
2679
2577
  export function generateAuthInstance(
2680
- config: TInitAuthOptions,
2578
+ config: TInitAuthOptions & { sdkVersion?: string },
2681
2579
  options?: {
2682
2580
  clientId: ICloudbaseConfig['clientId']
2683
2581
  env: ICloudbaseConfig['env']
@@ -2732,8 +2630,7 @@ export function generateAuthInstance(
2732
2630
  persistence: config.persistence,
2733
2631
  debug,
2734
2632
  cache:
2735
- cache
2736
- || new CloudbaseCache({
2633
+ cache || new CloudbaseCache({
2737
2634
  persistence: config.persistence,
2738
2635
  keys: { userInfoKey: `user_info_${env}` },
2739
2636
  platformInfo: platform,
package/src/type.ts CHANGED
@@ -1,26 +1,5 @@
1
1
  import type { authModels, OAUTH_TYPE } from '@cloudbase/oauth'
2
-
3
- class AuthError extends Error {
4
- /**
5
- * Error code associated with the error. Most errors coming from
6
- * HTTP responses will have a code, though some errors that occur
7
- * before a response is received will not have one present. In that
8
- * case {@link #status} will also be undefined.
9
- */
10
- code: (string & {}) | undefined
11
-
12
- /** HTTP status code that caused the error. */
13
- status: number | undefined
14
-
15
- protected __isAuthError = true
16
-
17
- constructor(error) {
18
- super(error.error_description || error.message)
19
- this.name = 'AuthError'
20
- this.status = error.error
21
- this.code = error.error_code
22
- }
23
- }
2
+ import { AuthError } from '@cloudbase/oauth'
24
3
 
25
4
 
26
5
  export interface SignInAnonymouslyReq {
@@ -62,10 +41,10 @@ export declare type User = {
62
41
  }
63
42
 
64
43
  export declare type Session = {
65
- access_token: string // 访问令牌
66
- refresh_token: string // 刷新令牌
67
- expires_in: number // 过期时间(秒)
68
- token_type: string // 令牌类型
44
+ access_token?: string // 访问令牌
45
+ refresh_token?: string // 刷新令牌
46
+ expires_in?: number // 过期时间(秒)
47
+ token_type?: string // 令牌类型
69
48
  user: User // 用户信息
70
49
  }
71
50
 
@@ -200,7 +179,6 @@ export interface GetUserIdentitiesRes {
200
179
  name: string // 身份源名称
201
180
  picture: string // 头像URL
202
181
  }>
203
- | authModels.ProvidersResponse['data']
204
182
  }
205
183
  error: AuthError | null // 错误信息,成功时为null
206
184
  }