@cloudbase/auth 1.7.3-alpha.0 → 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 (56) hide show
  1. package/dist/cjs/index.d.ts +50 -101
  2. package/dist/cjs/index.js +415 -778
  3. package/dist/esm/index.d.ts +50 -101
  4. package/dist/esm/index.js +416 -775
  5. package/package.json +52 -54
  6. package/src/index.ts +401 -766
  7. package/dist/cjs/common.d.ts +0 -8
  8. package/dist/cjs/common.js +0 -64
  9. package/dist/cjs/constants.d.ts +0 -12
  10. package/dist/cjs/constants.js +0 -17
  11. package/dist/cjs/providers/anonymousAuthProvider.d.ts +0 -15
  12. package/dist/cjs/providers/anonymousAuthProvider.js +0 -256
  13. package/dist/cjs/providers/base.d.ts +0 -21
  14. package/dist/cjs/providers/base.js +0 -152
  15. package/dist/cjs/providers/customAuthProvider.d.ts +0 -5
  16. package/dist/cjs/providers/customAuthProvider.js +0 -150
  17. package/dist/cjs/providers/emailAuthProvider.d.ts +0 -9
  18. package/dist/cjs/providers/emailAuthProvider.js +0 -250
  19. package/dist/cjs/providers/oauth2AuthProvider.d.ts +0 -61
  20. package/dist/cjs/providers/oauth2AuthProvider.js +0 -404
  21. package/dist/cjs/providers/phoneAuthProvider.d.ts +0 -17
  22. package/dist/cjs/providers/phoneAuthProvider.js +0 -219
  23. package/dist/cjs/providers/usernameAuthProvider.d.ts +0 -5
  24. package/dist/cjs/providers/usernameAuthProvider.js +0 -169
  25. package/dist/cjs/providers/weixinAuthProvider.d.ts +0 -28
  26. package/dist/cjs/providers/weixinAuthProvider.js +0 -294
  27. package/dist/esm/common.d.ts +0 -8
  28. package/dist/esm/common.js +0 -61
  29. package/dist/esm/constants.d.ts +0 -12
  30. package/dist/esm/constants.js +0 -14
  31. package/dist/esm/providers/anonymousAuthProvider.d.ts +0 -15
  32. package/dist/esm/providers/anonymousAuthProvider.js +0 -253
  33. package/dist/esm/providers/base.d.ts +0 -21
  34. package/dist/esm/providers/base.js +0 -149
  35. package/dist/esm/providers/customAuthProvider.d.ts +0 -5
  36. package/dist/esm/providers/customAuthProvider.js +0 -147
  37. package/dist/esm/providers/emailAuthProvider.d.ts +0 -9
  38. package/dist/esm/providers/emailAuthProvider.js +0 -247
  39. package/dist/esm/providers/oauth2AuthProvider.d.ts +0 -61
  40. package/dist/esm/providers/oauth2AuthProvider.js +0 -401
  41. package/dist/esm/providers/phoneAuthProvider.d.ts +0 -17
  42. package/dist/esm/providers/phoneAuthProvider.js +0 -216
  43. package/dist/esm/providers/usernameAuthProvider.d.ts +0 -5
  44. package/dist/esm/providers/usernameAuthProvider.js +0 -166
  45. package/dist/esm/providers/weixinAuthProvider.d.ts +0 -28
  46. package/dist/esm/providers/weixinAuthProvider.js +0 -291
  47. package/src/common.ts +0 -21
  48. package/src/constants.ts +0 -13
  49. package/src/providers/anonymousAuthProvider.ts +0 -126
  50. package/src/providers/base.ts +0 -78
  51. package/src/providers/customAuthProvider.ts +0 -69
  52. package/src/providers/emailAuthProvider.ts +0 -142
  53. package/src/providers/oauth2AuthProvider.ts +0 -585
  54. package/src/providers/phoneAuthProvider.ts +0 -132
  55. package/src/providers/usernameAuthProvider.ts +0 -77
  56. package/src/providers/weixinAuthProvider.ts +0 -193
