@cloudbase/auth 1.6.1 → 2.0.0-alpha.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.
Files changed (46) hide show
  1. package/dist/cjs/index.d.ts +50 -96
  2. package/dist/cjs/index.js +411 -679
  3. package/dist/esm/index.d.ts +50 -96
  4. package/dist/esm/index.js +412 -676
  5. package/package.json +52 -54
  6. package/src/index.ts +413 -650
  7. package/dist/cjs/constants.d.ts +0 -11
  8. package/dist/cjs/constants.js +0 -16
  9. package/dist/cjs/providers/anonymousAuthProvider.d.ts +0 -15
  10. package/dist/cjs/providers/anonymousAuthProvider.js +0 -255
  11. package/dist/cjs/providers/base.d.ts +0 -20
  12. package/dist/cjs/providers/base.js +0 -158
  13. package/dist/cjs/providers/customAuthProvider.d.ts +0 -5
  14. package/dist/cjs/providers/customAuthProvider.js +0 -149
  15. package/dist/cjs/providers/emailAuthProvider.d.ts +0 -9
  16. package/dist/cjs/providers/emailAuthProvider.js +0 -248
  17. package/dist/cjs/providers/phoneAuthProvider.d.ts +0 -17
  18. package/dist/cjs/providers/phoneAuthProvider.js +0 -217
  19. package/dist/cjs/providers/usernameAuthProvider.d.ts +0 -5
  20. package/dist/cjs/providers/usernameAuthProvider.js +0 -168
  21. package/dist/cjs/providers/weixinAuthProvider.d.ts +0 -28
  22. package/dist/cjs/providers/weixinAuthProvider.js +0 -294
  23. package/dist/esm/constants.d.ts +0 -11
  24. package/dist/esm/constants.js +0 -13
  25. package/dist/esm/providers/anonymousAuthProvider.d.ts +0 -15
  26. package/dist/esm/providers/anonymousAuthProvider.js +0 -252
  27. package/dist/esm/providers/base.d.ts +0 -20
  28. package/dist/esm/providers/base.js +0 -155
  29. package/dist/esm/providers/customAuthProvider.d.ts +0 -5
  30. package/dist/esm/providers/customAuthProvider.js +0 -146
  31. package/dist/esm/providers/emailAuthProvider.d.ts +0 -9
  32. package/dist/esm/providers/emailAuthProvider.js +0 -245
  33. package/dist/esm/providers/phoneAuthProvider.d.ts +0 -17
  34. package/dist/esm/providers/phoneAuthProvider.js +0 -214
  35. package/dist/esm/providers/usernameAuthProvider.d.ts +0 -5
  36. package/dist/esm/providers/usernameAuthProvider.js +0 -165
  37. package/dist/esm/providers/weixinAuthProvider.d.ts +0 -28
  38. package/dist/esm/providers/weixinAuthProvider.js +0 -291
  39. package/src/constants.ts +0 -11
  40. package/src/providers/anonymousAuthProvider.ts +0 -125
  41. package/src/providers/base.ts +0 -66
  42. package/src/providers/customAuthProvider.ts +0 -68
  43. package/src/providers/emailAuthProvider.ts +0 -139
  44. package/src/providers/phoneAuthProvider.ts +0 -130
  45. package/src/providers/usernameAuthProvider.ts +0 -76
  46. package/src/providers/weixinAuthProvider.ts +0 -193
package/src/index.ts CHANGED
@@ -1,76 +1,79 @@
1
1
  import { ICloudbase } from '@cloudbase/types';
2
- import { events, adapters, utils, constants, helpers } from '@cloudbase/utilities';
2
+ import { utils, constants, helpers, events } from '@cloudbase/utilities';
3
3
  import { ICloudbaseCache } from '@cloudbase/types/cache';
4
4
  import { ICloudbaseRequest } from '@cloudbase/types/request';
5
- import { ICloudbaseAuthConfig, ICredential, IUser, IUserInfo, IAuthProvider, ILoginState } from '@cloudbase/types/auth';
5
+ import { ICloudbaseAuthConfig, IUser, IUserInfo, ILoginState } from '@cloudbase/types/auth';
6
6
  import { ICloudbaseComponent } from '@cloudbase/types/component';
7
- import { WeixinAuthProvider } from './providers/weixinAuthProvider';
8
- import { AnonymousAuthProvider } from './providers/anonymousAuthProvider';
9
- import { CustomAuthProvider } from './providers/customAuthProvider';
10
- import { LOGINTYPE } from './constants';
11
- import { AuthProvider } from './providers/base';
12
- import { EmailAuthProvider } from './providers/emailAuthProvider';
13
- import { UsernameAuthProvider } from './providers/usernameAuthProvider';
14
- import { PhoneAuthProvider, SIGN_METHOD } from './providers/phoneAuthProvider'
7
+
8
+ import { authModels, CloudbaseOAuth } from '@cloudbase/oauth'
15
9
 
16
10
  declare const cloudbase: ICloudbase;
17
11
 
18
- const { CloudbaseEventEmitter } = events;
19
- const { RUNTIME } = adapters;
20
- const { printWarn, throwError, transformPhone } = utils;
12
+ const { printWarn, throwError } = utils;
21
13
  const { ERRORS, COMMUNITY_SITE_URL } = constants;
22
14
  const { catchErrorsDecorator } = helpers;
15
+ const { CloudbaseEventEmitter } = events;
23
16
 
24
17
  const COMPONENT_NAME = 'auth';
25
18
 
19
+ const EVENTS = {
20
+ // 登录态改变后触发
21
+ LOGIN_STATE_CHANGED: 'loginStateChanged',
22
+ };
23
+
26
24
  interface UserInfo {
27
- openid: string;
28
- nickname?: string;
29
- sex?: number;
30
- province?: string;
31
- city?: string;
32
- country?: string;
33
- headimgurl?: string;
34
- privilege?: [string];
35
- unionid?: string;
25
+ uid?: string;
26
+ gender?: string;
27
+ avatarUrl?: string;
28
+ picture?: string;
29
+ email?: string;
30
+ email_verified?: boolean;
31
+ phone_number?: string;
32
+ username?: string;
33
+ name?: string;
34
+ birthdate?: string;
35
+ zoneinfo?: string;
36
+ locale?: string;
37
+ sub?: string;
38
+ created_from?: string;
36
39
  }
37
40
 
38
41
  const eventBus = new CloudbaseEventEmitter();
39
42
 
40
43
  interface IUserOptions {
41
44
  cache: ICloudbaseCache;
42
- request: ICloudbaseRequest;
45
+ // request: ICloudbaseRequest;
46
+ oauthInstance: CloudbaseOAuth
43
47
  }
44
48
 
