@cloudbase/auth 2.23.4-alpha.0 → 2.24.0

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.
@@ -0,0 +1,1495 @@
1
+ import type { ICloudbaseAuthConfig } from '@cloudbase/types/auth'
2
+ import type { authModels, CloudbaseOAuth, Credentials } from '@cloudbase/oauth'
3
+ import type { ICloudbaseCache } from '@cloudbase/types/cache'
4
+ import {
5
+ weappJwtDecodeAll,
6
+ EVENTS,
7
+ AUTH_STATE_CHANGED_TYPE,
8
+ AuthError,
9
+ OAUTH_TYPE,
10
+ LOGIN_STATE_CHANGED_TYPE,
11
+ } from '@cloudbase/oauth'
12
+ import {
13
+ CommonRes,
14
+ DeleteMeReq,
15
+ GetClaimsRes,
16
+ GetUserIdentitiesRes,
17
+ GetUserRes,
18
+ LinkIdentityReq,
19
+ LinkIdentityRes,
20
+ OnAuthStateChangeCallback,
21
+ ReauthenticateRes,
22
+ ResendReq,
23
+ ResendRes,
24
+ ResetPasswordForEmailRes,
25
+ ResetPasswordForOldReq,
26
+ SetSessionReq,
27
+ SignInAnonymouslyReq,
28
+ SignInOAuthRes,
29
+ SignInRes,
30
+ SignInWithIdTokenReq,
31
+ SignInWithOAuthReq,
32
+ SignInWithOtpReq,
33
+ SignInWithOtpRes,
34
+ SignInWithPasswordReq,
35
+ SignUpRes,
36
+ UnlinkIdentityReq,
37
+ UpdateUserAttributes,
38
+ UpdateUserReq,
39
+ UpdateUserWithVerificationRes,
40
+ VerifyOAuthReq,
41
+ VerifyOtpReq,
42
+ } from './type'
43
+ import { eventBus, LoginState, User } from '.'
44
+ import { saveToBrowserSession, getBrowserSession, removeBrowserSession, addUrlSearch } from './utils'
45
+ import { utils } from '@cloudbase/utilities'
46
+ import { adapterForWxMp } from './utilities'
47
+ export const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined'
48
+
49
+ declare const wx: any
50
+
51
+ export class SbaseApi {
52
+ readonly config: ICloudbaseAuthConfig
53
+ oauthInstance: CloudbaseOAuth
54
+ readonly cache: ICloudbaseCache
55
+ private listeners: Map<string, Set<OnAuthStateChangeCallback>> = new Map()
56
+ private hasListenerSetUp = false
57
+
58
+ constructor(config: ICloudbaseAuthConfig & { cache: ICloudbaseCache }) {
59
+ this.config = config
60
+ this.oauthInstance = config.oauthInstance
61
+ this.cache = config.cache
62
+ this.init()
63
+ }
64
+
65
+ /**
66
+ * 获取当前登录的用户信息-同步
67
+ */
68
+ get currentUser() {
69
+ const loginState = this.hasLoginState()
70
+
71
+ if (loginState) {
72
+ return loginState.user || null
73
+ }
74
+ return null
75
+ }
76
+
77
+ hasLoginState(): LoginState | null {
78
+ throw new Error('Auth.hasLoginState() is not implemented')
79
+ }
80
+
81
+ async setAccessKey() {
82
+ throw new Error('Auth.setAccessKey() is not implemented')
83
+ }
84
+
85
+ async signIn(_params: authModels.SignInRequest): Promise<LoginState> {
86
+ throw new Error('Auth.signIn() is not implemented')
87
+ }
88
+
89
+ async signInWithProvider(_params: authModels.SignInWithProviderRequest): Promise<LoginState> {
90
+ throw new Error('Auth.signInWithProvider() is not implemented')
91
+ }
92
+
93
+ async genProviderRedirectUri(_params: authModels.GenProviderRedirectUriRequest,): Promise<authModels.GenProviderRedirectUriResponse> {
94
+ throw new Error('Auth.genProviderRedirectUri() is not implemented')
95
+ }
96
+
97
+ async getAccessToken(): Promise<{
98
+ accessToken: any
99
+ env: string
100
+ }> {
101
+ throw new Error('Auth.getAccessToken() is not implemented')
102
+ }
103
+
104
+ async getUserInfo(): Promise<(authModels.UserInfo & Partial<User>) | null> {
105
+ throw new Error('Auth.getUserInfo() is not implemented')
106
+ }
107
+
108
+ async updateUserBasicInfo(_params: authModels.ModifyUserBasicInfoRequest) {
109
+ throw new Error('Auth.updateUserBasicInfo() is not implemented')
110
+ }
111
+
112
+ setCustomSignFunc(_getTickFn: authModels.GetCustomSignTicketFn): void {
113
+ throw new Error('Auth.setCustomSignFunc() is not implemented')
114
+ }
115
+
116
+ async grantProviderToken(_params: authModels.GrantProviderTokenRequest,): Promise<authModels.GrantProviderTokenResponse> {
117
+ throw new Error('Auth.grantProviderToken() is not implemented')
118
+ }
119
+
120
+ async bindWithProvider(_params: authModels.BindWithProviderRequest): Promise<void> {
121
+ throw new Error('Auth.bindWithProvider() is not implemented')
122
+ }
123
+
124
+ async signInWithUsername(_params: {
125
+ verificationInfo?: { verification_id: string; is_user: boolean }
126
+ verificationCode?: string
127
+ username?: string // 用户名称,长度 5-24 位,支持字符中英文、数字、特殊字符(仅支持_-),不支持中文
128
+ bindInfo?: any
129
+ loginType?: string
130
+ autoSignUp?: boolean
131
+ }): Promise<LoginState> {
132
+ throw new Error('Auth.signInWithUsername() is not implemented')
133
+ }
134
+
135
+ async getVerification(
136
+ _params: authModels.GetVerificationRequest,
137
+ _options?: { withCaptcha: boolean },
138
+ ): Promise<authModels.GetVerificationResponse> {
139
+ throw new Error('Auth.getVerification() is not implemented')
140
+ }
141
+
142
+ async createLoginState(
143
+ _params?: { version?: string; query?: any },
144
+ _options?: { asyncRefreshUser?: boolean },
145
+ ): Promise<LoginState> {
146
+ throw new Error('Auth.createLoginState() is not implemented')
147
+ }
148
+
149
+ async verify(_params: authModels.VerifyRequest): Promise<authModels.VerifyResponse> {
150
+ throw new Error('Auth.verify() is not implemented')
151
+ }
152
+
153
+ /**
154
+ * https://supabase.com/docs/reference/javascript/auth-signinanonymously
155
+ * Sign in a user anonymously.
156
+ * const { data, error } = await auth.signInAnonymously();
157
+ * @param params
158
+ * @returns Promise<SignInRes>
159
+ */
160
+ async signInAnonymously(params: SignInAnonymouslyReq): Promise<SignInRes> {
161
+ try {
162
+ await this.oauthInstance.authApi.signInAnonymously(params)
163
+ const loginState = await this.createLoginState()
164
+
165
+ const { data: { session } = {} } = await this.getSession()
166
+
167
+ // loginState返回是为了兼容v2版本
168
+ return { ...(loginState as any), data: { user: session.user, session }, error: null }
169
+ } catch (error) {
170
+ return { data: {}, error: new AuthError(error) }
171
+ }
172
+ }
173
+
174
+ /**
175
+ * https://supabase.com/docs/reference/javascript/auth-signup
176
+ * Sign up a new user with email or phone using a one-time password (OTP). If the account not exist, a new account will be created.
177
+ * let signUpResolve = null;
178
+ const res = await app.auth.signUp({
179
+ phone: "xxxxxx",
180
+ });
181
+
182
+ signUpResolve = res.data.verify
183
+
184
+ const res = await signUpResolve(code);
185
+
186
+ // res.data.callback支持 messageId 参数用于重新发送验证码进行验证,messageId 可以从 resend() 方法中获取
187
+ const { data } = await app.auth.resend({
188
+ type: "signup",
189
+ phone: "xxxxxx",
190
+ })
191
+ const res = await signUpResolve(code, data.messageId);
192
+ * @param params
193
+ * @returns Promise<SignUpRes>
194
+ */
195
+ async signUp(params: authModels.SignUpRequest): Promise<SignUpRes> {
196
+ try {
197
+ // 参数校验:email或phone必填其一
198
+ this.validateAtLeastOne(params, [['email'], ['phone']], 'You must provide either an email or phone number')
199
+
200
+ // 第一步:发送验证码并存储 verificationInfo
201
+ const verificationInfo = await this.getVerification(params.email ? { email: params.email } : { phone_number: this.formatPhone(params.phone) },)
202
+
203
+ return {
204
+ data: {
205
+ // 第二步:等待用户输入验证码(通过 Promise 包装用户输入事件)
206
+ verifyOtp: async ({ token, messageId = verificationInfo.verification_id }): Promise<SignInRes> => {
207
+ try {
208
+ // 第三步:待用户输入完验证码之后,验证短信验证码
209
+ const verificationTokenRes = await this.verify({
210
+ verification_id: messageId || verificationInfo.verification_id,
211
+ verification_code: token,
212
+ })
213
+
214
+ // 第四步:注册并登录或直接登录
215
+ // 如果用户已经存在,直接登录
216
+ if (verificationInfo.is_user) {
217
+ await this.signIn({
218
+ username: params.email || this.formatPhone(params.phone),
219
+ verification_token: verificationTokenRes.verification_token,
220
+ })
221
+ } else {
222
+ // 如果用户不存在,注册用户
223
+ const data = JSON.parse(JSON.stringify(params))
224
+ delete data.email
225
+ delete data.phone
226
+
227
+ await this.oauthInstance.authApi.signUp({
228
+ ...data,
229
+ ...(params.email ? { email: params.email } : { phone_number: this.formatPhone(params.phone) }),
230
+ verification_token: verificationTokenRes.verification_token,
231
+ verification_code: token,
232
+ })
233
+ await this.createLoginState()
234
+ }
235
+
236
+ const { data: { session } = {} } = await this.getSession()
237
+
238
+ return { data: { user: session.user, session }, error: null }
239
+ } catch (error) {
240
+ return { data: {}, error: new AuthError(error) }
241
+ }
242
+ },
243
+ },
244
+ error: null,
245
+ }
246
+ } catch (error) {
247
+ return { data: {}, error: new AuthError(error) }
248
+ }
249
+ }
250
+
251
+ /**
252
+ * https://supabase.com/docs/reference/javascript/auth-signout
253
+ * const result = await auth.signOut();
254
+ *
255
+ * @param params
256
+ */
257
+ async signOut(params?: authModels.SignoutRequest): Promise<void | authModels.SignoutReponse> {
258
+ try {
259
+ const { userInfoKey } = this.cache.keys
260
+ const res = await this.oauthInstance.authApi.signOut(params)
261
+ await this.cache.removeStoreAsync(userInfoKey)
262
+ this.setAccessKey()
263
+
264
+ eventBus.fire(EVENTS.LOGIN_STATE_CHANGED, { eventType: LOGIN_STATE_CHANGED_TYPE.SIGN_OUT })
265
+
266
+ eventBus.fire(EVENTS.AUTH_STATE_CHANGED, { event: AUTH_STATE_CHANGED_TYPE.SIGNED_OUT })
267
+
268
+ // res返回是为了兼容v2版本
269
+ return { ...res, data: {}, error: null }
270
+ } catch (error) {
271
+ return { data: {}, error: new AuthError(error) }
272
+ }
273
+ }
274
+
275
+ /**
276
+ * https://supabase.com/docs/reference/javascript/auth-onauthstatechange
277
+ * Receive a notification every time an auth event happens. Safe to use without an async function as callback.
278
+ * const { data } = app.auth.onAuthStateChange((event, session) => {
279
+ console.log(event, session);
280
+ if (event === "INITIAL_SESSION") {
281
+ // handle initial session
282
+ } else if (event === "SIGNED_IN") {
283
+ // handle sign in event
284
+ } else if (event === "SIGNED_OUT") {
285
+ // handle sign out event
286
+ } else if (event === "PASSWORD_RECOVERY") {
287
+ // handle password recovery event
288
+ } else if (event === "TOKEN_REFRESHED") {
289
+ // handle token refreshed event
290
+ } else if (event === "USER_UPDATED") {
291
+ // handle user updated event
292
+ }
293
+ });
294
+ // call unsubscribe to remove the callback
295
+ data.subscription.unsubscribe();
296
+ * @param callback
297
+ * @returns Promise<{ data: { subscription: Subscription }, error: Error | null }>
298
+ */
299
+ onAuthStateChange(callback: OnAuthStateChangeCallback) {
300
+ if (!this.hasListenerSetUp) {
301
+ this.setupListeners()
302
+ this.hasListenerSetUp = true
303
+ }
304
+
305
+ const id = Math.random().toString(36)
306
+
307
+ if (!this.listeners.has(id)) {
308
+ this.listeners.set(id, new Set())
309
+ }
310
+
311
+ this.listeners.get(id)!.add(callback)
312
+
313
+ // 返回 Subscription 对象
314
+ const subscription = {
315
+ id,
316
+ callback,
317
+ unsubscribe: () => {
318
+ const callbacks = this.listeners.get(id)
319
+ if (callbacks) {
320
+ callbacks.delete(callback)
321
+ if (callbacks.size === 0) {
322
+ this.listeners.delete(id)
323
+ }
324
+ }
325
+ },
326
+ }
327
+
328
+ return {
329
+ data: { subscription },
330
+ }
331
+ }
332
+
333
+ /**
334
+ * https://supabase.com/docs/reference/javascript/auth-signinwithpassword
335
+ * Log in an existing user with an email and password or phone and password or username and password.
336
+ * const { data } = await app.auth.signInWithPassword({
337
+ username: "xxx",
338
+ password: "xxx",
339
+ })
340
+ * @param params
341
+ * @returns Promise<SignInRes>
342
+ */
343
+ async signInWithPassword(params: SignInWithPasswordReq): Promise<SignInRes> {
344
+ try {
345
+ // 参数校验:username/email/phone三选一,password必填
346
+ this.validateAtLeastOne(
347
+ params,
348
+ [['username'], ['email'], ['phone']],
349
+ 'You must provide either username, email, or phone',
350
+ )
351
+ this.validateParams(params, {
352
+ password: { required: true, message: 'Password is required' },
353
+ })
354
+
355
+ await this.signIn({
356
+ username: params.username || params.email || this.formatPhone(params.phone),
357
+ password: params.password,
358
+ })
359
+ const { data: { session } = {} } = await this.getSession()
360
+
361
+ return { data: { user: session.user, session }, error: null }
362
+ } catch (error) {
363
+ return { data: {}, error: new AuthError(error) }
364
+ }
365
+ }
366
+
367
+ /**
368
+ * https://supabase.com/docs/reference/javascript/auth-signinwithidtoken
369
+ * 第三方平台登录。如果用户不存在,会根据云开发平台-登录方式中对应身份源的登录模式配置,判断是否自动注册
370
+ * @param params
371
+ * @returns Promise<SignInRes>
372
+ */
373
+ async signInWithIdToken(params: SignInWithIdTokenReq): Promise<SignInRes> {
374
+ try {
375
+ // 参数校验:token必填
376
+ this.validateParams(params, {
377
+ token: { required: true, message: 'Token is required' },
378
+ })
379
+
380
+ await this.signInWithProvider({
381
+ provider_token: params.token,
382
+ })
383
+ const { data: { session } = {} } = await this.getSession()
384
+
385
+ return { data: { user: session.user, session }, error: null }
386
+ } catch (error) {
387
+ return { data: {}, error: new AuthError(error) }
388
+ }
389
+ }
390
+
391
+ /**
392
+ * https://supabase.com/docs/reference/javascript/auth-signinwithotp
393
+ * Log in a user using a one-time password (OTP).
394
+ * let signResolve = null;
395
+ const res = await app.auth.signInWithOtp({
396
+ phone: "xxxxxx",
397
+ });
398
+
399
+ signResolve = res.data.verify
400
+
401
+ const res = await signResolve(code);
402
+
403
+ // res.data.callback支持 messageId 参数用于重新发送验证码进行验证,messageId 可以从 resend() 方法中获取
404
+ const { data } = await app.auth.resend({
405
+ type: "signup",
406
+ phone: "xxxxxx",
407
+ })
408
+ const res = await signUpResolve(code, data.messageId);
409
+ * @param params
410
+ * @returns Promise<SignInWithOtpRes>
411
+ */
412
+ async signInWithOtp(params: SignInWithOtpReq): Promise<SignInWithOtpRes> {
413
+ try {
414
+ // 参数校验:email或phone必填其一
415
+ this.validateAtLeastOne(params, [['email'], ['phone']], 'You must provide either an email or phone number')
416
+
417
+ // 第一步:发送验证码并存储 verificationInfo
418
+ const verificationInfo = await this.getVerification(params.email ? { email: params.email } : { phone_number: this.formatPhone(params.phone) },)
419
+
420
+ return {
421
+ data: {
422
+ user: null,
423
+ session: null,
424
+ // 第二步:等待用户输入验证码(通过 Promise 包装用户输入事件)
425
+ verifyOtp: async ({ token, messageId = verificationInfo.verification_id }): Promise<SignInRes> => this.verifyOtp({
426
+ email: params.email,
427
+ phone: params.phone,
428
+ token,
429
+ messageId,
430
+ }),
431
+ },
432
+ error: null,
433
+ }
434
+ } catch (error) {
435
+ return { data: {}, error: new AuthError(error) }
436
+ }
437
+ }
438
+
439
+ /**
440
+ * 校验第三方平台授权登录回调,需先调用 signInWithOAuth 生成第三方平台授权 Uri,访问该 Uri 后,会跳转到第三方平台授权页面,授权完成后回调回来再调用该方法,不传参数则从 url query 和 sessionStorage 中获取
441
+ * // 1. 获取第三方平台授权页地址
442
+ const { data } = app.auth.signInWithOAuth({
443
+ provider: 'string'
444
+ options: {
445
+ redirectTo: 'https://example.com/callback'
446
+ state: 'string'
447
+ }
448
+ })
449
+
450
+ // 2. 访问uri (如 location.href = uri)
451
+
452
+ // 3. 校验第三方平台授权回调
453
+ const { data } = await app.auth.verifyOAuth()
454
+ * @param params
455
+ * @returns Promise<SignInRes>
456
+ */
457
+ async verifyOAuth(params?: VerifyOAuthReq): Promise<SignInRes | LinkIdentityRes> {
458
+ const data: any = {}
459
+ try {
460
+ // 回调至 provider_redirect_uri 地址(url query中携带 授权code,state等参数),此时检查 state 是否符合预期(如 自己设置的 wx_open)
461
+ const code = params?.code || utils.getQuery('code')
462
+ const state = params?.state || utils.getQuery('state')
463
+
464
+ // 参数校验:code和state必填
465
+ if (!code) {
466
+ return { data: {}, error: new AuthError({ message: 'Code is required' }) }
467
+ }
468
+
469
+ if (!state) {
470
+ return { data: {}, error: new AuthError({ message: 'State is required' }) }
471
+ }
472
+
473
+ const cacheData = getBrowserSession(state)
474
+ data.type = cacheData?.type
475
+
476
+ const provider = params?.provider || cacheData?.provider || utils.getQuery('provider')
477
+
478
+ if (!provider) {
479
+ return { data, error: new AuthError({ message: 'Provider is required' }) }
480
+ }
481
+
482
+ // state符合预期,则获取该三方平台token
483
+ const { provider_token: token } = await this.grantProviderToken({
484
+ provider_id: provider,
485
+ provider_redirect_uri: location.origin + location.pathname, // 指定三方平台跳回的 url 地址
486
+ provider_code: code, // 第三方平台跳转回页面时,url param 中携带的 code 参数
487
+ })
488
+
489
+ let res: SignInRes | LinkIdentityRes
490
+
491
+ if (cacheData.type === OAUTH_TYPE.BIND_IDENTITY) {
492
+ res = await this.oauthInstance.authApi.toBindIdentity({ provider_token: token, provider, fireEvent: true })
493
+ } else {
494
+ // 通过 provider_token 仅登录或登录并注册(与云开发平台-登录方式-身份源登录模式配置有关)
495
+ res = await this.signInWithIdToken({
496
+ token,
497
+ })
498
+ res.data = { ...data, ...res.data }
499
+ }
500
+
501
+ const localSearch = new URLSearchParams(location?.search)
502
+ localSearch.delete('code')
503
+ localSearch.delete('state')
504
+ addUrlSearch(
505
+ cacheData?.search === undefined ? `?${localSearch.toString()}` : cacheData?.search,
506
+ cacheData?.hash || location.hash,
507
+ )
508
+ removeBrowserSession(state)
509
+
510
+ return res
511
+ } catch (error) {
512
+ return { data, error: new AuthError(error) }
513
+ }
514
+ }
515
+
516
+ /**
517
+ * https://supabase.com/docs/reference/javascript/auth-signinwithoauth
518
+ * 生成第三方平台授权 Uri (如微信二维码扫码授权网页)
519
+ * @param params
520
+ * @returns Promise<SignInOAuthRes>
521
+ */
522
+ async signInWithOAuth(params: SignInWithOAuthReq): Promise<SignInOAuthRes> {
523
+ try {
524
+ // 参数校验:provider必填
525
+ this.validateParams(params, {
526
+ provider: { required: true, message: 'Provider is required' },
527
+ })
528
+
529
+ const href = params.options?.redirectTo || location.href
530
+
531
+ const urlObject = new URL(href)
532
+
533
+ const provider_redirect_uri = urlObject.origin + urlObject.pathname
534
+
535
+ const state = params.options?.state || `prd-${params.provider}-${Math.random().toString(36)
536
+ .slice(2)}`
537
+
538
+ const { uri } = await this.genProviderRedirectUri({
539
+ provider_id: params.provider,
540
+ provider_redirect_uri,
541
+ state,
542
+ })
543
+
544
+ // 对 URL 进行解码
545
+ const decodedUri = decodeURIComponent(uri)
546
+
547
+ // 合并额外的查询参数
548
+ let finalUri = decodedUri
549
+
550
+ if (params.options?.queryParams) {
551
+ const url = new URL(decodedUri)
552
+ Object.entries(params.options.queryParams).forEach(([key, value]) => {
553
+ url.searchParams.set(key, value)
554
+ })
555
+ finalUri = url.toString()
556
+ }
557
+
558
+ saveToBrowserSession(state, {
559
+ provider: params.provider,
560
+ search: urlObject.search,
561
+ hash: urlObject.hash,
562
+ type: params.options?.type || OAUTH_TYPE.SIGN_IN,
563
+ })
564
+
565
+ if (isBrowser() && !params.options?.skipBrowserRedirect) {
566
+ window.location.assign(finalUri)
567
+ }
568
+
569
+ return { data: { url: finalUri, provider: params.provider }, error: null }
570
+ } catch (error) {
571
+ return { data: {}, error: new AuthError(error) }
572
+ }
573
+ }
574
+
575
+ // https://supabase.com/docs/reference/javascript/auth-signinwithsso
576
+ async signInWithSSO() {
577
+ //
578
+ }
579
+
580
+ // https://supabase.com/docs/reference/javascript/auth-signinwithweb3
581
+ async signInWithWeb3() {
582
+ //
583
+ }
584
+
585
+ // https://supabase.com/docs/reference/javascript/auth-getclaims
586
+ async getClaims(): Promise<GetClaimsRes> {
587
+ try {
588
+ const { accessToken } = await this.getAccessToken()
589
+ const parsedToken = weappJwtDecodeAll(accessToken)
590
+ return { data: parsedToken, error: null }
591
+ } catch (error) {
592
+ return { data: {}, error: new AuthError(error) }
593
+ }
594
+ }
595
+
596
+ /**
597
+ * https://supabase.com/docs/reference/javascript/auth-resetpasswordforemail
598
+ * 通过 email 或手机号重置密码
599
+ * const { data } = await app.auth.resetPasswordForEmail("xxx@xx.com");
600
+ * const { data } = await app.auth.resetPasswordForEmail("13800138000");
601
+
602
+ await data.updateUser(code, newPassWord);
603
+ *
604
+ * @param emailOrPhone 邮箱或手机号
605
+ * @returns Promise<ResetPasswordForEmailRes>
606
+ */
607
+ async resetPasswordForEmail(
608
+ emailOrPhone: string,
609
+ options?: { redirectTo?: string },
610
+ ): Promise<ResetPasswordForEmailRes> {
611
+ try {
612
+ // 参数校验:emailOrPhone必填
613
+ this.validateParams(
614
+ { emailOrPhone },
615
+ {
616
+ emailOrPhone: { required: true, message: 'Email or phone is required' },
617
+ },
618
+ )
619
+
620
+ const { redirectTo } = options || {}
621
+
622
+ // 判断是邮箱还是手机号
623
+ const isEmail = emailOrPhone.includes('@')
624
+ let verificationParams: { email?: string; phone_number?: string }
625
+
626
+ if (isEmail) {
627
+ verificationParams = { email: emailOrPhone }
628
+ } else {
629
+ // 正规化手机号
630
+ const formattedPhone = this.formatPhone(emailOrPhone)
631
+ verificationParams = { phone_number: formattedPhone }
632
+ }
633
+
634
+ // 第一步:发送验证码并存储 verificationInfo
635
+ const verificationInfo = await this.getVerification(verificationParams)
636
+
637
+ return {
638
+ data: {
639
+ // 第二步:等待用户输入验证码(通过 Promise 包装用户输入事件)
640
+ updateUser: async (attributes: UpdateUserAttributes): Promise<SignInRes> => {
641
+ this.validateParams(attributes, {
642
+ nonce: { required: true, message: 'Nonce is required' },
643
+ password: { required: true, message: 'Password is required' },
644
+ })
645
+ try {
646
+ // 第三步:待用户输入完验证码之后,验证验证码
647
+ const verificationTokenRes = await this.verify({
648
+ verification_id: verificationInfo.verification_id,
649
+ verification_code: attributes.nonce,
650
+ })
651
+
652
+ await this.oauthInstance.authApi.resetPassword({
653
+ email: isEmail ? emailOrPhone : undefined,
654
+ phone: !isEmail ? emailOrPhone : undefined,
655
+ new_password: attributes.password,
656
+ verification_token: verificationTokenRes.verification_token,
657
+ })
658
+
659
+ eventBus.fire(EVENTS.AUTH_STATE_CHANGED, { event: AUTH_STATE_CHANGED_TYPE.PASSWORD_RECOVERY })
660
+
661
+ const res = await this.signInWithPassword({
662
+ email: isEmail ? emailOrPhone : undefined,
663
+ phone: !isEmail ? emailOrPhone : undefined,
664
+ password: attributes.password,
665
+ })
666
+
667
+ if (redirectTo && isBrowser()) {
668
+ window.location.assign(redirectTo)
669
+ }
670
+
671
+ return res
672
+ } catch (error) {
673
+ return { data: {}, error: new AuthError(error) }
674
+ }
675
+ },
676
+ },
677
+ error: null,
678
+ }
679
+ } catch (error) {
680
+ return { data: {}, error: new AuthError(error) }
681
+ }
682
+ }
683
+
684
+ /**
685
+ * 通过旧密码重置密码
686
+ * @param new_password
687
+ * @param old_password
688
+ * @returns
689
+ */
690
+ async resetPasswordForOld(params: ResetPasswordForOldReq) {
691
+ try {
692
+ await this.oauthInstance.authApi.updatePasswordByOld({
693
+ old_password: params.old_password,
694
+ new_password: params.new_password,
695
+ })
696
+
697
+ const { data: { session } = {} } = await this.getSession()
698
+
699
+ return { data: { user: session.user, session }, error: null }
700
+ } catch (error) {
701
+ return { data: {}, error: new AuthError(error) }
702
+ }
703
+ }
704
+
705
+ /**
706
+ * https://supabase.com/docs/reference/javascript/auth-verifyotp
707
+ * Log in a user given a User supplied OTP and verificationId received through mobile or email.
708
+ * const verificationInfo = await app.auth.getVerification({
709
+ phone: "xxxxxx",
710
+ });
711
+
712
+ const data = await app.auth.verifyOtp({
713
+ type: "sms",
714
+ phone: "xxxxxx",
715
+ token: "xxxxxx",
716
+ verificationInfo,
717
+ })
718
+ * @param params
719
+ * @returns Promise<SignInRes>
720
+ */
721
+ async verifyOtp(params: VerifyOtpReq): Promise<SignInRes> {
722
+ try {
723
+ const { type } = params
724
+ // 参数校验:token和verificationInfo必填
725
+ this.validateParams(params, {
726
+ token: { required: true, message: 'Token is required' },
727
+ messageId: { required: true, message: 'messageId is required' },
728
+ })
729
+
730
+ if (['phone_change', 'email_change'].includes(type)) {
731
+ await this.verify({
732
+ verification_id: params.messageId,
733
+ verification_code: params.token,
734
+ })
735
+ } else {
736
+ await this.signInWithUsername({
737
+ verificationInfo: { verification_id: params.messageId, is_user: true },
738
+ verificationCode: params.token,
739
+ username: params.email || this.formatPhone(params.phone) || '',
740
+ loginType: params.email ? 'email' : 'phone',
741
+ })
742
+ }
743
+
744
+ const { data: { session } = {} } = await this.getSession()
745
+
746
+ return { data: { user: session.user, session }, error: null }
747
+ } catch (error) {
748
+ return { data: {}, error: new AuthError(error) }
749
+ }
750
+ }
751
+
752
+ /**
753
+ * https://supabase.com/docs/reference/javascript/auth-getSession
754
+ * Returns the session, refreshing it if necessary.
755
+ * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out.
756
+ * const { data } = await app.auth.getSession()
757
+ * @returns Promise<SignInRes>
758
+ */
759
+ async getSession(): Promise<SignInRes> {
760
+ try {
761
+ const credentials: Credentials = await this.oauthInstance.oauth2client.getCredentials()
762
+
763
+ if (!credentials || credentials.scope === 'accessKey') {
764
+ return { data: { session: null }, error: null }
765
+ }
766
+
767
+ const { data: { user } = {} } = await this.getUser()
768
+
769
+ return { data: { session: { ...credentials, user } }, error: null }
770
+ } catch (error) {
771
+ return { data: {}, error: new AuthError(error) }
772
+ }
773
+ }
774
+
775
+ /**
776
+ * https://supabase.com/docs/reference/javascript/auth-refreshsession
777
+ * 无论过期状态如何,都返回一个新的会话。接受一个可选的refresh_token。如果未传入当前会话,则refreshSession()将尝试从getSession()中检索它。如果当前会话的刷新令牌无效,则会抛出一个错误。
778
+ * const { data } = await app.auth.refreshSession()
779
+ * @param refresh_token
780
+ * @returns Promise<SignInRes>
781
+ */
782
+ async refreshSession(refresh_token?: string): Promise<SignInRes> {
783
+ try {
784
+ const credentials: Credentials = await this.oauthInstance.oauth2client.localCredentials.getCredentials()
785
+ credentials.refresh_token = refresh_token || credentials.refresh_token
786
+ const newTokens = await this.oauthInstance.oauth2client.refreshToken(credentials)
787
+ const { data: { user } = {} } = await this.getUser()
788
+
789
+ return { data: { user, session: { ...newTokens, user } }, error: null }
790
+ } catch (error) {
791
+ return { data: {}, error: new AuthError(error) }
792
+ }
793
+ }
794
+
795
+ /**
796
+ * https://supabase.com/docs/reference/javascript/auth-getuser
797
+ * 如果存在现有会话,则获取当前用户详细信息。此方法会向服务器发起网络请求,因此返回的值是真实的,可用于制定授权规则。
798
+ * const { data } = await app.auth.getUser()
799
+ * @returns Promise<GetUserRes>
800
+ */
801
+ async getUser(): Promise<GetUserRes> {
802
+ try {
803
+ const user = this.convertToUser(await this.getUserInfo())
804
+ return { data: { user }, error: null }
805
+ } catch (error) {
806
+ return { data: {}, error: new AuthError(error) }
807
+ }
808
+ }
809
+
810
+ /**
811
+ * 刷新用户信息
812
+ * @returns Promise<CommonRes>
813
+ */
814
+ async refreshUser(): Promise<CommonRes> {
815
+ try {
816
+ await this.currentUser.refresh()
817
+
818
+ const { data: { session } = {} } = await this.getSession()
819
+ return { data: { user: session.user, session }, error: null }
820
+ } catch (error) {
821
+ return { data: {}, error: new AuthError(error) }
822
+ }
823
+ }
824
+
825
+ /**
826
+ * https://supabase.com/docs/reference/javascript/auth-updateuser
827
+ * 更新用户信息
828
+ * - 不支持更新密码,更新密码请使用 resetPasswordForEmail 或 reauthenticate
829
+ * - 如果更新 email 或 phone,需要先发送验证码,然后调用返回的 verifyOtp 回调进行验证
830
+ *
831
+ * // 更新不需要验证的字段
832
+ * const { data } = await app.auth.updateUser({
833
+ username: "xxx",
834
+ description: "xxx",
835
+ avatar_url: "xxx",
836
+ nickname: "xxx",
837
+ gender: 'MALE'
838
+ })
839
+ *
840
+ * // 更新 email 或 phone(需要验证)
841
+ * const { data } = await app.auth.updateUser({
842
+ email: "new@example.com"
843
+ })
844
+ * // 调用 verifyOtp 回调验证
845
+ * await data.verifyOtp({ email: "new@example.com", token: "123456" })
846
+ *
847
+ * @param params
848
+ * @returns Promise<GetUserRes | UpdateUserWithVerificationRes>
849
+ */
850
+ async updateUser(params: UpdateUserReq): Promise<GetUserRes | UpdateUserWithVerificationRes> {
851
+ try {
852
+ // 参数校验:至少有一个更新字段被提供
853
+ const hasValue = Object.keys(params).some(key => params[key] !== undefined && params[key] !== null && params[key] !== '',)
854
+ if (!hasValue) {
855
+ throw new AuthError({ message: 'At least one field must be provided for update' })
856
+ }
857
+
858
+ const { email, phone, ...restParams } = params
859
+
860
+ // 检查是否需要更新 email 或 phone
861
+ const needsEmailVerification = email !== undefined
862
+ const needsPhoneVerification = phone !== undefined
863
+
864
+ let extraRes = {}
865
+
866
+ if (needsEmailVerification || needsPhoneVerification) {
867
+ // 需要发送验证码
868
+ let verificationParams: { email?: string; phone_number?: string }
869
+ let verificationType: 'email_change' | 'phone_change'
870
+
871
+ if (needsEmailVerification) {
872
+ verificationParams = { email: params.email }
873
+ verificationType = 'email_change'
874
+ } else {
875
+ // 正规化手机号
876
+ const formattedPhone = this.formatPhone(params.phone)
877
+ verificationParams = { phone_number: formattedPhone }
878
+ verificationType = 'phone_change'
879
+ }
880
+
881
+ // 发送验证码
882
+ const verificationInfo = await this.getVerification(verificationParams)
883
+
884
+ await this.updateUserBasicInfo(restParams)
885
+
886
+ extraRes = {
887
+ messageId: verificationInfo.verification_id,
888
+ verifyOtp: async (verifyParams: { email?: string; phone?: string; token: string }): Promise<GetUserRes> => {
889
+ try {
890
+ if (verifyParams.email && params.email === verifyParams.email) {
891
+ // 验证码验证
892
+ await this.verifyOtp({
893
+ type: 'email_change',
894
+ email: params.email,
895
+ token: verifyParams.token,
896
+ messageId: verificationInfo.verification_id,
897
+ })
898
+ await this.updateUserBasicInfo({ email: params.email })
899
+ } else if (verifyParams.phone && params.phone === verifyParams.phone) {
900
+ // 验证码验证
901
+ await this.verifyOtp({
902
+ type: 'phone_change',
903
+ phone: params.phone,
904
+ token: verifyParams.token,
905
+ messageId: verificationInfo.verification_id,
906
+ })
907
+ await this.updateUserBasicInfo({ phone: params.phone })
908
+ } else {
909
+ await this.verifyOtp({
910
+ type: verificationType,
911
+ email: needsEmailVerification ? params.email : undefined,
912
+ phone: !needsEmailVerification ? params.phone : undefined,
913
+ token: verifyParams.token,
914
+ messageId: verificationInfo.verification_id,
915
+ })
916
+ // 验证成功后更新用户信息
917
+ await this.updateUserBasicInfo(params)
918
+ }
919
+
920
+ const {
921
+ data: { user },
922
+ } = await this.getUser()
923
+ eventBus.fire(EVENTS.AUTH_STATE_CHANGED, { event: AUTH_STATE_CHANGED_TYPE.USER_UPDATED })
924
+
925
+ return { data: { user }, error: null }
926
+ } catch (error) {
927
+ return { data: {}, error: new AuthError(error) }
928
+ }
929
+ },
930
+ }
931
+ } else {
932
+ // 不需要验证,直接更新
933
+ await this.updateUserBasicInfo(params)
934
+ }
935
+ const {
936
+ data: { user },
937
+ } = await this.getUser()
938
+ eventBus.fire(EVENTS.AUTH_STATE_CHANGED, { event: AUTH_STATE_CHANGED_TYPE.USER_UPDATED })
939
+
940
+ return { data: { user, ...extraRes }, error: null }
941
+ } catch (error) {
942
+ return { data: {}, error: new AuthError(error) }
943
+ }
944
+ }
945
+
946
+ /**
947
+ * https://supabase.com/docs/reference/javascript/auth-getuseridentities
948
+ * 获取所有身份源
949
+ * const { data } = await app.auth.getUserIdentities()
950
+ * @returns Promise<GetUserIdentitiesRes>
951
+ */
952
+ async getUserIdentities(): Promise<GetUserIdentitiesRes> {
953
+ try {
954
+ const providers = await this.oauthInstance.authApi.getProviders()
955
+
956
+ return { data: { identities: providers?.data?.filter(v => !!v.bind) }, error: null }
957
+ } catch (error) {
958
+ return { data: {}, error: new AuthError(error) }
959
+ }
960
+ }
961
+
962
+ /**
963
+ * https://supabase.com/docs/reference/javascript/auth-linkidentity
964
+ * 绑定身份源到当前用户,如果已有用户绑定该身份源,会抛出错误
965
+ * const { data } = await app.auth.linkIdentity({
966
+ provider: 'string'
967
+ })
968
+ * @param params
969
+ * @returns Promise<LinkIdentityRes>
970
+ */
971
+ async linkIdentity(params: LinkIdentityReq): Promise<LinkIdentityRes> {
972
+ try {
973
+ // 参数校验:provider必填
974
+ this.validateParams(params, {
975
+ provider: { required: true, message: 'Provider is required' },
976
+ })
977
+
978
+ await this.signInWithOAuth({
979
+ provider: params.provider,
980
+ options: {
981
+ type: OAUTH_TYPE.BIND_IDENTITY,
982
+ },
983
+ })
984
+
985
+ return { data: { provider: params.provider }, error: null }
986
+ } catch (error) {
987
+ return { data: {}, error: new AuthError(error) }
988
+ }
989
+ }
990
+
991
+ /**
992
+ * https://supabase.com/docs/reference/javascript/auth-unlinkidentity
993
+ * 解绑身份源
994
+ * const { data } = await app.auth.unlinkIdentity({
995
+ provider: "xxx"
996
+ })
997
+ * @param params
998
+ * @returns Promise<CommonRes>
999
+ */
1000
+ async unlinkIdentity(params: UnlinkIdentityReq): Promise<CommonRes> {
1001
+ try {
1002
+ // 参数校验:provider必填
1003
+ this.validateParams(params, {
1004
+ provider: { required: true, message: 'Provider is required' },
1005
+ })
1006
+
1007
+ await this.oauthInstance.authApi.unbindProvider({ provider_id: params.provider })
1008
+
1009
+ return { data: {}, error: null }
1010
+ } catch (error) {
1011
+ return { data: {}, error: new AuthError(error) }
1012
+ }
1013
+ }
1014
+
1015
+ /**
1016
+ * https://supabase.com/docs/reference/javascript/auth-reauthentication
1017
+ * 重新认证。通过发送验证码来重新认证用户身份,支持更新密码
1018
+ * const { data } = await app.auth.reauthenticate()
1019
+
1020
+ await data.updateUser(code, newPassWord)
1021
+ *
1022
+ * @returns Promise<ReauthenticateRes>
1023
+ */
1024
+ async reauthenticate(): Promise<ReauthenticateRes> {
1025
+ try {
1026
+ const {
1027
+ data: { user },
1028
+ } = await this.getUser()
1029
+
1030
+ this.validateAtLeastOne(user, [['email', 'phone']], 'You must provide either an email or phone number')
1031
+ const userInfo = user.email ? { email: user.email } : { phone_number: this.formatPhone(user.phone) }
1032
+
1033
+ // 第一步:发送验证码并存储 verificationInfo
1034
+ const verificationInfo = await this.getVerification(userInfo)
1035
+
1036
+ return {
1037
+ data: {
1038
+ // 第二步:等待用户输入验证码(通过 Promise 包装用户输入事件)
1039
+ updateUser: async (attributes: UpdateUserAttributes): Promise<SignInRes> => {
1040
+ this.validateParams(attributes, {
1041
+ nonce: { required: true, message: 'Nonce is required' },
1042
+ })
1043
+ try {
1044
+ if (attributes.password) {
1045
+ // 第三步:待用户输入完验证码之后,验证验证码
1046
+ const verificationTokenRes = await this.verify({
1047
+ verification_id: verificationInfo.verification_id,
1048
+ verification_code: attributes.nonce,
1049
+ })
1050
+
1051
+ // 第四步:获取 sudo_token
1052
+ const sudoRes = await this.oauthInstance.authApi.sudo({
1053
+ verification_token: verificationTokenRes.verification_token,
1054
+ })
1055
+
1056
+ await this.oauthInstance.authApi.setPassword({
1057
+ new_password: attributes.password,
1058
+ sudo_token: sudoRes.sudo_token,
1059
+ })
1060
+ } else {
1061
+ await this.signInWithUsername({
1062
+ verificationInfo,
1063
+ verificationCode: attributes.nonce,
1064
+ ...userInfo,
1065
+ loginType: userInfo.email ? 'email' : 'phone',
1066
+ })
1067
+ }
1068
+
1069
+ const { data: { session } = {} } = await this.getSession()
1070
+
1071
+ return { data: { user: session.user, session }, error: null }
1072
+ } catch (error) {
1073
+ return { data: {}, error: new AuthError(error) }
1074
+ }
1075
+ },
1076
+ },
1077
+ error: null,
1078
+ }
1079
+ } catch (error) {
1080
+ return { data: {}, error: new AuthError(error) }
1081
+ }
1082
+ }
1083
+
1084
+ /**
1085
+ * https://supabase.com/docs/reference/javascript/auth-resend
1086
+ * 重新发送验证码
1087
+ * - 向用户重新发送邮箱、手机号注册或登录的验证码。
1088
+ * - 可以通过再次调用 signInWithOtp() 方法来重新发送验证码登录。
1089
+ * - 可以通过再次调用 signUp() 方法来重新发送验证码注册。
1090
+ * - 此方法仅在调用 signInWithOtp() 或 signUp() 后,重新发送验证码,收到验证码后再继续调用 signInWithOtp() 或 signUp() 的callback参数,将messageId传入callback。
1091
+ * const result = await app.auth.signInWithOtp({ phone: "xxx" });
1092
+
1093
+ let signResolve = result.data.verify
1094
+
1095
+ const { data } = await app.auth.resend({
1096
+ type: "signup",
1097
+ phone: "xxx",
1098
+ })
1099
+
1100
+ const res = await signResolve(code, data.messageId);
1101
+ * @param params
1102
+ * @returns Promise<ResendRes>
1103
+ */
1104
+ async resend(params: ResendReq): Promise<ResendRes> {
1105
+ try {
1106
+ // 参数校验:email或phone必填其一
1107
+ this.validateAtLeastOne(params, [['email'], ['phone']], 'You must provide either an email or phone number')
1108
+
1109
+ const target = params.type === 'signup' ? 'ANY' : 'USER'
1110
+ const data: { email?: string; phone_number?: string; target: 'USER' | 'ANY' } = { target }
1111
+ if ('email' in params) {
1112
+ data.email = params.email
1113
+ }
1114
+
1115
+ if ('phone' in params) {
1116
+ data.phone_number = this.formatPhone(params.phone)
1117
+ }
1118
+
1119
+ // 重新发送验证码
1120
+ const { verification_id: verificationId } = await this.oauthInstance.authApi.getVerification(data)
1121
+
1122
+ return {
1123
+ data: { messageId: verificationId },
1124
+ error: null,
1125
+ }
1126
+ } catch (error: any) {
1127
+ return {
1128
+ data: {},
1129
+ error: new AuthError(error),
1130
+ }
1131
+ }
1132
+ }
1133
+
1134
+ /**
1135
+ * https://supabase.com/docs/reference/javascript/auth-setsession
1136
+ * 使用access_token和refresh_token来设置会话
1137
+ * 如果成功,则会触发一个SIGNED_IN事件
1138
+ * const { data, error } = await app.auth.setSession({
1139
+ access_token,
1140
+ refresh_token
1141
+ })
1142
+ * @param params
1143
+ * @returns Promise<SignInRes>
1144
+ */
1145
+ async setSession(params: SetSessionReq): Promise<SignInRes> {
1146
+ try {
1147
+ this.validateParams(params, {
1148
+ access_token: { required: true, message: 'Access token is required' },
1149
+ refresh_token: { required: true, message: 'Refresh token is required' },
1150
+ })
1151
+
1152
+ await this.oauthInstance.oauth2client.refreshToken(params, { throwOnError: true })
1153
+
1154
+ const { data: { session } = {} } = await this.getSession()
1155
+
1156
+ eventBus.fire(EVENTS.AUTH_STATE_CHANGED, { event: AUTH_STATE_CHANGED_TYPE.SIGNED_IN })
1157
+
1158
+ return { data: { user: session.user, session }, error: null }
1159
+ } catch (error) {
1160
+ return { data: {}, error: new AuthError(error) }
1161
+ }
1162
+ }
1163
+
1164
+ // https://supabase.com/docs/reference/javascript/auth-exchangecodeforsession
1165
+ async exchangeCodeForSession() {
1166
+ //
1167
+ }
1168
+
1169
+ /**
1170
+ * 删除当前用户
1171
+ * @param params
1172
+ * @returns
1173
+ */
1174
+ async deleteUser(params: DeleteMeReq): Promise<CommonRes> {
1175
+ try {
1176
+ this.validateParams(params, {
1177
+ password: { required: true, message: 'Password is required' },
1178
+ })
1179
+
1180
+ const { sudo_token } = await this.oauthInstance.authApi.sudo(params)
1181
+
1182
+ await this.oauthInstance.authApi.deleteMe({ sudo_token })
1183
+
1184
+ return { data: {}, error: null }
1185
+ } catch (error) {
1186
+ return { data: {}, error: new AuthError(error) }
1187
+ }
1188
+ }
1189
+
1190
+ /**
1191
+ * 跳转系统默认登录页
1192
+ * @returns {Promise<authModels.ToDefaultLoginPage>}
1193
+ * @memberof Auth
1194
+ */
1195
+ async toDefaultLoginPage(params: authModels.ToDefaultLoginPage = {}): Promise<CommonRes> {
1196
+ try {
1197
+ const configVersion = params.config_version || 'env'
1198
+ const query = Object.keys(params.query || {})
1199
+ .map(key => `${key}=${params.query[key]}`)
1200
+ .join('&')
1201
+
1202
+ if (adapterForWxMp.isMatch()) {
1203
+ wx.navigateTo({ url: `/packages/$wd_system/pages/login/index${query ? `?${query}` : ''}` })
1204
+ } else {
1205
+ const redirectUri = params.redirect_uri || window.location.href
1206
+ const urlObj = new URL(redirectUri)
1207
+ const loginPage = `${urlObj.origin}/__auth/?app_id=${params.app_id || ''}&env_id=${this.config.env}&client_id=${
1208
+ this.config.clientId || this.config.env
1209
+ }&config_version=${configVersion}&redirect_uri=${encodeURIComponent(redirectUri)}${query ? `&${query}` : ''}`
1210
+ window.location.href = loginPage
1211
+ }
1212
+ return { data: {}, error: null }
1213
+ } catch (error) {
1214
+ return { data: {}, error: new AuthError(error) }
1215
+ }
1216
+ }
1217
+
1218
+ /**
1219
+ * 自定义登录
1220
+ * @param getTickFn () => Promise<string>, 获取自定义登录 ticket 的函数
1221
+ * @returns
1222
+ */
1223
+ async signInWithCustomTicket(getTickFn?: authModels.GetCustomSignTicketFn): Promise<SignInRes> {
1224
+ if (getTickFn) {
1225
+ this.setCustomSignFunc(getTickFn)
1226
+ }
1227
+
1228
+ try {
1229
+ await this.oauthInstance.authApi.signInWithCustomTicket()
1230
+ const loginState = await this.createLoginState()
1231
+
1232
+ const { data: { session } = {} } = await this.getSession()
1233
+
1234
+ // loginState返回是为了兼容v2版本
1235
+ return { ...(loginState as any), data: { user: session.user, session }, error: null }
1236
+ } catch (error) {
1237
+ return { data: {}, error: new AuthError(error) }
1238
+ }
1239
+ }
1240
+
1241
+ /**
1242
+ * 小程序openId静默登录
1243
+ * @param params
1244
+ * @returns Promise<SignInRes>
1245
+ */
1246
+ async signInWithOpenId({ useWxCloud = true } = {}): Promise<SignInRes> {
1247
+ if (!adapterForWxMp.isMatch()) {
1248
+ throw Error('wx api undefined')
1249
+ }
1250
+ const wxInfo = wx.getAccountInfoSync().miniProgram
1251
+
1252
+ const mainFunc = async (code) => {
1253
+ let result: authModels.GrantProviderTokenResponse | undefined = undefined
1254
+ let credentials: Credentials | undefined = undefined
1255
+
1256
+ try {
1257
+ result = await this.oauthInstance.authApi.grantProviderToken(
1258
+ {
1259
+ provider_id: wxInfo?.appId,
1260
+ provider_code: code,
1261
+ provider_params: {
1262
+ provider_code_type: 'open_id',
1263
+ appid: wxInfo?.appId,
1264
+ },
1265
+ },
1266
+ useWxCloud,
1267
+ )
1268
+
1269
+ if ((result as any)?.error_code || !result.provider_token) {
1270
+ throw result
1271
+ }
1272
+
1273
+ credentials = await this.oauthInstance.authApi.signInWithProvider(
1274
+ { provider_token: result.provider_token },
1275
+ useWxCloud,
1276
+ )
1277
+
1278
+ if ((credentials as any)?.error_code) {
1279
+ throw credentials
1280
+ }
1281
+ } catch (error) {
1282
+ throw error
1283
+ }
1284
+ await this.oauthInstance.oauth2client.setCredentials(credentials as Credentials)
1285
+ }
1286
+
1287
+ try {
1288
+ await new Promise((resolve, reject) => {
1289
+ wx.login({
1290
+ success: async (res: { code: string }) => {
1291
+ try {
1292
+ await mainFunc(res.code)
1293
+ resolve(true)
1294
+ } catch (error) {
1295
+ reject(error)
1296
+ }
1297
+ },
1298
+ fail: (res: any) => {
1299
+ const error = new Error(res?.errMsg)
1300
+ ;(error as any).code = res?.errno
1301
+ reject(error)
1302
+ },
1303
+ })
1304
+ })
1305
+
1306
+ const loginState = await this.createLoginState()
1307
+
1308
+ const { data: { session } = {} } = await this.getSession()
1309
+
1310
+ // loginState返回是为了兼容v2版本
1311
+ return { ...(loginState as any), data: { user: session.user, session }, error: null }
1312
+ } catch (error) {
1313
+ return { data: {}, error: new AuthError(error) }
1314
+ }
1315
+ }
1316
+
1317
+ /**
1318
+ * 小程序手机号授权登录,目前只支持全托管手机号授权登录
1319
+ * @param params
1320
+ * @returns Promise<SignInRes>
1321
+ */
1322
+ async signInWithPhoneAuth({ phoneCode = '' }): Promise<SignInRes> {
1323
+ if (!adapterForWxMp.isMatch()) {
1324
+ return { data: {}, error: new AuthError({ message: 'wx api undefined' }) }
1325
+ }
1326
+ const wxInfo = wx.getAccountInfoSync().miniProgram
1327
+ const providerInfo = {
1328
+ provider_params: { provider_code_type: 'phone' },
1329
+ provider_id: wxInfo.appId,
1330
+ }
1331
+
1332
+ const { code } = await wx.login()
1333
+ ;(providerInfo as any).provider_code = code
1334
+
1335
+ try {
1336
+ let providerToken = await this.oauthInstance.authApi.grantProviderToken(providerInfo)
1337
+ if (providerToken.error_code) {
1338
+ throw providerToken
1339
+ }
1340
+
1341
+ providerToken = await this.oauthInstance.authApi.patchProviderToken({
1342
+ provider_token: providerToken.provider_token,
1343
+ provider_id: wxInfo.appId,
1344
+ provider_params: {
1345
+ code: phoneCode,
1346
+ provider_code_type: 'phone',
1347
+ },
1348
+ })
1349
+ if (providerToken.error_code) {
1350
+ throw providerToken
1351
+ }
1352
+
1353
+ const signInRes = await this.oauthInstance.authApi.signInWithProvider({
1354
+ provider_token: providerToken.provider_token,
1355
+ })
1356
+
1357
+ if ((signInRes as any)?.error_code) {
1358
+ throw signInRes
1359
+ }
1360
+ } catch (error) {
1361
+ return { data: {}, error: new AuthError(error) }
1362
+ }
1363
+
1364
+ const loginState = await this.createLoginState()
1365
+
1366
+ const { data: { session } = {} } = await this.getSession()
1367
+
1368
+ // loginState返回是为了兼容v2版本
1369
+ return { ...(loginState as any), data: { user: session.user, session }, error: null }
1370
+ }
1371
+
1372
+ private formatPhone(phone: string) {
1373
+ if (!/\s+/.test(phone) && /^\+\d{1,3}\d+/.test(phone)) {
1374
+ return phone.replace(/^(\+\d{1,2})(\d+)$/, '$1 $2')
1375
+ }
1376
+ return /^\+\d{1,3}\s+/.test(phone) ? phone : `+86 ${phone}`
1377
+ }
1378
+
1379
+ private notifyListeners(event, session, info): OnAuthStateChangeCallback {
1380
+ this.listeners.forEach((callbacks) => {
1381
+ callbacks.forEach((callback) => {
1382
+ try {
1383
+ callback(event, session, info)
1384
+ } catch (error) {
1385
+ console.error('Error in auth state change callback:', error)
1386
+ }
1387
+ })
1388
+ })
1389
+ return
1390
+ }
1391
+
1392
+ private async init(): Promise<{ error: Error | null }> {
1393
+ try {
1394
+ const credentials: Credentials = await this.oauthInstance.oauth2client.localCredentials.getCredentials()
1395
+ if (credentials) {
1396
+ eventBus.fire(EVENTS.AUTH_STATE_CHANGED, { event: AUTH_STATE_CHANGED_TYPE.INITIAL_SESSION })
1397
+ }
1398
+ } catch (error) {
1399
+ // Ignore errors when checking for existing credentials
1400
+ }
1401
+
1402
+ return { error: null }
1403
+ }
1404
+
1405
+ private setupListeners() {
1406
+ eventBus.on(EVENTS.AUTH_STATE_CHANGED, async (params) => {
1407
+ const event = params?.data?.event
1408
+ const info = params?.data?.info
1409
+ const {
1410
+ data: { session },
1411
+ } = await this.getSession()
1412
+
1413
+ this.notifyListeners(event, session, info)
1414
+ })
1415
+ }
1416
+
1417
+ private convertToUser(userInfo: authModels.UserInfo & Partial<User>) {
1418
+ if (!userInfo) return null
1419
+
1420
+ // 优先使用 userInfo 中的数据(V3 API)
1421
+ const email = userInfo?.email || userInfo?.username
1422
+ const phone = userInfo?.phone_number
1423
+ const userId = userInfo?.sub || userInfo?.uid || ''
1424
+
1425
+ return {
1426
+ id: userId,
1427
+ aud: 'authenticated',
1428
+ role: userInfo.groups,
1429
+ email: email || '',
1430
+ email_confirmed_at: userInfo?.email_verified ? userInfo.created_at : userInfo.created_at,
1431
+ phone,
1432
+ phone_confirmed_at: phone ? userInfo.created_at : undefined,
1433
+ confirmed_at: userInfo.created_at,
1434
+ last_sign_in_at: userInfo.last_sign_in_at,
1435
+ app_metadata: {
1436
+ provider: userInfo.loginType?.toLowerCase() || 'cloudbase',
1437
+ providers: [userInfo.loginType?.toLowerCase() || 'cloudbase'],
1438
+ },
1439
+ user_metadata: {
1440
+ // V3 API 用户信息
1441
+ name: userInfo?.name,
1442
+ picture: userInfo?.picture,
1443
+ username: userInfo?.username, // 用户名称,长度 5-24 位,支持字符中英文、数字、特殊字符(仅支持_-),不支持中文
1444
+ gender: userInfo?.gender,
1445
+ locale: userInfo?.locale,
1446
+ // V2 API 兼容(使用 any 避免类型错误)
1447
+ uid: userInfo.uid,
1448
+ nickName: userInfo.nickName,
1449
+ avatarUrl: userInfo.avatarUrl,
1450
+ location: userInfo.location,
1451
+ hasPassword: userInfo.hasPassword,
1452
+ },
1453
+ identities:
1454
+ userInfo?.providers?.map(p => ({
1455
+ id: p.id || '',
1456
+ identity_id: p.id || '',
1457
+ user_id: userId,
1458
+ identity_data: {
1459
+ provider_id: p.id,
1460
+ provider_user_id: p.provider_user_id,
1461
+ name: p.name,
1462
+ },
1463
+ provider: p.id || 'cloudbase',
1464
+ created_at: userInfo.created_at,
1465
+ updated_at: userInfo.updated_at,
1466
+ last_sign_in_at: userInfo.last_sign_in_at,
1467
+ })) || [],
1468
+ created_at: userInfo.created_at,
1469
+ updated_at: userInfo.updated_at,
1470
+ is_anonymous: userInfo.name === 'anonymous',
1471
+ }
1472
+ }
1473
+
1474
+ /**
1475
+ * 参数校验辅助方法
1476
+ */
1477
+ private validateParams(params: any, rules: { [key: string]: { required?: boolean; message: string } }): void {
1478
+ for (const [key, rule] of Object.entries(rules)) {
1479
+ if (rule.required && (params?.[key] === undefined || params?.[key] === null || params?.[key] === '')) {
1480
+ throw new AuthError({ message: rule.message })
1481
+ }
1482
+ }
1483
+ }
1484
+
1485
+ /**
1486
+ * 校验必填参数组(至少有一个参数必须有值)
1487
+ */
1488
+ private validateAtLeastOne(params: any, fieldGroups: string[][], message: string): void {
1489
+ const hasValue = fieldGroups.some(group => group.some(field => params?.[field] !== undefined && params?.[field] !== null && params?.[field] !== ''),)
1490
+
1491
+ if (!hasValue) {
1492
+ throw new AuthError({ message })
1493
+ }
1494
+ }
1495
+ }