@@ -1,132 +0,0 @@
1
- import { constants, utils, helpers } from '@cloudbase/utilities';
2
- import { ILoginState } from '@cloudbase/types/auth';
3
- import { AuthProvider } from './base';
4
- import { LOGINTYPE } from '../constants';
5
- import { eventBus, EVENTS, LoginState } from '..';
6
-
7
- const { throwError, isString, transformPhone } = utils;
8
- const { ERRORS, COMMUNITY_SITE_URL } = constants;
9
- const { catchErrorsDecorator, stopAuthLoginWithOAuth } = helpers;
10
-
11
- export const SIGN_METHOD = {
12
- SIGNIN: 'SIGNIN',
13
- SIGNUP: 'SIGNUP',
14
- FORCERESETPWD: 'FORCERESETPWD'
15
- }
16
-
17
- export class PhoneAuthProvider extends AuthProvider {
18
- @stopAuthLoginWithOAuth()
19
- @catchErrorsDecorator({
20
- title: '手机号登录失败',
21
- messages: [
22
- '请确认以下各项:',
23
- ' 1 - 调用 auth().SmsAuthProvider() 的语法或参数是否正确',
24
- ' 2 - 当前环境是否开通了短信验证码登录',
25
- ' 3 - 短信验证码/密码是否正确',
26
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
27
- ]
28
- })
29
- public async signIn(param: {
30
- phoneNumber: string
31
- phoneCode?: string
32
- password?: string
33
- signMethod?: string
34
- }): Promise<ILoginState> {
35
- let { phoneNumber, phoneCode, password, signMethod } = param
36
- if (!isString(phoneNumber)) {
37
- throwError(ERRORS.INVALID_PARAMS, 'phoneNumber must be a string');
38
- }
39
-
40
- if (!isString(phoneCode) && !isString(password)) {
41
- throwError(ERRORS.INVALID_PARAMS, 'phoneCode or password must be a string');
42
- }
43
-
44
- if (!signMethod) {
45
- signMethod = SIGN_METHOD.SIGNIN
46
- }
47
-
48
- const { refreshTokenKey } = this._cache.keys;
49
- const res = await this._request.send('auth.signIn', {
50
- loginType: LOGINTYPE.PHONE,
51
- phoneNumber: transformPhone(phoneNumber),
52
- phoneCode,
53
- password,
54
- refresh_token: this._cache.getStore(refreshTokenKey) || '',
55
- signMethod
56
- });
57
- const { refresh_token, access_token, access_token_expire } = res;
58
- if (refresh_token) {
59
- await this.setRefreshToken(refresh_token);
60
- if (access_token && access_token_expire) {
61
- await this.setAccessToken(access_token, access_token_expire);
62
- } else {
63
- await this._request.refreshAccessToken();
64
- }
65
- // set user info
66
- await this.refreshUserInfo();
67
- eventBus.fire(EVENTS.LOGIN_STATE_CHANGED);
68
- eventBus.fire(EVENTS.LOGIN_TYPE_CHANGED, {
69
- env: this._config.env,
70
- loginType: LOGINTYPE.PHONE,
71
- persistence: this._config.persistence
72
- });
73
- return new LoginState({
74
- envId: this._config.env,
75
- cache: this._cache,
76
- request: this._request
77
- });
78
- } else if (res.code) {
79
- throwError(ERRORS.OPERATION_FAIL, `Phone login fail[${res.code}] ${res.message}`);
80
- } else {
81
- throwError(ERRORS.OPERATION_FAIL, `Phone login fail`);
82
- }
83
- }
84
- /**
85
- * 手机号注册
86
- * @param phoneNumber
87
- * @param phoneCode
88
- * @param password
89
- */
90
- @stopAuthLoginWithOAuth()
91
- @catchErrorsDecorator({
92
- title: '手机短信注册失败',
93
- messages: [
94
- '请确认以下各项:',
95
- ' 1 - 调用 auth().signUpWithPhoneCode() 的语法或参数是否正确',
96
- ' 2 - 当前环境是否开通了短信验证码登录',
97
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
98
- ]
99
- })
100
- public async signUp(phoneNumber: string, phoneCode: string, password?: string): Promise<ILoginState> {
101
- return this.signIn({
102
- phoneNumber,
103
- phoneCode,
104
- password,
105
- signMethod: SIGN_METHOD.SIGNUP
106
- })
107
- }
108
-
109
- /**
110
- * 手机号注册
111
- * @param phoneNumber
112
- * @param phoneCode
113
- * @param password
114
- */
115
- @catchErrorsDecorator({
116
- title: '手机密码重置失败',
117
- messages: [
118
- '请确认以下各项:',
119
- ' 1 - 调用 auth().forceResetPwd() 的语法或参数是否正确',
120
- ' 2 - 当前环境是否开通了短信验证码登录',
121
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
122
- ]
123
- })
124
- public async forceResetPwd(phoneNumber: string, phoneCode: string, password: string): Promise<ILoginState> {
125
- return this.signIn({
126
- phoneNumber,
127
- phoneCode,
128
- password,
129
- signMethod: SIGN_METHOD.FORCERESETPWD
130
- })
131
- }
132
- }
@@ -1,77 +0,0 @@
1
- import { AuthProvider } from './base';
2
- import { ILoginState } from '@cloudbase/types/auth';
3
- import { eventBus, EVENTS, LoginState } from '..';
4
- import { LOGINTYPE } from '../constants';
5
- import { utils, constants, helpers } from '@cloudbase/utilities';
6
-
7
- const { printWarn } = utils;
8
- const { ERRORS, COMMUNITY_SITE_URL } = constants;
9
- const { catchErrorsDecorator, stopAuthLoginWithOAuth } = helpers;
10
-
11
- export class UsernameAuthProvider extends AuthProvider {
12
- @stopAuthLoginWithOAuth()
13
- @catchErrorsDecorator({
14
- title: '用户名密码登录失败',
15
- messages: [
16
- '请确认以下各项:',
17
- ' 1 - 调用 auth().signInWithUsernameAndPassword() 的语法或参数是否正确',
18
- ' 2 - 当前环境是否开通了用户名密码登录',
19
- ' 3 - 用户名密码是否匹配',
20
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
21
- ]
22
- })
23
- public async signIn(username: string, password: string): Promise<ILoginState> {
24
- if (typeof username !== 'string') {
25
- throw new Error(JSON.stringify({
26
- code: ERRORS.INVALID_PARAMS,
27
- msg: 'username must be a string'
28
- }));
29
- }
30
- // 用户不设置密码
31
- if (typeof password !== 'string') {
32
- password = '';
33
- printWarn(ERRORS.INVALID_PARAMS, 'password is empty');
34
- }
35
-
36
- const { refreshTokenKey } = this._cache.keys;
37
- const res = await this._request.send('auth.signIn', {
38
- loginType: LOGINTYPE.USERNAME,
39
- username,
40
- password,
41
- refresh_token: await this._cache.getStoreAsync(refreshTokenKey) || ''
42
- });
43
-
44
- const { refresh_token, access_token_expire, access_token } = res;
45
- if (refresh_token) {
46
- await this.setRefreshToken(refresh_token);
47
- if (access_token && access_token_expire) {
48
- await this.setAccessToken(access_token, access_token_expire);
49
- } else {
50
- await this._request.refreshAccessToken();
51
- }
52
- // set user info
53
- await this.refreshUserInfo();
54
- eventBus.fire(EVENTS.LOGIN_STATE_CHANGED);
55
- eventBus.fire(EVENTS.LOGIN_TYPE_CHANGED, {
56
- env: this._config.env,
57
- loginType: LOGINTYPE.USERNAME,
58
- persistence: this._config.persistence
59
- });
60
- return new LoginState({
61
- envId: this._config.env,
62
- cache: this._cache,
63
- request: this._request
64
- });
65
- } else if (res.code) {
66
- throw new Error(JSON.stringify({
67
- code: ERRORS.OPERATION_FAIL,
68
- msg: `login by username failed:[${res.code}] ${res.message}`
69
- }));
70
- } else {
71
- throw new Error(JSON.stringify({
72
- code: ERRORS.OPERATION_FAIL,
73
- msg: 'login by username failed'
74
- }));
75
- }
76
- }
77
- }
@@ -1,193 +0,0 @@
1
- import { AuthProvider } from './base';
2
- import { ICloudbaseAuthConfig } from '@cloudbase/types/auth';
3
- import { ICloudbaseCache } from '@cloudbase/types/cache';
4
- import { ICloudbaseRequest } from '@cloudbase/types/request';
5
- import { constants, adapters,utils, helpers } from '@cloudbase/utilities/';
6
- import { eventBus, EVENTS, LoginState } from '..';
7
- import { LOGINTYPE } from '../constants';
8
-
9
- const { getSdkName, ERRORS, COMMUNITY_SITE_URL } = constants;
10
- const { RUNTIME } = adapters;
11
- const { getQuery, getHash, removeParam, printWarn } = utils;
12
- const { catchErrorsDecorator } = helpers;
13
-
14
- export class WeixinAuthProvider extends AuthProvider {
15
- private readonly _scope: string;
16
- private readonly _state: string;
17
- private readonly _appid: string;
18
- private readonly _runtime:string;
19
-
20
- constructor(config: ICloudbaseAuthConfig&{cache:ICloudbaseCache,request:ICloudbaseRequest,runtime:string}, appid: string, scope: string, state?: string) {
21
- super(config);
22
-
23
- this._runtime = config.runtime;
24
- this._appid = appid;
25
- this._scope = scope;
26
- this._state = state || 'weixin';
27
- }
28
-
29
- public async signIn(){
30
- return printWarn(ERRORS.OPERATION_FAIL,'API signIn has been deprecated, please use signInWithRedirect insteed');
31
- }
32
- @catchErrorsDecorator({
33
- title: '跳转微信公众号授权失败',
34
- messages: [
35
- '请确认以下各项:',
36
- ' 1 - 调用 auth().weixinAuthProvider().signInWithRedirect() 的语法或参数是否正确',
37
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
38
- ]
39
- })
40
- public async signInWithRedirect() {
41
- return this._redirect();
42
- }
43
- @catchErrorsDecorator({
44
- title: '微信公众号登录失败',
45
- messages: [
46
- '请确认以下各项:',
47
- ' 1 - 调用 auth().weixinAuthProvider().getRedirectResult() 的语法或参数是否正确',
48
- ' 2 - 当前环境是否开通了微信公众号登录授权',
49
- ' 3 - 微信公众号的 AppId 与 AppSecret 配置是否正确',
50
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
51
- ]
52
- })
53
- public async getRedirectResult(options:{ withUnionId?: boolean; syncUserInfo?: boolean }) {
54
- const code = getWeixinCode();
55
- if (!code) {
56
- return null;
57
- }
58
- return this._signInWithCode(code,options);
59
- }
60
- @catchErrorsDecorator({
61
- title: '获取微信重定向绑定结果',
62
- messages: [
63
- '请确认以下各项:',
64
- ' 1 - 调用 auth().weixinAuthProvider().getLinkRedirectResult() 的语法或参数是否正确',
65
- ' 2 - 当前环境是否开通了微信公众号登录授权',
66
- ' 3 - 微信公众号的 AppId 与 AppSecret 配置是否正确',
67
- `如果问题依然存在,建议到官方问答社区提问或寻找帮助:${COMMUNITY_SITE_URL}`
68
- ]
69
- })
70
- async getLinkRedirectResult(options: { withUnionId?: boolean } = {}) {
71
- const { withUnionId = false } = options;
72
- const code = getWeixinCode();
73
- if (!code) {
74
- return null;
75
- }
76
- const { _appid: appid } = this;
77
- const loginType = (scope => {
78
- switch (scope) {
79
- case 'snsapi_login':
80
- return 'WECHAT-OPEN';
81
- default:
82
- return 'WECHAT-PUBLIC';
83
- }
84
- })(this._scope);
85
- const hybridMiniapp = this._runtime === RUNTIME.WX_MP ? '1' : '0';
86
- return this._request.send('auth.linkWithWeixinCode', {
87
- payload: {
88
- appid,
89
- loginType,
90
- code,
91
- hybridMiniapp,
92
- withUnionId
93
- }
94
- });
95
- }
96
-
97
- private _redirect(): any {
98
- let currUrl = removeParam('code', location.href);
99
- currUrl = removeParam('state', currUrl);
100
- currUrl = encodeURIComponent(currUrl);
101
-
102
- let host = '//open.weixin.qq.com/connect/oauth2/authorize';
103
- if (this._scope === 'snsapi_login') {
104
- host = '//open.weixin.qq.com/connect/qrconnect';
105
- }
106
- try{
107
- location.href = `${host}?appid=${this._appid}&redirect_uri=${currUrl}&response_type=code&scope=${this._scope}&state=${this._state}#wechat_redirect`;
108
- }catch(e){
109
- throw new Error(`[${getSdkName()}][${ERRORS.UNKOWN_ERROR}]${e}`)
110
- }
111
- }
112
-
113
- private async _signInWithCode(code:string,options) {
114
- const { accessTokenKey, accessTokenExpireKey, refreshTokenKey } = this._cache.keys;
115
- // 有code,用code换refresh token
116
- const loginType = (scope => {
117
- switch (scope) {
118
- case 'snsapi_login':
119
- return 'WECHAT-OPEN';
120
- default:
121
- return 'WECHAT-PUBLIC';
122
- }
123
- })(this._scope);
124
-
125
- const refreshTokenRes = await this._getRefreshTokenByWXCode(this._appid, loginType, code,options);
126
- const { refreshToken } = refreshTokenRes;
127
-
128
- // 本地存下
129
- await this._cache.setStoreAsync(refreshTokenKey, refreshToken);
130
- if (refreshTokenRes.accessToken) {
131
- await this._cache.setStoreAsync(accessTokenKey, refreshTokenRes.accessToken);
132
- }
133
- if (refreshTokenRes.accessTokenExpire) {
134
- await this._cache.setStoreAsync(accessTokenExpireKey, String(refreshTokenRes.accessTokenExpire + Date.now()));
135
- }
136
- eventBus.fire(EVENTS.LOGIN_STATE_CHANGED);
137
- // 抛出登录类型更改事件
138
- eventBus.fire(EVENTS.LOGIN_TYPE_CHANGED, {
139
- env: this._config.env,
140
- loginType: LOGINTYPE.WECHAT,
141
- persistence: this._config.persistence
142
- });
143
- await this.refreshUserInfo();
144
- const loginState = new LoginState({
145
- envId: this._config.env,
146
- cache: this._cache,
147
- request: this._request
148
- });
149
- await loginState.checkLocalStateAsync();
150
-
151
- return loginState;
152
- }
153
-
154
- private async _getRefreshTokenByWXCode(
155
- appid: string,
156
- loginType: string,
157
- code: string,
158
- options: any = {}
159
- ): Promise<{ refreshToken: string; accessToken: string; accessTokenExpire: number }> {
160
- const { withUnionId = false, createUser = true } = options;
161
- // snsapi_userinfo 和 snsapi_login 才可以获取用户的微信信息
162
- const syncUserInfo = this._scope === 'snsapi_base' ? false : options.syncUserInfo || false;
163
-
164
- const action = 'auth.signIn';
165
- const hybridMiniapp = this._runtime === RUNTIME.WX_MP ? '1' : '0';
166
- return this._request.send(action, {
167
- appid,
168
- loginType,
169
- hybridMiniapp,
170
- syncUserInfo,
171
- loginCredential: code,
172
- withUnionId,
173
- createUser
174
- }).then(res => {
175
- if (res.code) {
176
- throw new Error(`[${getSdkName()}][${ERRORS.OPERATION_FAIL}] failed login via wechat: ${res.code}`);
177
- }
178
- if (res.refresh_token) {
179
- return {
180
- refreshToken: res.refresh_token,
181
- accessToken: res.access_token,
182
- accessTokenExpire: res.access_token_expire
183
- };
184
- } else {
185
- throw new Error(`[${getSdkName()}][${ERRORS.OPERATION_FAIL}] action:getJwt not return refreshToken`);
186
- }
187
- });
188
- }
189
- }
190
-
191
- function getWeixinCode () {
192
- return getQuery('code') || getHash('code');
193
- };