45
49
  class User implements IUser {
46
- public uid: string;
47
- public loginType: string;
48
- public openid: string;
49
- public wxOpenId: string;
50
- public wxPublicId: string;
51
- public unionId: string;
52
- public qqMiniOpenId: string;
53
- public customUserId: string;
54
- public nickName: string;
55
- public gender: string;
56
- public avatarUrl: string;
57
- public email: string;
58
- public hasPassword: boolean;
59
- public phone?: string;
50
+ public uid?: string;
51
+ public gender?: string;
52
+ public avatarUrl?: string;
53
+ public picture?: string;
54
+ public email?: string;
55
+ public email_verified?: boolean;
56
+ public phone_number?: string;
60
57
  public username?: string;
61
- public location?: {
62
- country?: string;
63
- province?: string;
64
- city?: string;
65
- };
58
+ public name?: string;
59
+ public providers?: {
60
+ id?: string;
61
+ provider_user_id?: string;
62
+ name?: string;
63
+ }[]
64
+ public birthdate?: string;
65
+ public zoneinfo?: string;
66
+ public locale?: string;
67
+ public sub?: string;
68
+ public created_from?: string;
66
69
 
67
70
  private _cache: ICloudbaseCache;
68
- private _request: ICloudbaseRequest;
71
+ private _oauthInstance: CloudbaseOAuth // CloudbaseOAuth 类型
69
72
 
70
73
  constructor(options: IUserOptions) {
71
- const { cache, request } = options;
74
+ const { cache, oauthInstance } = options;
72
75
  this._cache = cache;
73
- this._request = request;
76
+ this._oauthInstance = oauthInstance
74
77
 
75
78
  this._setUserInfo();
76
79
  }
@@ -78,149 +81,44 @@ class User implements IUser {
78
81
  * 获取本地用户信息-同步
79
82
  */
80
83
  public async checkLocalInfo() {
81
- this.uid = this._getLocalUserInfo('uid');
82
- this.loginType = this._getLocalUserInfo('loginType');
83
- this.openid = this._getLocalUserInfo('wxOpenId');
84
- this.wxOpenId = this._getLocalUserInfo('wxOpenId');
85
- this.wxPublicId = this._getLocalUserInfo('wxPublicId');
86
- this.unionId = this._getLocalUserInfo('wxUnionId');
87
- this.qqMiniOpenId = this._getLocalUserInfo('qqMiniOpenId');
88
- this.customUserId = this._getLocalUserInfo('customUserId');
89
- this.nickName = this._getLocalUserInfo('nickName');
90
- this.gender = this._getLocalUserInfo('gender');
91
- this.avatarUrl = this._getLocalUserInfo('avatarUrl');
92
- this.email = this._getLocalUserInfo('email');
93
- this.hasPassword = Boolean(this._getLocalUserInfo('hasPassword'));
94
- this.phone = this._getLocalUserInfo('phone')
95
- this.username = this._getLocalUserInfo('username')
96
- this.location = {
97
- country: this._getLocalUserInfo('country'),
98
- province: this._getLocalUserInfo('province'),
99
- city: this._getLocalUserInfo('city')
100
- };
84
+ this.uid = this._getLocalUserInfo('uid') as string;
85
+ this.gender = this._getLocalUserInfo('gender') as string;
86
+ this.picture = this._getLocalUserInfo('picture') as string;
87
+ this.avatarUrl = this._getLocalUserInfo('avatarUrl') as string;
88
+ this.email = this._getLocalUserInfo('email') as string;
89
+ this.email_verified = this._getLocalUserInfo('email_verified') as boolean;
90
+ this.phone_number = this._getLocalUserInfo('phone_number') as string
91
+ this.username = this._getLocalUserInfo('username') as string
92
+ this.name = this._getLocalUserInfo('name') as string
93
+ this.birthdate = this._getLocalUserInfo('birthdate') as string
94
+ this.zoneinfo = this._getLocalUserInfo('zoneinfo') as string
95
+ this.locale = this._getLocalUserInfo('locale') as string
96
+ this.sub = this._getLocalUserInfo('sub') as string
97
+ this.created_from = this._getLocalUserInfo('created_from') as string
98
+ this.providers = this._getLocalUserInfo('providers') as any
101
99
  }
102
100
  /**
103
101
  * 获取本地用户信息-异步
104
102
  */
105
103
  public async checkLocalInfoAsync() {
106
104
  this.uid = await this._getLocalUserInfoAsync('uid');
107
- this.loginType = await this._getLocalUserInfoAsync('loginType');
108
- this.openid = await this._getLocalUserInfoAsync('wxOpenId');
109
- this.wxOpenId = await this._getLocalUserInfoAsync('wxOpenId');
110
- this.wxPublicId = await this._getLocalUserInfoAsync('wxPublicId');
111
- this.unionId = await this._getLocalUserInfoAsync('wxUnionId');
112
- this.qqMiniOpenId = await this._getLocalUserInfoAsync('qqMiniOpenId');
113
- this.customUserId = await this._getLocalUserInfoAsync('customUserId');
114
- this.nickName = await this._getLocalUserInfoAsync('nickName');
115
105
  this.gender = await this._getLocalUserInfoAsync('gender');
106
+ this.picture = this._getLocalUserInfo('picture') as string;
116
107
  this.avatarUrl = await this._getLocalUserInfoAsync('avatarUrl');
117
108
  this.email = await this._getLocalUserInfoAsync('email');
118
- this.hasPassword = Boolean(await this._getLocalUserInfoAsync('hasPassword'));
119
- this.phone = await this._getLocalUserInfoAsync('phone')
109
+ this.email_verified = this._getLocalUserInfo('email_verified') as boolean;
110
+ this.phone_number = this._getLocalUserInfo('phone_number') as string
120
111
  this.username = await this._getLocalUserInfoAsync('username')
121
- this.location = {
122
- country: await this._getLocalUserInfoAsync('country'),
123
- province: await this._getLocalUserInfoAsync('province'),
124
- city: await this._getLocalUserInfoAsync('city')
125
- };
112
+ this.name = this._getLocalUserInfo('name') as string
113
+ this.birthdate = this._getLocalUserInfo('birthdate') as string
114
+ this.zoneinfo = this._getLocalUserInfo('zoneinfo') as string
115
+ this.locale = this._getLocalUserInfo('locale') as string
116
+ this.sub = this._getLocalUserInfo('sub') as string
117
+ this.created_from = this._getLocalUserInfo('created_from') as string
118
+ this.providers = this._getLocalUserInfo('providers') as any
126
119
  }
127
120
 
128
- /**
129
- * 将当前账户与自定义登录 Ticket 进行绑定,绑定之后便可以通过自定义登录登录当前云开发账户。
130
- * @param {string} ticket 自定义登录ticket
131
- */
132
- @catchErrorsDecorator({
133
- title: '绑定自定义登录失败',
134
- messages: [
135
- '请确认以下各项:',
136
- ' 1 - 调用 User.linkWithTicket() 的语法或参数是否正确',
137
- ' 2 - 此账户是否已经绑定自定义登录',
138
- ' 3 - ticket 参数是否归属当前环境',
139
- ' 4 - 创建 ticket 的自定义登录私钥是否过期',
140
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
141
- ]
142
- })
143
- public linkWithTicket(ticket: string): Promise<void> {
144
- if (typeof ticket !== 'string') {
145
- throw new Error('ticket must be string');
146
- }
147
- return this._request.send('auth.linkWithTicket', { ticket });
148
- }
149
- /**
150
- * 将当前账户与第三方鉴权提供方,以重定向的形式,进行绑定,绑定之后便可以通过第三方鉴权提供方登录当前的云开发账户。
151
- * @param provider 特定登录方式的provider,必须具备signInWithRedirect方法
152
- */
153
- @catchErrorsDecorator({
154
- title: '绑定第三方登录方式失败',
155
- messages: [
156
- '请确认以下各项:',
157
- ' 1 - 调用 User.linkWithRedirect() 的语法或参数是否正确',
158
- ' 2 - 此账户是否已经绑定此第三方',
159
- ' 3 - 此第三方是否已经授权',
160
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
161
- ]
162
- })
163
- public linkWithRedirect(provider: IAuthProvider): void {
164
- provider.signInWithRedirect();
165
- }
166
- /**
167
- * 获取当前账户的微信 UnionID 绑定的云开发账户列表。如果当前账户不存在 UnionID,会返回错误。
168
- */
169
- @catchErrorsDecorator({
170
- title: '获取账户列表失败',
171
- messages: [
172
- '请确认以下各项:',
173
- ' 1 - 调用 User.getLinkedUidList() 的语法或参数是否正确',
174
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
175
- ]
176
- })
177
- public async getLinkedUidList() {
178
- const { data } = await this._request.send('auth.getLinkedUidList', {});
179
- let hasPrimaryUid = false;
180
- const users = data.users as IUserInfo[];
181
- for (const user of users) {
182
- if (user.wxOpenId && user.wxPublicId) {
183
- hasPrimaryUid = true;
184
- break;
185
- }
186
- }
187
- return {
188
- users,
189
- hasPrimaryUid
190
- };
191
- }
192
- /**
193
- * 设置微信主账号,通常搭配和 User.getLinkedUidList() 使用,用于在同个微信 UnionID 对应的多个云开发账号中,设置其中一个为主账号
194
- * 设置之后,通过 UnionID 登录便会登录至主账号之上。
195
- * @param uid
196
- */
197
- @catchErrorsDecorator({
198
- title: '设置微信主账号失败',
199
- messages: [
200
- '请确认以下各项:',
201
- ' 1 - 调用 User.setPrimaryUid() 的语法或参数是否正确',
202
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
203
- ]
204
- })
205
- public setPrimaryUid(uid: string) {
206
- return this._request.send('auth.setPrimaryUid', { uid });
207
- }
208
- /**
209
- * 解绑某个登录方式
210
- * @param loginType
211
- */
212
- @catchErrorsDecorator({
213
- title: '接触绑定失败',
214
- messages: [
215
- '请确认以下各项:',
216
- ' 1 - 调用 User.unlink() 的语法或参数是否正确',
217
- ' 2 - 当前账户是否已经与此登录方式解绑',
218
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
219
- ]
220
- })
221
- public unlink(loginType: 'CUSTOM' | 'WECHAT-OPEN' | 'WECHAT-PUBLIC' | 'WECHAT-UNION' | 'PHONE') {
222
- return this._request.send('auth.unlink', { platform: loginType });
223
- }
121
+
224
122
  /**
225
123
  * 更新用户信息
226
124
  * @param userInfo
@@ -235,8 +133,9 @@ class User implements IUser {
235
133
  ]
236
134
  })
237
135
  public async update(userInfo: IUserInfo): Promise<void> {
238
- const { nickName, gender, avatarUrl, province, country, city } = userInfo;
239
- const { data: newUserInfo } = await this._request.send('auth.updateUserInfo', { nickName, gender, avatarUrl, province, country, city });
136
+ const { name, gender, avatarUrl, province, country, city } = userInfo;
137
+ const newUserInfo = await this._oauthInstance.authApi.setUserProfile({ name, gender, avatarUrl, province, country, city })
138
+
240
139
  this._setLocalUserInfo(newUserInfo);
241
140
  }
242
141
  /**
@@ -254,30 +153,12 @@ class User implements IUser {
254
153
  ]
255
154
  })
256
155
  public updatePassword(newPassword: string, oldPassword: string) {
257
- return this._request.send('auth.updatePassword', {
258
- oldPassword,
259
- newPassword
260
- });
261
- }
262
- /**
263
- * 更新邮箱地址
264
- * @param newEmail
265
- */
266
- @catchErrorsDecorator({
267
- title: '更新邮箱地址失败',
268
- messages: [
269
- '请确认以下各项:',
270
- ' 1 - 调用 User.updateEmail() 的语法或参数是否正确',
271
- ' 2 - 当前环境是否开通了邮箱密码登录',
272
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
273
- ]
274
- })
275
- public updateEmail(newEmail: string, password?: string) {
276
- return this._request.send('auth.updateEmail', {
277
- newEmail,
278
- password
279
- });
156
+ return this._oauthInstance.authApi.updatePasswordByOld({
157
+ old_password: oldPassword,
158
+ new_password: newPassword
159
+ })
280
160
  }
161
+
281
162
  /**
282
163
  * 更新用户名
283
164
  * @param username
@@ -296,10 +177,11 @@ class User implements IUser {
296
177
  throwError(ERRORS.INVALID_PARAMS, 'username must be a string');
297
178
  }
298
179
 
299
- return this._request.send('auth.updateUsername', {
180
+ return this.update({
300
181
  username
301
- });
182
+ })
302
183
  }
184
+
303
185
  /**
304
186
  * 刷新本地用户信息。当用户在其他客户端更新用户信息之后,可以调用此接口同步更新之后的信息。
305
187
  */
@@ -312,54 +194,12 @@ class User implements IUser {
312
194
  ]
313
195
  })
