@cloudbase/oauth 2.5.46-beta.0 → 2.5.48-beta.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.
@@ -42,6 +42,7 @@ export interface AuthClientRequestOptions extends RequestOptions {
42
42
  } | null;
43
43
  withCredentials?: boolean;
44
44
  retry?: number;
45
+ useWxCloud?: boolean;
45
46
 
46
47
  [key: string]: any;
47
48
  }
@@ -50,6 +51,7 @@ export interface OAuth2ClientOptions {
50
51
  devMode?: boolean;
51
52
  apiOrigin: string;
52
53
  clientId: string;
54
+ env: string;
53
55
  // default value is 1,min value is 0, max value is 5
54
56
  retry?: number;
55
57
  baseRequest?: <T>(url: string, options?: RequestOptions) => Promise<T>;
@@ -62,4 +64,5 @@ export interface OAuth2ClientOptions {
62
64
  headers?: { [key: string]: string };
63
65
  // hook
64
66
  anonymousSignInFunc?: (Credentials) => Promise<Credentials | void>
67
+ wxCloud?: any;
65
68
  }
@@ -1,5 +1,6 @@
1
1
  import { ErrorType } from './consts'
2
2
  import { ApiUrls, ApiUrlsV2 } from '../auth/consts'
3
+ import adapterForWxMp from 'cloudbase-adapter-wx_mp'
3
4
 
4
5
  import { AuthClient, SimpleStorage } from './interface'
5
6
 
@@ -13,6 +14,7 @@ import {
13
14
  } from './models'
14
15
 
15
16
  import { uuidv4 } from '../utils/uuid'
17
+ import { getPathName } from '../utils/index'
16
18
 
17
19
  import { SinglePromise } from '../utils/function/single-promise'
18
20
 
@@ -20,18 +22,16 @@ const RequestIdHeaderName = 'x-request-id'
20
22
  const DeviceIdHeaderName = 'x-device-id'
21
23
  const DeviceIdSectionName = 'device_id'
22
24
 
25
+ declare const wx: any
26
+
23
27
  export interface ToResponseErrorOptions {
24
- error?: ErrorType;
25
- error_description?: string | null;
26
- error_uri?: string | null;
27
- details?: any | null;
28
+ error?: ErrorType
29
+ error_description?: string | null
30
+ error_uri?: string | null
31
+ details?: any | null
28
32
  }
29
33
 
30
-
31
- export const defaultRequest: RequestFunction = async function <T>(
32
- url: string,
33
- options?: RequestOptions
34
- ): Promise<T> {
34
+ export const defaultRequest: RequestFunction = async function <T>(url: string, options?: RequestOptions): Promise<T> {
35
35
  let result: T | null = null
36
36
  let responseError: ResponseError | null = null
37
37
  try {
@@ -65,10 +65,7 @@ export const defaultRequest: RequestFunction = async function <T>(
65
65
  }
66
66
  }
67
67
 
68
- export const toResponseError = (
69
- error: ResponseError | Error,
70
- options?: ToResponseErrorOptions,
71
- ): ResponseError => {
68
+ export const toResponseError = (error: ResponseError | Error, options?: ToResponseErrorOptions): ResponseError => {
72
69
  let responseError: ResponseError
73
70
  const formatOptions: ToResponseErrorOptions = options || {}
74
71
  if (error instanceof Error) {
@@ -82,8 +79,7 @@ export const toResponseError = (
82
79
  const formatError: ToResponseErrorOptions = error || {}
83
80
  responseError = {
84
81
  error: formatOptions.error || formatError.error || ErrorType.LOCAL,
85
- error_description:
86
- formatOptions.error_description || formatError.error_description,
82
+ error_description: formatOptions.error_description || formatError.error_description,
87
83
  error_uri: formatOptions.error_uri || formatError.error_uri,
88
84
  details: formatOptions.details || formatError.details,
89
85
  }
@@ -99,57 +95,56 @@ export function generateRequestId(): string {
99
95
  return uuidv4()
100
96
  }
101
97
 
102
-
103
98
  /**
104
99
  * Default Storage.
105
100
  */
106
101
  class DefaultStorage implements SimpleStorage {
107
102
  /**
108
- * Get item.
109
- * @param {string} key
110
- */
103
+ * Get item.
104
+ * @param {string} key
105
+ */
111
106
  async getItem(key: string): Promise<string | null> {
112
107
  return window.localStorage.getItem(key)
113
108
  }
114
109
 
115
110
  /**
116
- * Remove item.
117
- * @param {string} key
118
- */
111
+ * Remove item.
112
+ * @param {string} key
113
+ */
119
114
  async removeItem(key: string): Promise<void> {
120
115
  window.localStorage.removeItem(key)
121
116
  }
122
117
 
123
118
  /**
124
- * Set item.
125
- * @param {string} key
126
- * @param {string} value
127
- */
119
+ * Set item.
120
+ * @param {string} key
121
+ * @param {string} value
122
+ */
128
123
  async setItem(key: string, value: string): Promise<void> {
129
124
  window.localStorage.setItem(key, value)
130
125
  }
131
126
 
132
127
  /**
133
- * Get item sync.
134
- * @param {string} key
135
- */
128
+ * Get item sync.
129
+ * @param {string} key
130
+ */
136
131
  getItemSync(key: string): string | null {
137
132
  return window.localStorage.getItem(key)
138
133
  }
139
134
 
140
135
  /**
141
- * Remove item sync.
142
- * @param {string} key
143
- */
136
+ * Remove item sync.
137
+ * @param {string} key
138
+ */
144
139
  removeItemSync(key: string): void {
145
140
  window.localStorage.removeItem(key)
146
141
  }
147
142
 
148
143
  /**
149
- * Set item sync.
150
- * @param {string} key
151
- * @param {string} value
152
- */
144
+ * Set item sync.
145
+ * @param {string} key
146
+ * @param {string} value
147
+ */
153
148
  setItemSync(key: string, value: string): void {
154
149
  window.localStorage.setItem(key, value)
155
150
  }
@@ -158,8 +153,8 @@ class DefaultStorage implements SimpleStorage {
158
153
  export const defaultStorage = new DefaultStorage()
159
154
 
160
155
  interface LocalCredentialsOptions {
161
- tokenSectionName: string;
162
- storage: SimpleStorage;
156
+ tokenSectionName: string
157
+ storage: SimpleStorage
163
158
  }
164
159
 
165
160
  /**
@@ -200,7 +195,7 @@ class LocalCredentials {
200
195
 
201
196
  public getStorageCredentialsSync(): Credentials | null {
202
197
  let credentials: Credentials = null
203
- const tokenStr: string = this.storage.getItemSync(this.tokenSectionName,)
198
+ const tokenStr: string = this.storage.getItemSync(this.tokenSectionName)
204
199
  if (tokenStr !== undefined && tokenStr !== null) {
205
200
  try {
206
201
  credentials = JSON.parse(tokenStr)
@@ -221,7 +216,7 @@ class LocalCredentials {
221
216
  */
222
217
  public async setCredentials(credentials?: Credentials): Promise<void> {
223
218
  if (credentials?.expires_in) {
224
- credentials.expires_at = new Date(Date.now() + (credentials.expires_in - 30) * 1000,)
219
+ credentials.expires_at = new Date(Date.now() + (credentials.expires_in - 30) * 1000)
225
220
  if (this.storage) {
226
221
  const tokenStr: string = JSON.stringify(credentials)
227
222
  await this.storage.setItem(this.tokenSectionName, tokenStr)
@@ -254,7 +249,7 @@ class LocalCredentials {
254
249
  private async getStorageCredentials(): Promise<Credentials | null> {
255
250
  return this.singlePromise.run('_getStorageCredentials', async () => {
256
251
  let credentials: Credentials = null
257
- const tokenStr: string = await this.storage.getItem(this.tokenSectionName,)
252
+ const tokenStr: string = await this.storage.getItem(this.tokenSectionName)
258
253
  if (tokenStr !== undefined && tokenStr !== null) {
259
254
  try {
260
255
  credentials = JSON.parse(tokenStr)
@@ -284,10 +279,7 @@ export class OAuth2Client implements AuthClient {
284
279
  private clientId: string
285
280
  private retry: number
286
281
  private clientSecret?: string
287
- private baseRequest: <T>(
288
- url: string,
289
- options?: RequestOptions,
290
- ) => Promise<T>
282
+ private baseRequest: <T>(url: string, options?: RequestOptions) => Promise<T>
291
283
  private localCredentials: LocalCredentials
292
284
  private storage: SimpleStorage
293
285
  private deviceID?: string
@@ -296,6 +288,7 @@ export class OAuth2Client implements AuthClient {
296
288
  private headers?: { [key: string]: string }
297
289
  private singlePromise: SinglePromise = new SinglePromise()
298
290
  private anonymousSignInFunc: (Credentials) => Promise<Credentials | void>
291
+ private wxCloud: any
299
292
 
300
293
  /**
301
294
  * constructor
@@ -319,6 +312,15 @@ export class OAuth2Client implements AuthClient {
319
312
  storage: this.storage,
320
313
  })
321
314
  this.clientSecret = options.clientSecret
315
+ this.wxCloud = options.wxCloud
316
+ try {
317
+ if (adapterForWxMp.isMatch() && this.wxCloud === undefined && options.env) {
318
+ wx.cloud.init({ env: options.env })
319
+ this.wxCloud = wx.cloud
320
+ }
321
+ } catch (error) {
322
+ //
323
+ }
322
324
  this.refreshTokenFunc = options.refreshTokenFunc || this.defaultRefreshTokenFunc
323
325
  this.anonymousSignInFunc = options.anonymousSignInFunc
324
326
  }
@@ -349,10 +351,7 @@ export class OAuth2Client implements AuthClient {
349
351
  * @param {string} url
350
352
  * @param {AuthClientRequestOptions} options
351
353
  */
352
- public async request<T>(
353
- url: string,
354
- options?: AuthClientRequestOptions,
355
- ): Promise<T> {
354
+ public async request<T>(url: string, options?: AuthClientRequestOptions): Promise<T> {
356
355
  if (!options) {
357
356
  options = {}
358
357
  }
@@ -394,13 +393,13 @@ export class OAuth2Client implements AuthClient {
394
393
  }
395
394
  let response: T | null = null
396
395
  const maxRequestTimes: number = retry + 1
397
- for (
398
- let requestTime = 0;
399
- requestTime < maxRequestTimes;
400
- requestTime++
401
- ) {
396
+ for (let requestTime = 0; requestTime < maxRequestTimes; requestTime++) {
402
397
  try {
403
- response = await this.baseRequest<T>(url, options)
398
+ if (options.useWxCloud) {
399
+ response = await this.wxCloudCallFunction<T>(url, options)
400
+ } else {
401
+ response = await this.baseRequest<T>(url, options)
402
+ }
404
403
  break
405
404
  } catch (responseError) {
406
405
  if (options.withCredentials && responseError && responseError.error === ErrorType.UNAUTHENTICATED) {
@@ -408,11 +407,7 @@ export class OAuth2Client implements AuthClient {
408
407
  return Promise.reject(responseError)
409
408
  }
410
409
 
411
- if (
412
- requestTime === retry
413
- || !responseError
414
- || responseError.error !== 'unreachable'
415
- ) {
410
+ if (requestTime === retry || !responseError || responseError.error !== 'unreachable') {
416
411
  return Promise.reject(responseError)
417
412
  }
418
413
  }
@@ -421,6 +416,46 @@ export class OAuth2Client implements AuthClient {
421
416
  return response
422
417
  }
423
418
 
419
+ public async wxCloudCallFunction<T>(
420
+ url: string,
421
+ options?: RequestOptions,
422
+ ): Promise<T> {
423
+ let result: T | null = null
424
+ let responseError: ResponseError | null = null
425
+ try {
426
+ const { result: responseResult } = await this.wxCloud.callFunction({
427
+ name: 'httpOverCallFunction',
428
+ data: {
429
+ url,
430
+ method: options.method,
431
+ headers: {
432
+ origin: 'https://servicewechat.com',
433
+ ...options.headers,
434
+ },
435
+ body: options.body,
436
+ },
437
+ })
438
+
439
+ if (responseResult?.body?.error_code) {
440
+ responseError = responseResult?.body as ResponseError
441
+ responseError.error_uri = getPathName(url)
442
+ } else {
443
+ result = responseResult?.body as T
444
+ }
445
+ } catch (error) {
446
+ responseError = {
447
+ error: ErrorType.UNREACHABLE,
448
+ error_description: error.message,
449
+ error_uri: getPathName(url),
450
+ }
451
+ }
452
+
453
+ if (responseError) {
454
+ throw responseError
455
+ } else {
456
+ return result
457
+ }
458
+ }
424
459
 
425
460
  /**
426
461
  * Get credentials.
@@ -431,7 +466,7 @@ export class OAuth2Client implements AuthClient {
431
466
  if (credentials && credentials.scope === 'anonymous') {
432
467
  if (this.anonymousSignInFunc) {
433
468
  const c = await this.anonymousSignInFunc(credentials)
434
- credentials = c || await this.localCredentials.getCredentials()
469
+ credentials = c || (await this.localCredentials.getCredentials())
435
470
  } else {
436
471
  credentials = await this.anonymousSignIn(credentials)
437
472
  }
@@ -501,11 +536,7 @@ export class OAuth2Client implements AuthClient {
501
536
  */
502
537
  private checkRetry(retry: number): number {
503
538
  let responseError: ResponseError | null = null
504
- if (
505
- typeof retry !== 'number'
506
- || retry < OAuth2Client.minRetry
507
- || retry > OAuth2Client.maxRetry
508
- ) {
539
+ if (typeof retry !== 'number' || retry < OAuth2Client.minRetry || retry > OAuth2Client.maxRetry) {
509
540
  responseError = {
510
541
  error: ErrorType.UNREACHABLE,
511
542
  error_description: 'wrong options param: retry',
@@ -609,10 +640,8 @@ export class OAuth2Client implements AuthClient {
609
640
  if (this.deviceID) {
610
641
  return this.deviceID
611
642
  }
612
- let deviceId: string = await this.storage.getItem(DeviceIdSectionName,)
613
- if (!(typeof deviceId === 'string'
614
- && deviceId.length >= 16
615
- && deviceId.length <= 48)) {
643
+ let deviceId: string = await this.storage.getItem(DeviceIdSectionName)
644
+ if (!(typeof deviceId === 'string' && deviceId.length >= 16 && deviceId.length <= 48)) {
616
645
  deviceId = uuidv4()
617
646
  await this.storage.setItem(DeviceIdSectionName, deviceId)
618
647
  }
@@ -17,9 +17,7 @@ export const deepClone = (value: any) => {
17
17
  return copiedValue
18
18
  }
19
19
 
20
- const type = value === null || value === undefined
21
- ? 'NullOrUndefined'
22
- : Object.prototype.toString.call(value).slice(8, -1)
20
+ const type = value === null || value === undefined ? 'NullOrUndefined' : Object.prototype.toString.call(value).slice(8, -1)
23
21
 
24
22
  if (
25
23
  [
@@ -59,3 +57,15 @@ export const deepClone = (value: any) => {
59
57
  return value
60
58
  }
61
59
  }
60
+
61
+ export const getPathName = (url: string) => {
62
+ // eslint-disable-next-line no-useless-escape
63
+ const regex = /^(?:http(s)?:\/\/[^\/]+)?(\/[^\?#]*)/
64
+ const match = url.match(regex)
65
+
66
+ if (match) {
67
+ return match[2] || ''
68
+ }
69
+
70
+ return ''
71
+ }