@cloudbase/auth 1.7.2-alpha.0 → 2.0.0-alpha.2

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