314
196
  public async refresh(): Promise<IUserInfo> {
315
- const action = 'auth.getUserInfo';
316
- const { data: userInfo } = await this._request.send(action, {});
317
- this._setLocalUserInfo(userInfo);
318
- return userInfo;
319
- }
320
-
321
- /**
322
- * 绑定手机号
323
- * @param phoneNumber
324
- * @param phoneCode
325
- */
326
- @catchErrorsDecorator({
327
- title: '绑定手机号失败',
328
- messages: [
329
- '请确认以下各项:',
330
- ' 1 - 调用 auth().linkWithPhoneNumber() 的语法或参数是否正确',
331
- ' 2 - 当前环境是否开通了短信验证码登录',
332
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
333
- ]
334
- })
335
- public async linkWithPhoneNumber(phoneNumber: string, phoneCode: string) {
336
- return this._request.send('auth.linkOrUpdatePhoneNumber', {
337
- phoneNumber: transformPhone(phoneNumber),
338
- phoneCode
339
- });
340
- }
341
- /**
342
- * 更新手机号
343
- * @param phoneNumber
344
- * @param phoneCode
345
- */
346
- @catchErrorsDecorator({
347
- title: '更新手机号失败',
348
- messages: [
349
- '请确认以下各项:',
350
- ' 1 - 调用语法或参数是否正确',
351
- ' 2 - 当前环境是否开通了短信验证码登录',
352
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
353
- ]
354
- })
355
- public async updatePhoneNumber(phoneNumber: string, phoneCode: string) {
356
- return this._request.send('auth.linkOrUpdatePhoneNumber', {
357
- phoneNumber: transformPhone(phoneNumber),
358
- phoneCode
359
- });
197
+ const newUserInfo = await this._oauthInstance.authApi.getUserInfo()
198
+ this._setLocalUserInfo(newUserInfo);
199
+ return newUserInfo;
360
200
  }
361
201
 
362
- private _getLocalUserInfo(key: string): string {
202
+ private _getLocalUserInfo(key: string): string | boolean {
363
203
  const { userInfoKey } = this._cache.keys;
364
204
  const userInfo = this._cache.getStore(userInfoKey);
365
205
  return userInfo[key];
@@ -376,29 +216,24 @@ class User implements IUser {
376
216
  const userInfo = this._cache.getStore(userInfoKey);
377
217
  [
378
218
  'uid',
379
- 'loginType',
380
- 'openid',
381
- 'wxOpenId',
382
- 'wxPublicId',
383
- 'unionId',
384
- 'qqMiniOpenId',
385
219
  'email',
386
- 'hasPassword',
387
- 'customUserId',
388
- 'nickName',
220
+ 'name',
389
221
  'gender',
222
+ 'picture',
390
223
  'avatarUrl',
391
224
  'phone',
225
+ 'email_verified',
226
+ 'phone_number',
227
+ 'birthdate',
228
+ 'zoneinfo',
229
+ 'locale',
230
+ 'sub',
231
+ 'created_from',
232
+ 'providers',
392
233
  'username'
393
234
  ].forEach(infoKey => {
394
235
  this[infoKey] = userInfo[infoKey];
395
236
  });
396
-
397
- this.location = {
398
- country: userInfo['country'],
399
- province: userInfo['province'],
400
- city: userInfo['city']
401
- };
402
237
  }
403
238
 
404
239
  private _setLocalUserInfo(userInfo: any) {
@@ -411,104 +246,143 @@ interface ILoginStateOptions extends IUserOptions {
411
246
  envId: string;
412
247
  }
413
248
  export class LoginState implements ILoginState {
414
- public credential: ICredential;
415
249
  public user: IUser;
250
+ public oauthLoginState: any
416
251
 
252
+ private _oauthInstance: CloudbaseOAuth
417
253
  private _cache: ICloudbaseCache;
418
- private _loginType: string;
419
254
 
420
255
  constructor(options: ILoginStateOptions) {
421
- const { envId, cache, request } = options;
256
+ const { envId, cache, oauthInstance } = options;
422
257
  if (!envId) {
423
258
  throwError(ERRORS.INVALID_PARAMS, 'envId is not defined');
424
259
  }
425
260
  this._cache = cache;
261
+ this._oauthInstance = oauthInstance
426
262
 
427
263
  this.user = new User({
428
- cache,
429
- request
264
+ cache: this._cache,
265
+ oauthInstance
430
266
  });
431
267
  }
432
268
 
433
-
434
- public async checkLocalState() {
435
- const { refreshTokenKey, accessTokenKey, accessTokenExpireKey } = this._cache.keys;
436
- const refreshToken = this._cache.getStore(refreshTokenKey);
437
- const accessToken = this._cache.getStore(accessTokenKey);
438
- const accessTokenExpire = this._cache.getStore(accessTokenExpireKey);
439
-
440
- this.credential = {
441
- refreshToken,
442
- accessToken,
443
- accessTokenExpire
444
- };
445
-
446
- this._loginType = this._cache.getStore(this._cache.keys.loginTypeKey);
447
-
269
+ public checkLocalState() {
270
+ this.oauthLoginState = this._oauthInstance?.authApi.hasLoginStateSync()
448
271
  this.user.checkLocalInfo();
449
272
  }
450
- public async checkLocalStateAsync() {
451
- const { refreshTokenKey, accessTokenKey, accessTokenExpireKey } = this._cache.keys;
452
- const refreshToken = await this._cache.getStoreAsync(refreshTokenKey);
453
- const accessToken = await this._cache.getStoreAsync(accessTokenKey);
454
- const accessTokenExpire = await this._cache.getStoreAsync(accessTokenExpireKey);
455
-
456
- this.credential = {
457
- refreshToken,
458
- accessToken,
459
- accessTokenExpire
460
- };
461
-
462
- this._loginType = await this._cache.getStoreAsync(this._cache.keys.loginTypeKey);
463
-
464
273
 
274
+ public async checkLocalStateAsync() {
275
+ await this._oauthInstance?.authApi.getLoginState()
465
276
  await this.user.checkLocalInfoAsync();
466
277
  }
278
+ }
467
279
 
468
- get isAnonymousAuth() {
469
- return this.loginType === LOGINTYPE.ANONYMOUS;
470
- }
280
+ class Auth {
281
+ private readonly _config: ICloudbaseAuthConfig;
282
+ private readonly _cache: ICloudbaseCache
283
+ // private readonly _request: ICloudbaseRequest;
471
284
 
472
- get isCustomAuth() {
473
- return this.loginType === LOGINTYPE.CUSTOM;
474
- }
285
+ private _oauthInstance: CloudbaseOAuth
475
286
 
476
- get isWeixinAuth() {
477
- return this.loginType === LOGINTYPE.WECHAT || this.loginType === LOGINTYPE.WECHAT_OPEN || this.loginType === LOGINTYPE.WECHAT_PUBLIC;
287
+ constructor(config: ICloudbaseAuthConfig & { cache: ICloudbaseCache, request?: ICloudbaseRequest, runtime?: string }) {
288
+ this._config = config;
289
+ this._cache = config.cache;
290
+ // this._request = config.request;
291
+ this._oauthInstance = config.oauthInstance
478
292
  }
479
293
 
480
- get isUsernameAuth() {
481
- return this.loginType === LOGINTYPE.USERNAME;
294
+ /**
295
+ * 绑定手机号
296
+ * @param phoneNumber
297
+ * @param phoneCode
298
+ */
299
+ @catchErrorsDecorator({
300
+ title: '绑定手机号失败',
301
+ messages: [
302
+ '请确认以下各项:',
303
+ ' 1 - 调用 auth().bindPhoneNumber() 的语法或参数是否正确',
304
+ ' 2 - 当前环境是否开通了短信验证码登录',
305
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
306
+ ]
307
+ })
308
+ public async bindPhoneNumber(params: authModels.BindPhoneRequest) {
309
+ return this._oauthInstance.authApi.bindPhone(params)
482
310
  }
483
311
 
484
- get loginType() {
485
- return this._loginType
312
+ /**
313
+ * 解绑三方绑定
314
+ * @param loginType
315
+ */
316
+ @catchErrorsDecorator({
317
+ title: '解除三方绑定失败',
318
+ messages: [
319
+ '请确认以下各项:',
320
+ ' 1 - 调用 auth().unbindProvider() 的语法或参数是否正确',
321
+ ' 2 - 当前账户是否已经与此登录方式解绑',
322
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
323
+ ]
324
+ })
325
+ public async unbindProvider(params: authModels.UnbindProviderRequest): Promise<void> {
326
+ return this._oauthInstance.authApi.unbindProvider(params)
486
327
  }
487
328
 
488
- get isPhoneAuth() {
489
- return this.loginType === LOGINTYPE.PHONE
329
+ /**
330
+ * 更新邮箱地址
331
+ * @param email
332
+ * @param sudo_token
333
+ * @param verification_token
334
+ */
335
+ @catchErrorsDecorator({
336
+ title: '绑定邮箱地址失败',
337
+ messages: [
338
+ '请确认以下各项:',
339
+ ' 1 - 调用 auth().bindEmail() 的语法或参数是否正确',
340
+ ' 2 - 当前环境是否开通了邮箱密码登录',
341
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
342
+ ]
343
+ })
344
+ public bindEmail(params: authModels.BindEmailRequest) {
345
+ return this._oauthInstance.authApi.bindEmail(params)
490
346
  }
491
- }
492
347
 
493
- class Auth {
494
- private readonly _config: ICloudbaseAuthConfig;
495
- private readonly _cache: ICloudbaseCache
496
- private readonly _request: ICloudbaseRequest;
497
- private readonly _runtime: string;
498
- private _anonymousAuthProvider: AnonymousAuthProvider;
499
- private _customAuthProvider: CustomAuthProvider;
500
- private _weixinAuthProvider: WeixinAuthProvider;
501
- private _emailAuthProvider: EmailAuthProvider;
502
- private _usernameAuthProvider: UsernameAuthProvider;
503
- private _phoneAuthProvider: PhoneAuthProvider;
504
-
505
- constructor(config: ICloudbaseAuthConfig & { cache: ICloudbaseCache, request: ICloudbaseRequest, runtime?: string }) {
506
- this._config = config;
507
- this._cache = config.cache;
508
- this._request = config.request;
509
- this._runtime = config.runtime || RUNTIME.WEB
348
+ /**
349
+ * verify
350
+ * @param {authModels.VerifyRequest} params
351
+ * @returns {Promise<authModels.VerifyResponse>}
352
+ * @memberof User
353
+ */
354
+ @catchErrorsDecorator({
355
+ title: '验证码验证失败',
356
+ messages: [
357
+ '请确认以下各项:',
358
+ ' 1 - 调用 auth().verify() 的语法或参数是否正确',
359
+ ' 2 - 当前环境是否开通了手机验证码/邮箱登录',
360
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
361
+ ]
362
+ })
363
+ public async verify(params: authModels.VerifyRequest): Promise<authModels.VerifyResponse> {
364
+ return this._oauthInstance.authApi.verify(params)
365
+ }
510
366
 
511
- eventBus.on(EVENTS.LOGIN_TYPE_CHANGED, this._onLoginTypeChanged.bind(this));
367
+ /**
368
+ * 获取验证码
369
+ * @param {authModels.GetVerificationRequest} params
370
+ * @returns {Promise<authModels.GetVerificationResponse>}
371
+ * @memberof User
372
+ */
373
+ @catchErrorsDecorator({
374
+ title: '获取验证码失败',
375
+ messages: [
376
+ '请确认以下各项:',
377
+ ' 1 - 调用 auth().getVerification() 的语法或参数是否正确',
378
+ ' 2 - 当前环境是否开通了手机验证码/邮箱登录',
379
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
380
+ ]
381
+ })
382
+ public async getVerification(
383
+ params: authModels.GetVerificationRequest,
384
+ ): Promise<authModels.GetVerificationResponse> {
385
+ return this._oauthInstance.authApi.getVerification(params)
512
386
  }
513
387
 
514
388
  /**
@@ -517,7 +391,7 @@ class Auth {
517
391
  get currentUser() {
518
392
  if (this._cache.mode === 'async') {
519
393
  // async storage的平台调用此API提示
520
- printWarn(ERRORS.INVALID_OPERATION, 'current platform\'s storage is asynchronous, please use getCurrenUser insteed');
394
+ printWarn(ERRORS.INVALID_OPERATION, 'current platform\'s storage is asynchronous, please use getCurrentUser insteed');
521
395
  return;
522
396
  }
523
397
 
@@ -530,13 +404,6 @@ class Auth {
530
404
  }
531
405
  }
532
406
 
533
- /**
534
- * 获取当前登录类型-同步
535
- */
536
- get loginType(): LOGINTYPE {
537
- return this._cache.getStore(this._cache.keys.loginTypeKey);
538
- }
539
-
540
407
  /**
541
408
  * 获取当前登录的用户信息-异步
542
409
  */
@@ -548,7 +415,7 @@ class Auth {
548
415
  `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
549
416
  ]
550
417
  })
551
- public async getCurrenUser() {
418
+ public async getCurrentUser() {
552
419
  const loginState = await this.getLoginState();
553
420
  if (loginState) {
554
421
  await loginState.user.checkLocalInfoAsync();
@@ -557,88 +424,99 @@ class Auth {
557
424
  return null;
558
425
  }
559
426
  }
427
+
428
+
560
429
  /**
561
- * 获取当前登录类型-异步
430
+ * 匿名登录
431
+ * @returns {Promise<LoginState>}
432
+ * @memberof Auth
562
433
  */
563
- public async getLoginType(): Promise<LOGINTYPE> {
564
- return await this._cache.getStoreAsync(this._cache.keys.loginTypeKey) as LOGINTYPE;
565
- }
566
- public async getAccessToken() {
567
- return {
568
- accessToken: (await this._request.getAccessToken()).accessToken,
569
- env: this._config.env
570
- };
571
- }
572
- public weixinAuthProvider({ appid, scope, state }): WeixinAuthProvider {
573
- if (!this._weixinAuthProvider) {
574
- this._weixinAuthProvider = new WeixinAuthProvider({
575
- ...this._config,
576
- cache: this._cache,
577
- request: this._request,
578
- runtime: this._runtime
579
- }, appid, scope, state);
580
- }
581
- return this._weixinAuthProvider;
582
- }
583
- public anonymousAuthProvider(): AnonymousAuthProvider {
584
- if (!this._anonymousAuthProvider) {
585
- this._anonymousAuthProvider = new AnonymousAuthProvider({
586
- ...this._config,
587
- cache: this._cache,
588
- request: this._request
589
- });
590
- }
591
- return this._anonymousAuthProvider;
434
+ @catchErrorsDecorator({
435
+ title: '匿名登录失败',
436
+ messages: [
437
+ '请确认以下各项:',
438
+ ' 1 - 当前环境是否开启了匿名登录',
439
+ ' 2 - 调用 auth().signInAnonymously() 的语法或参数是否正确',
440
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
441
+ ]
442
+ })
443
+ public async signInAnonymously(): Promise<LoginState> {
444
+ await this._oauthInstance.authApi.signInAnonymously()
445
+ return this.createLoginState()
592
446
  }
593
- public customAuthProvider(): CustomAuthProvider {
594
- if (!this._customAuthProvider) {
595
- this._customAuthProvider = new CustomAuthProvider({
596
- ...this._config,
597
- cache: this._cache,
598
- request: this._request
599
- });
600
- }
601
- return this._customAuthProvider;
447
+
448
+ /**
449
+ * 设置获取自定义登录 ticket 函数
450
+ * @param {authModels.GetCustomSignTicketFn} getTickFn
451
+ * @memberof Auth
452
+ */
453
+ public setCustomSignFunc(getTickFn: authModels.GetCustomSignTicketFn): void {
454
+ this._oauthInstance.authApi.setCustomSignFunc(getTickFn)
602
455
  }
603
- public emailAuthProvider(): EmailAuthProvider {
604
- if (!this._emailAuthProvider) {
605
- this._emailAuthProvider = new EmailAuthProvider({
606
- ...this._config,
607
- cache: this._cache,
608
- request: this._request
609
- });
610
- }
611
- return this._emailAuthProvider;
456
+
457
+ /**
458
+ *
459
+ * @returns {Promise<LoginState>}
460
+ * @memberof Auth
461
+ */
462
+ @catchErrorsDecorator({
463
+ title: '自定义登录失败',
464
+ messages: [
465
+ '请确认以下各项:',
466
+ ' 1 - 当前环境是否开启了自定义登录',
467
+ ' 2 - 调用 auth().signInWithCustomTicket() 的语法或参数是否正确',
468
+ ' 3 - ticket 是否归属于当前环境',
469
+ ' 4 - 创建 ticket 的自定义登录私钥是否过期',
470
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
471
+ ]
472
+ })
473
+ public async signInWithCustomTicket(): Promise<LoginState> {
474
+ await this._oauthInstance.authApi.signInWithCustomTicket()
475
+ return this.createLoginState()
612
476
  }
613
- public usernameAuthProvider(): UsernameAuthProvider {
614
- if (!this._usernameAuthProvider) {
615
- this._usernameAuthProvider = new UsernameAuthProvider({
616
- ...this._config,
617
- cache: this._cache,
618
- request: this._request
619
- });
620
- }
621
- return this._usernameAuthProvider;
477
+
478
+ /**
479
+ *
480
+ * @param {authModels.SignInRequest} params
481
+ * @returns {Promise<LoginState>}
482
+ * @memberof Auth
483
+ */
484
+ public async signIn(params: authModels.SignInRequest): Promise<LoginState> {
485
+ await this._oauthInstance.authApi.signIn(params)
486
+ return this.createLoginState()
622
487
  }
623
488
 
624
- public phoneAuthProvider(): PhoneAuthProvider {
625
- if (!this._phoneAuthProvider) {
626
- this._phoneAuthProvider = new PhoneAuthProvider({
627
- ...this._config,
628
- cache: this._cache,
629
- request: this._request
630
- });
631
- }
632
- return this._phoneAuthProvider;
489
+ /**
490
+ *
491
+ * @param {authModels.SignUpRequest} params
492
+ * @returns {Promise<LoginState>}
493
+ * @memberof Auth
494
+ */
495
+ @catchErrorsDecorator({
496
+ title: '注册失败',
497
+ messages: [
498
+ '请确认以下各项:',
499
+ ' 1 - 当前环境是否开启了指定登录方式',
500
+ ' 2 - 调用 auth().signUp() 的语法或参数是否正确',
501
+ `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
502
+ ]
503
+ })
504
+ public async signUp(params: authModels.SignUpRequest): Promise<LoginState> {
505
+ console.log('ggg')
506
+ await this._oauthInstance.authApi.signUp(params)
507
+ return this.createLoginState()
633
508
  }
509
+
634
510
  /**
635
- * 用户名密码登录
636
- * @param username
637
- * @param password
511
+ * 设置密码
512
+ * @param {authModels.SetPasswordRequest} params
513
+ * @returns {Promise<void>}
514
+ * @memberof Auth
638
515
  */
639
- public async signInWithUsernameAndPassword(username: string, password: string) {
640
- return this.usernameAuthProvider().signIn(username, password);
516
+ public async setPassword(params: authModels.SetPasswordRequest): Promise<void> {
517
+ return this._oauthInstance.authApi.setPassword(params)
641
518
  }
519
+
642
520
  /**
643
521
  * 检测用户名是否已经占用
644
522
  * @param username
@@ -656,34 +534,14 @@ class Auth {
656
534
  throwError(ERRORS.INVALID_PARAMS, 'username must be a string');
657
535
  }
658
536
 
659
- const { data } = await this._request.send('auth.isUsernameRegistered', {
660
- username
661
- });
662
- return data?.isRegistered;
663
- }
664
- /**
665
- * 邮箱密码登录
666
- * @param email
667
- * @param password
668
- */
669
- public async signInWithEmailAndPassword(email: string, password: string) {
670
- return this.emailAuthProvider().signIn(email, password);
671
- }
672
- /**
673
- * 邮箱密码注册
674
- * @param email
675
- * @param password
676
- */
677
- public async signUpWithEmailAndPassword(email: string, password: string) {
678
- return this.emailAuthProvider().signUp(email, password);
679
- }
680
- /**
681
- * 重置邮箱密码
682
- * @param email
683
- */
684
- public async sendPasswordResetEmail(email: string) {
685
- return this.emailAuthProvider().resetPassword(email);
537
+ try {
538
+ await this._oauthInstance.authApi.checkUsername({ username })
539
+ return true
540
+ } catch (e) {
541
+ return false
542
+ }
686
543
  }
544
+
687
545
  /**
688
546
  * 登出
689
547
  */
@@ -697,84 +555,35 @@ class Auth {
697
555
  ]
698
556
  })
699
557
  public async signOut() {
700
- // const loginType = await this.getLoginType();
701
- // if (loginType === LOGINTYPE.ANONYMOUS) {
702
- // throw new Error(JSON.stringify({
703
- // code: ERRORS.INVALID_OPERATION,
704
- // msg: 'anonymous user doesn\'t support signOut action'
705
- // }));
706
- // }
707
- const { refreshTokenKey, accessTokenKey, accessTokenExpireKey } = this._cache.keys;
708
- const action = 'auth.logout';
709
-
710
- const refresh_token = await this._cache.getStoreAsync(refreshTokenKey);
711
- if (!refresh_token) {
712
- return;
713
- }
714
- const res = await this._request.send(action, { refresh_token });
715
-
716
- this._cache.removeStoreAsync(refreshTokenKey);
717
- this._cache.removeStoreAsync(accessTokenKey);
718
- this._cache.removeStoreAsync(accessTokenExpireKey);
719
-
720
- eventBus.fire(EVENTS.LOGIN_STATE_CHANGED);
721
- eventBus.fire(EVENTS.LOGIN_TYPE_CHANGED, {
722
- env: this._config.env,
723
- loginType: LOGINTYPE.NULL,
724
- persistence: this._config.persistence
725
- });
726
-
727
-
728
- return res;
729
- }
730
- public async onLoginStateChanged(callback: Function) {
731
- eventBus.on(EVENTS.LOGIN_STATE_CHANGED, async () => {
732
- const loginState = await this.getLoginState();
733
- callback.call(this, loginState);
734
- });
735
- // 立刻执行一次回调
736
- const loginState = await this.getLoginState();
737
- callback.call(this, loginState);
738
- }
739
- public onLoginStateExpired(callback: Function) {
740
- eventBus.on(EVENTS.LOGIN_STATE_EXPIRED, callback.bind(this));
741
- }
742
- public onAccessTokenRefreshed(callback: Function) {
743
- eventBus.on(EVENTS.ACCESS_TOKEN_REFRESHD, callback.bind(this));
744
- }
745
- public onAnonymousConverted(callback: Function) {
746
- eventBus.on(EVENTS.ANONYMOUS_CONVERTED, callback.bind(this));
747
- }
748
- public onLoginTypeChanged(callback: Function) {
749
- eventBus.on(EVENTS.LOGIN_TYPE_CHANGED, async () => {
750
- const loginState = await this.getLoginState();
751
- callback.call(this, loginState);
752
- });
558
+ const { userInfoKey } = this._cache.keys;
559
+ await this._oauthInstance.authApi.signOut()
560
+ await this._cache.removeStoreAsync(userInfoKey)
561
+ eventBus.fire(EVENTS.LOGIN_STATE_CHANGED)
753
562
  }
563
+
754
564
  /**
755
565
  * 获取本地登录态-同步
756
566
  */
757
- public hasLoginState(): ILoginState | null {
567
+ public hasLoginState(): LoginState | null {
758
568
  if (this._cache.mode === 'async') {
759
569
  // async storage的平台调用此API提示
760
570
  printWarn(ERRORS.INVALID_OPERATION, 'current platform\'s storage is asynchronous, please use getLoginState insteed');
761
571
  return;
762
572
  }
763
- const { refreshTokenKey } = this._cache.keys;
764
- const refreshToken = this._cache.getStore(refreshTokenKey);
765
573
 
766
- if (refreshToken) {
574
+ const oauthLoginState = this._oauthInstance?.authApi.hasLoginStateSync()
575
+ if (oauthLoginState) {
767
576
  const loginState = new LoginState({
768
577
  envId: this._config.env,
769
578
  cache: this._cache,
770
- request: this._request
771
- });
772
- loginState.checkLocalState();
773
- return loginState;
579
+ oauthInstance: this._oauthInstance,
580
+ })
581
+ return loginState
774
582
  } else {
775
- return null;
583
+ return null
776
584
  }
777
585
  }
586
+
778
587
  /**
779
588
  * 获取本地登录态-异步
780
589
  * 此API为兼容异步storage的平台
@@ -788,25 +597,19 @@ class Auth {
788
597
  ]
789
598
  })
790
599
  public async getLoginState() {
791
- const { refreshTokenKey } = this._cache.keys;
792
- const refreshToken = await this._cache.getStoreAsync(refreshTokenKey);
793
- if (refreshToken) {
600
+ const oauthLoginState = await this._oauthInstance.authApi.getLoginState()
601
+ if (oauthLoginState) {
794
602
  const loginState = new LoginState({
795
603
  envId: this._config.env,
796
604
  cache: this._cache,
797
- request: this._request
798
- });
799
- await loginState.checkLocalStateAsync();
800
- return loginState;
801
- } else {
802
- return null;
605
+ oauthInstance: this._oauthInstance,
606
+ })
607
+ return loginState
803
608
  }
804
- }
805
609
 
806
- public shouldRefreshAccessToken(hook) {
807
- // @ts-ignore
808
- this._request._shouldRefreshAccessTokenHook = hook.bind(this);
610
+ return null
809
611
  }
612
+
810
613
  @catchErrorsDecorator({
811
614
  title: '获取用户信息失败',
812
615
  messages: [
@@ -816,159 +619,148 @@ class Auth {
816
619
  `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
817
620
  ]
818
621
  })
819
- public async getUserInfo(): Promise<any> {
820
- const action = 'auth.getUserInfo';
821
-
822
- const res = await this._request.send(action, {});
823
- if (res.code) {
824
- return res;
825
- } else {
826
- return {
827
- ...res.data,
828
- requestId: res.seqId
829
- };
830
- }
622
+ public async getUserInfo(): Promise<IUserInfo> {
623
+ return this._oauthInstance.authApi.getUserInfo()
831
624
  }
832
- /**
833
- * 获取Http鉴权header,用于云接入 HTTP 访问云函数时的鉴权
834
- */
835
- public getAuthHeader() {
836
- const { refreshTokenKey, accessTokenKey } = this._cache.keys;
837
- const refreshToken = this._cache.getStore(refreshTokenKey);
838
- const accessToken = this._cache.getStore(accessTokenKey);
839
- return {
840
- 'x-cloudbase-credentials': accessToken + '/@@/' + refreshToken
841
- };
842
- }
843
- /**
844
- * 异步模式获取Http鉴权header,用于云接入 HTTP 访问云函数时的鉴权
845
- * 调用此API会刷新登录态
846
- */
847
- public async getAuthHeaderAsync() {
848
- await this._request.refreshAccessToken();
849
625
 
850
- const { refreshTokenKey, accessTokenKey } = this._cache.keys;
851
- const refreshToken = await this._cache.getStoreAsync(refreshTokenKey);
852
- const accessToken = await this._cache.getStoreAsync(accessTokenKey);
853
- return {
854
- 'x-cloudbase-credentials': accessToken + '/@@/' + refreshToken
855
- };
856
- }
857
626
 
858
627
  /**
859
- * 发送验证码
860
- * @param phoneNumber
861
- * @param phoneCode
862
- */
628
+ * 为已有账户绑第三方账户
629
+ * @param {authModels.BindWithProviderRequest} params
630
+ * @returns {Promise<void>}
631
+ * @memberof Auth
632
+ */
863
633
  @catchErrorsDecorator({
864
- title: '发送短信验证码失败',
634
+ title: '绑定第三方登录方式失败',
865
635
  messages: [
866
636
  '请确认以下各项:',
867
- ' 1 - 调用语法或参数是否正确',
868
- ' 2 - 当前环境是否开通了短信验证码登录',
637
+ ' 1 - 调用 auth().bindWithProvider() 的语法或参数是否正确',
638
+ ' 2 - 此账户是否已经绑定此第三方',
869
639
  `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
870
640
  ]
871
641
  })
872
- public async sendPhoneCode(phoneNumber: string): Promise<boolean> {
873
- const { data } = await this._request.send('auth.sendPhoneCode', {
874
- phoneNumber: transformPhone(phoneNumber)
875
- });
876
- return data.SendStatus === 'Ok'
642
+ public async bindWithProvider(
643
+ params: authModels.BindWithProviderRequest,
644
+ ): Promise<void> {
645
+ return this._oauthInstance.authApi.bindWithProvider(params)
877
646
  }
878
647
 
879
648
  /**
880
- * 手机短信注册
881
- * @param email
882
- * @param password
649
+ * 查询用户
650
+ * @param {authModels.QueryUserProfileRequest} appended_params
651
+ * @returns {Promise<authModels.UserProfile>}
652
+ * @memberof Auth
883
653
  */
884
- public async signUpWithPhoneCode(phoneNumber: string, phoneCode: string, password: string) {
885
- return this.phoneAuthProvider().signUp(phoneNumber, phoneCode, password);
654
+ public async queryUser(
655
+ queryObj: authModels.QueryUserProfileRequest,
656
+ ): Promise<authModels.QueryUserProfileResponse> {
657
+ return this._oauthInstance.authApi.queryUserProfile(queryObj)
886
658
  }
887
659
 
888
- /**
889
- * 手机验证码 or 密码登录
890
- * @param email
891
- * @param password
892
- */
893
- public async signInWithPhoneCodeOrPassword(param: {
894
- phoneNumber: string
895
- phoneCode?: string
896
- password?: string
897
- signMethod?: string
898
- }) {
899
- return this.phoneAuthProvider().signIn(param);
660
+ public async getAccessToken() {
661
+ const oauthAccessTokenRes = await this._oauthInstance.oauth2client.getAccessToken()
662
+ return {
663
+ accessToken: oauthAccessTokenRes,
664
+ env: this._config.env
665
+ };
666
+ }
667
+
668
+ public async grantProviderToken(
669
+ params: authModels.GrantProviderTokenRequest,
670
+ ): Promise<authModels.GrantProviderTokenResponse> {
671
+ return this._oauthInstance.authApi.grantProviderToken(params)
672
+ }
673
+
674
+ public async signInWithProvider(
675
+ params: authModels.SignInWithProviderRequest,
676
+ ): Promise<LoginState> {
677
+ await this._oauthInstance.authApi.signInWithProvider(params)
678
+ return this.createLoginState()
679
+ }
680
+
681
+ public async grantToken(params: authModels.GrantTokenRequest): Promise<LoginState> {
682
+ await this._oauthInstance.authApi.grantToken(params)
683
+ return this.createLoginState()
900
684
  }
901
685
 
902
- public async forceResetPwdByPhoneCode(param: {
903
- phoneNumber: string
904
- phoneCode: string
905
- password: string
906
- }) {
907
- return this.phoneAuthProvider().signIn({
908
- ...param,
909
- signMethod: SIGN_METHOD.FORCERESETPWD
686
+ public async genProviderRedirectUri(
687
+ params: authModels.GenProviderRedirectUriRequest,
688
+ ): Promise<authModels.GenProviderRedirectUriResponse> {
689
+ return this._oauthInstance.authApi.genProviderRedirectUri(params)
690
+ }
691
+
692
+ public async resetPassword(params: authModels.ResetPasswordRequest): Promise<void> {
693
+ return this._oauthInstance.authApi.resetPassword(params)
694
+ }
695
+
696
+ public async deviceAuthorize(params: authModels.DeviceAuthorizeRequest): Promise<authModels.DeviceAuthorizeResponse> {
697
+ return this._oauthInstance.authApi.deviceAuthorize(params)
698
+ }
699
+
700
+ public async sudo(params: authModels.SudoRequest): Promise<authModels.SudoResponse> {
701
+ return this._oauthInstance.authApi.sudo(params)
702
+ }
703
+
704
+ public async onLoginStateChanged(callback: Function) {
705
+ eventBus.on(EVENTS.LOGIN_STATE_CHANGED, async () => {
706
+ const loginState = await this.getLoginState();
707
+ callback.call(this, loginState);
910
708
  });
709
+ // 立刻执行一次回调
710
+ const loginState = await this.getLoginState();
711
+ callback.call(this, loginState);
911
712
  }
912
713
 
913
- private async _onLoginTypeChanged(ev) {
914
- const { loginType, persistence, env } = ev.data;
915
- if (env !== this._config.env) {
916
- return;
917
- }
918
- // 登录态转变后迁移cache,防止在匿名登录状态下cache混用
919
- await this._cache.updatePersistenceAsync(persistence);
920
- await this._cache.setStoreAsync(this._cache.keys.loginTypeKey, loginType);
714
+ private async createLoginState(): Promise<LoginState> {
715
+ const loginState = new LoginState({
716
+ envId: this._config.env,
717
+ cache: this._cache,
718
+ oauthInstance: this._oauthInstance,
719
+ })
720
+
721
+ await loginState.checkLocalStateAsync();
722
+ await loginState.user.refresh();
723
+ eventBus.fire(EVENTS.LOGIN_STATE_CHANGED);
724
+ return loginState
921
725
  }
922
726
  }
923
727
 
924
- const EVENTS = {
925
- // 登录态改变后触发
926
- LOGIN_STATE_CHANGED: 'loginStateChanged',
927
- // 登录态过期后触发
928
- LOGIN_STATE_EXPIRED: 'loginStateExpire',
929
- // 登录类型改变后触发
930
- LOGIN_TYPE_CHANGED: 'loginTypeChanged',
931
- // 匿名账户被转正后触发
932
- ANONYMOUS_CONVERTED: 'anonymousConverted',
933
- // access token刷新后触发
934
- ACCESS_TOKEN_REFRESHD: 'refreshAccessToken'
935
- };
936
-
937
728
  const component: ICloudbaseComponent = {
938
729
  name: COMPONENT_NAME,
939
730
  namespace: 'auth',
940
- injectEvents: {
941
- bus: eventBus,
942
- events: [
943
- EVENTS.LOGIN_TYPE_CHANGED,
944
- EVENTS.LOGIN_STATE_EXPIRED,
945
- EVENTS.LOGIN_STATE_CHANGED,
946
- EVENTS.ACCESS_TOKEN_REFRESHD,
947
- EVENTS.ANONYMOUS_CONVERTED
948
- ]
949
- },
950
731
  entity: function (config: Pick<ICloudbaseAuthConfig, 'region' | 'persistence'> = { region: '', persistence: 'local' }) {
951
732
  if (this.authInstance) {
952
733
  printWarn(ERRORS.INVALID_OPERATION, 'every cloudbase instance should has only one auth object');
953
734
  return this.authInstance;
954
735
  }
955
736
  const { adapter, runtime } = this.platform;
956
- // 如不明确指定persistence则优先取各平台adapter首选,其次session
737
+ // 如不明确指定persistence则优先取各平台adapter首选,其次localStorage
957
738
  const newPersistence = config.persistence || adapter.primaryStorage;
958
739
  if (newPersistence && (newPersistence !== this.config.persistence)) {
959
740
  this.updateConfig({ persistence: newPersistence })
960
741
  }
961
742
 
962
- const { env, persistence, debug } = this.config;
743
+ const { env, persistence, debug, clientId } = this.config;
744
+ const oauthInstance = new CloudbaseOAuth({
745
+ clientId: clientId,
746
+ apiOrigin: this.request.getBaseEndPoint(),
747
+ })
748
+
749
+ this.oauthInstance = oauthInstance
750
+
963
751
  this.authInstance = new Auth({
964
752
  env,
965
753
  region: config.region,
966
754
  persistence,
967
755
  debug,
968
756
  cache: this.cache,
969
- request: this.request,
970
- runtime: runtime
757
+ // request: this.request,
758
+ runtime: runtime,
759
+ _fromApp: this,
760
+ // oauthInstance: this.oauthInstance || (this as any).oauth()
761
+ oauthInstance
971
762
  });
763
+
972
764
  return this.authInstance;
973
765
  }
974
766
  }
@@ -982,9 +774,6 @@ try {
982
774
  export {
983
775
  UserInfo,
984
776
  Auth,
985
- AuthProvider,
986
- EVENTS,
987
- eventBus
988
777
  };
989
778
  /**
990
779
  * @api 手动注册至cloudbase app
@@ -997,29 +786,3 @@ export function registerAuth(app: Pick<ICloudbase, 'registerComponent'>) {
997
786
  }
998
787
  }
999
788
 
1000
- type IProvider = new (...args: any[]) => any;
1001
- /**
1002
- * 注册provider,如果
1003
- * @param name
1004
- * @param provider
1005
- * @example
1006
- * // 注册
1007
- * registerProvider('emailAuthProvider',function(){
1008
- * // ...
1009
- * });
1010
- * // 使用新provider登录
1011
- * cloudbase.auth().emailAuthProvider().signIn();
1012
- */
1013
- export function registerProvider(name: string, provider: IProvider) {
1014
- const proto = Auth.prototype;
1015
- proto[name] = function (options: object) {
1016
- const privateName = `_${name}`;
1017
- if (!this[privateName]) {
1018
- this[privateName] = new provider({
1019
- ...options,
1020
- ...this._config
1021
- });
1022
- }
1023
- return this[privateName];
1024
- };
1025
- }