@authing/guard-shim-react18 5.0.8-alpha.0 → 5.0.8-alpha.10

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.
package/package.json CHANGED
@@ -1,11 +1,15 @@
1
1
  {
2
2
  "name": "@authing/guard-shim-react18",
3
- "version": "5.0.8-alpha.0",
3
+ "version": "5.0.8-alpha.10",
4
4
  "description": "Guard shim for react18",
5
- "main": "src/index.tsx",
5
+ "module": "dist/esm/guard.min.js",
6
+ "types": "dist/typings/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
6
10
  "scripts": {
7
11
  "autoinstall": "npm ci",
8
- "build": "echo 'No need to build @authing/guard-shim-react18'",
12
+ "build": "node scripts/build.js",
9
13
  "lint": "eslint --ext .ts,.tsx src/**",
10
14
  "lint:fix": "eslint --fix --ext .ts,.tsx src/**",
11
15
  "release:official": "npm publish --verbose --access public",
@@ -21,10 +25,9 @@
21
25
  "webpack": "^5.72.0"
22
26
  },
23
27
  "dependencies": {
24
- "@authing/react18-components": "^4.1.0-alpha.0",
25
- "axios": "^0.27.2",
26
- "react": "^18.2.0",
27
- "react-dom": "^18.2.0"
28
+ "@authing/react18-ui-components": "^4.1.0-alpha.2",
29
+ "react": "^18.0.0",
30
+ "react-dom": "^18.0.0"
28
31
  },
29
32
  "author": "https://github.com/authing",
30
33
  "license": "MIT",
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2019 Authing
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
package/README.md DELETED
@@ -1,137 +0,0 @@
1
- <div align=center>
2
- <img width="300" src="https://files.authing.co/authing-console/authing-logo-new-20210924.svg" />
3
- </div>
4
-
5
- <br />
6
-
7
- English | [简体中文](./README.zh_CN.md)
8
-
9
- <br />
10
-
11
- Guard is a portable authentication component provided by authing. You can embed it in any application to handle complex user authentication processes in one stop.
12
-
13
- Prepare your native JavaScript project and follow the guide to connect Guard to your native JavaScript project!
14
-
15
- ## Install
16
-
17
- From CDN:
18
-
19
- ``` html
20
- <link rel="stylesheet" href="https://cdn.authing.co/packages/guard/5.0.7/guard.min.css" />
21
- <script src="https://cdn.authing.co/packages/guard/5.0.7/guard.min.js"></script>
22
- ```
23
-
24
- From NPM:
25
-
26
- ``` shell
27
- npm install --save @authing/guard
28
- ```
29
-
30
- ## Initialize
31
-
32
- |Key|Type|Default|Requires
33
- |-----|----|----|----|
34
- |appId|String| - |Y|
35
- |mode|normal / modal|normal|N|
36
- |defaultScene|GuardModuleType|login|N|
37
- |align|none / left / center / right | none | N | Guard default position|
38
- |lang|zh-CN / en-US|zh-CN|N|
39
- |isSSO|Boolean|true|N|
40
- |host|String| - |N|
41
- |scope|String| - |N|
42
- |redirectUri|String| - |N|
43
- |state|String| - |N|
44
-
45
-
46
- ``` javascript
47
- // From CDN
48
- const guard = new GuardFactory.Guard({
49
- appId: '62e22721c889dd44bad1dda2',
50
- host: 'https://guard-test-2022.authing.cn',
51
- redirectUri: 'http://localhost:3000/callback'
52
- })
53
-
54
- // From npm
55
- const guard = new Guard({
56
- appId: '62e22721c889dd44bad1dda2',
57
- host: 'https://guard-test-2022.authing.cn',
58
- redirectUri: 'http://localhost:3000/callback'
59
- })
60
- ```
61
-
62
- ## Guard provides three login modes
63
-
64
- ### Embed mode
65
-
66
- Render Guard component
67
-
68
- ``` javascript
69
- guard.start('#root').then(userInfo => {
70
- console.log(userInfo)
71
- })
72
- ```
73
-
74
- ### modal mode
75
-
76
- When the parameter 'mode' of Guard instantiation is' modal ', the modal mode is started, and the following API can be used to display and hide the guard.
77
-
78
- ``` javascript
79
- guard.show()
80
- ```
81
-
82
- ``` javascript
83
- guard.hide()
84
- ```
85
-
86
- ### Redirect mode
87
-
88
- Login by code, redirect to login page
89
-
90
- ``` javascript
91
- guard.startWithRedirect()
92
- ```
93
-
94
- Auto handle redirect callback
95
-
96
- ``` javascript
97
- guard.handleRedirectCallback()
98
- ```
99
-
100
- Logout
101
-
102
- ``` javascript
103
- guard.logout()
104
- ```
105
-
106
- ## Regist events
107
-
108
- ``` javascript
109
- guard.on('load', e => {
110
- console.log(e)
111
- })
112
-
113
- guard.on('login', userInfo => {
114
- console.log(userInfo)
115
- })
116
-
117
- // ......
118
- ```
119
-
120
- ## Integrate authing js sdk instance
121
-
122
- Guard integrated AuthenticationClient, so you can access all apis of AuthenticationClient, etc:
123
-
124
- ``` javascript
125
- guard.getAuthClient().then(authClient => {
126
- authClient.registerByEmail()
127
- authClient.validateToken()
128
- // .........
129
- })
130
- // ....
131
- ```
132
-
133
- Refer to [Authentication SDK](https://docs.authing.cn/v2/reference/sdk-for-node/authentication/)
134
-
135
- ## Documentation
136
-
137
- To check out live examples and docs, visit [docs](https://docs.authing.cn/v2/reference/guard/v3/mpa.html)
package/README.zh_CN.md DELETED
@@ -1,137 +0,0 @@
1
- <div align=center>
2
- <img width="300" src="https://files.authing.co/authing-console/authing-logo-new-20210924.svg" />
3
- </div>
4
-
5
- <br />
6
-
7
- 简体中文 | [English](./README.md)
8
-
9
- <br />
10
-
11
- Guard 是 Authing 提供的一种轻便的认证组件,你可以把它嵌入在你任何的 SPA(Single Page Application)应用中,一站式处理复杂的用户认证流程。
12
-
13
- 准备好你的 原生 JavaScript 项目,跟随引导将 Guard 接入到你的 原生 JavaScript 项目中吧!
14
-
15
- ## 安装
16
-
17
- 使用 CDN:
18
-
19
- ``` html
20
- <link rel="stylesheet" src="https://cdn.authing.co/packages/guard/5.0.0/guard.min.css" />
21
- <script src="https://cdn.authing.co/packages/guard/5.0.0/guard.min.js"></script>
22
- ```
23
-
24
- 使用 NPM:
25
-
26
- ``` shell
27
- npm install --save @authing/guard
28
- ```
29
-
30
- ## 初始化
31
-
32
- |字段|类型|默认是|必传
33
- |-----|----|----|----|
34
- |appId|String| - |是|
35
- |mode|normal / modal|normal|否|
36
- |defaultScene|GuardModuleType|login|否|
37
- | align |none / left / center / right | none | 否 |
38
- |lang|zh-CN / en-US|zh-CN|否|
39
- |isSSO|Boolean|true|否|
40
- |host|String| - |否|
41
- |scope|String| - |否|
42
- |redirectUri|String| - |否|
43
- |state|String| - |否|
44
-
45
-
46
- ``` javascript
47
- // 使用 CDN
48
- const guard = new GuardFactory.Guard({
49
- appId: '62e22721c889dd44bad1dda2',
50
- host: 'https://guard-test-2022.authing.cn',
51
- redirectUri: 'http://localhost:3000/callback'
52
- })
53
-
54
- // 使用 npm
55
- const guard = new Guard({
56
- appId: '62e22721c889dd44bad1dda2',
57
- host: 'https://guard-test-2022.authing.cn',
58
- redirectUri: 'http://localhost:3000/callback'
59
- })
60
- ```
61
-
62
- ## Guard 提供三种登录模式
63
-
64
- ### 嵌入模式
65
-
66
- 渲染 Guard 组件
67
-
68
- ``` javascript
69
- guard.start('#root').then(userInfo => {
70
- console.log(userInfo)
71
- })
72
- ```
73
-
74
- ### 弹窗模式
75
-
76
- 当 Guard 实例化的参数 `mode` 为 `modal` 时,将启动模态模式,下面的 API 可用于显示和隐藏 Guard。
77
-
78
- ``` javascript
79
- guard.show()
80
- ```
81
-
82
- ``` javascript
83
- guard.hide()
84
- ```
85
-
86
- ### 跳转模式
87
-
88
- 使用 code 码登录,跳转到登录页面
89
-
90
- ``` javascript
91
- guard.startWithRedirect()
92
- ```
93
-
94
- code 换 token,自动处理页面重定向
95
-
96
- ``` javascript
97
- guard.handleRedirectCallback()
98
- ```
99
-
100
- 登出
101
-
102
- ``` javascript
103
- guard.logout()
104
- ```
105
-
106
- ## 注册事件
107
-
108
- ``` javascript
109
- guard.on('load', e => {
110
- console.log(e)
111
- })
112
-
113
- guard.on('login', userInfo => {
114
- console.log(userInfo)
115
- })
116
-
117
- // ......
118
- ```
119
-
120
- ## 集成 Authing JS SDK
121
-
122
- Guard 集成了 AuthenticationClient,所以你可以访问 AuthenticationClient 的所有 api 等等:
123
-
124
- ``` javascript
125
- guard.getAuthClient().then(authClient => {
126
- authClient.registerByEmail()
127
- authClient.validateToken()
128
- // .........
129
- })
130
- // ....
131
- ```
132
-
133
- 参考 [Authentication SDK](https://docs.authing.cn/v2/reference/sdk-for-node/authentication/)
134
-
135
- ## 文档
136
-
137
- 参考详细文档说明 [docs](https://docs.authing.cn/v2/reference/guard/v3/mpa.html)
package/scripts/build.js DELETED
@@ -1,26 +0,0 @@
1
- const path = require('path')
2
- const rm = require('rimraf')
3
- const webpack = require('webpack')
4
- const webpackEsmBundlerConfig = require('./webpack.esm.config')
5
- const webpackGlobalConfig = require('./webpack.global.config')
6
-
7
- try {
8
- rm.sync(path.resolve(__dirname, '../', 'dist'))
9
- } catch (e) {
10
- console.error('\n\n build guard, failed to delete dist directory, please operate manually \n\n')
11
- }
12
-
13
- readyGo()
14
-
15
- function readyGo () {
16
- webpack(webpackEsmBundlerConfig, (error) => {
17
- if (error) {
18
- console.error('build guard.js esm bundler error: ', error)
19
- }
20
- })
21
- webpack(webpackGlobalConfig, (error) => {
22
- if (error) {
23
- console.error('build guard.js global error: ', error)
24
- }
25
- })
26
- }
@@ -1,42 +0,0 @@
1
- const path = require('path')
2
- const MiniCssExtractPlugin = require('mini-css-extract-plugin')
3
-
4
- function resolve (dir, file = '') {
5
- return path.resolve(__dirname, '../', dir, file)
6
- }
7
-
8
- module.exports = {
9
- mode: 'production',
10
- entry: resolve('src/index.tsx'),
11
- output: {
12
- filename: 'guard.min.js',
13
- path: resolve('dist/esm'),
14
- library: {
15
- type: 'module'
16
- }
17
- },
18
- experiments: {
19
- outputModule: true
20
- },
21
- resolve: {
22
- extensions: ['.ts', '.tsx', '.js']
23
- },
24
- module: {
25
- rules: [
26
- {
27
- test: /\.css$/,
28
- use: [MiniCssExtractPlugin.loader, 'css-loader']
29
- },
30
- {
31
- test: /\.tsx?$/,
32
- use: 'ts-loader',
33
- exclude: /node_modules/
34
- }
35
- ]
36
- },
37
- plugins: [
38
- new MiniCssExtractPlugin({
39
- filename: 'guard.min.css'
40
- })
41
- ]
42
- }
@@ -1,40 +0,0 @@
1
- const path = require('path')
2
- const MiniCssExtractPlugin = require('mini-css-extract-plugin')
3
-
4
- function resolve (dir, file = '') {
5
- return path.resolve(__dirname, '../', dir, file)
6
- }
7
-
8
- module.exports = {
9
- mode: 'production',
10
- entry: resolve('src/index.tsx'),
11
- output: {
12
- filename: 'guard.min.js',
13
- path: resolve('dist/global'),
14
- library: {
15
- name: 'GuardFactory',
16
- type: 'global'
17
- }
18
- },
19
- resolve: {
20
- extensions: ['.ts', '.tsx', '.js']
21
- },
22
- module: {
23
- rules: [
24
- {
25
- test: /\.css$/,
26
- use: [MiniCssExtractPlugin.loader, 'css-loader']
27
- },
28
- {
29
- test: /\.tsx?$/,
30
- use: 'ts-loader',
31
- exclude: /node_modules/
32
- }
33
- ]
34
- },
35
- plugins: [
36
- new MiniCssExtractPlugin({
37
- filename: 'guard.min.css'
38
- })
39
- ]
40
- }
package/src/index.tsx DELETED
@@ -1,513 +0,0 @@
1
- import React from 'react'
2
-
3
- import { createRoot } from 'react-dom/client'
4
-
5
- import {
6
- GuardOptions,
7
- GuardMode,
8
- GuardEventsCamelToKebabMapping,
9
- GuardLocalConfig,
10
- GuardEventListeners,
11
- GuardEvents,
12
- Guard as ReactAuthingGuard,
13
- GuardEventsKebabToCamelType,
14
- StartWithRedirectOptions,
15
- AuthenticationClient,
16
- JwtTokenStatus,
17
- User,
18
- GuardModuleType,
19
- Lang,
20
- IGuardConfig
21
- } from './types'
22
-
23
- import '@authing/react18-components/lib/index.min.css'
24
-
25
- export * from './types'
26
-
27
- const isDef = (value: unknown) => value !== undefined
28
-
29
- export class Guard {
30
- public options: GuardOptions
31
-
32
- private visible = false
33
-
34
- private then: () => Promise<any | never>
35
-
36
- private publicConfig?: Record<string, unknown>
37
-
38
- constructor(options: GuardOptions) {
39
- if (!options.appId) {
40
- throw new Error('appId is required')
41
- }
42
-
43
- const config = {
44
- ...options.config
45
- }
46
-
47
- this.options = this.adaptOptions(options, config)
48
-
49
- const init = (async () => {
50
- if (this.publicConfig) {
51
- return this.publicConfig
52
- }
53
-
54
- const publicConfigRes = await this.getPublicConfig()
55
-
56
- return (this.publicConfig = publicConfigRes.data)
57
- })()
58
-
59
- this.then = init.then.bind(init)
60
-
61
- this.visible = !!(options.mode === GuardMode.Modal)
62
- }
63
-
64
- private adaptOptions(options: GuardOptions, config: Partial<IGuardConfig>) {
65
- options.host = options.host || ''
66
-
67
- if (isDef(options.isSSO)) {
68
- config.isSSO = options.isSSO
69
- }
70
-
71
- if (isDef(options.defaultScene)) {
72
- // @ts-ignore
73
- config.defaultScenes = options.defaultScene
74
- }
75
-
76
- if (isDef(options.lang)) {
77
- config.lang = options.lang
78
- }
79
-
80
- if (isDef(options.host)) {
81
- config.host = options.host
82
- }
83
-
84
- if (isDef(options.mode)) {
85
- // @ts-ignore
86
- config.mode = options.mode
87
- }
88
-
89
- options.config = config
90
-
91
- if (isDef(options.config.socialConnectionList)) {
92
- // @ts-ignore
93
- options.config.socialConnections = options.config.socialConnectionList
94
- }
95
-
96
- if (isDef(options.config.loginMethod)) {
97
- // @ts-ignore
98
- options.config.defaultLoginMethod = options.config.loginMethod
99
- }
100
-
101
- if (isDef(options.config.loginMethodList)) {
102
- // @ts-ignore
103
- options.config.loginMethods = options.config.loginMethodList
104
- }
105
-
106
- if (isDef(options.config.registerMethodList)) {
107
- // @ts-ignore
108
- options.config.registerMethods = options.config.registerMethodList
109
- }
110
-
111
- if (isDef(options.config.registerMethod)) {
112
- // @ts-ignore
113
- options.config.defaultRegisterMethod = options.config.registerMethod
114
- }
115
-
116
- if (isDef(options.config.contentCSS)) {
117
- options.config.contentCss = options.config.contentCSS
118
- }
119
-
120
- return options
121
- }
122
-
123
- private async getPublicConfig(): Promise<{
124
- [prop: string]: any
125
- }> {
126
- const host = `${this.options.host}` || 'https://core.authing.cn'
127
-
128
- const options: RequestInit = {
129
- method: 'GET',
130
- credentials: 'include'
131
- }
132
-
133
- const fetchRes = await fetch(
134
- `${host}/api/v2/applications/${this.options.appId}/public-config`,
135
- options
136
- )
137
-
138
- const publicConfig = await fetchRes.text()
139
-
140
- return JSON.parse(publicConfig)
141
- }
142
-
143
- async getAuthClient(): Promise<AuthenticationClient> {
144
- let publicConfig = {} as any
145
-
146
- try {
147
- publicConfig = await this.then()
148
- } catch (e) {
149
- throw new Error(JSON.stringify(e))
150
- }
151
-
152
- const _authClientOptions = Object.assign(
153
- {},
154
- {
155
- appId: this.options.appId,
156
- appHost: this.options.host || `https://${publicConfig.requestHostname}`,
157
- tenantId: this.options.tenantId,
158
- redirectUri:
159
- this.options.redirectUri || publicConfig.oidcConfig.redirect_uris[0],
160
- tokenEndPointAuthMethod:
161
- publicConfig.oidcConfig.token_endpoint_auth_method || 'none',
162
- introspectionEndPointAuthMethod:
163
- publicConfig.oidcConfig.introspection_endpoint_auth_method || 'none'
164
- }
165
- )
166
-
167
- return new AuthenticationClient(_authClientOptions)
168
- }
169
-
170
- static getGuardContainer(selector?: string | HTMLElement): Element | null {
171
- const defaultId = 'authing_guard_container'
172
-
173
- if (!selector) {
174
- let container = document.querySelector(`#${defaultId}`)
175
- if (!container) {
176
- container = document.createElement('div')
177
- container.id = defaultId
178
- document.body.appendChild(container)
179
- }
180
-
181
- return container
182
- }
183
-
184
- if (typeof selector === 'string') {
185
- const res = document.querySelector(selector)
186
- if (!res) {
187
- console.warn(
188
- `Failed to start guard: target selector "${selector}" returned null.`
189
- )
190
- }
191
- return res
192
- }
193
-
194
- return selector
195
- }
196
-
197
- private eventListeners = Object.values(GuardEventsCamelToKebabMapping).reduce(
198
- (acc, evtName) => {
199
- return Object.assign({}, acc, {
200
- [evtName as string]: []
201
- })
202
- },
203
- {} as GuardEventListeners
204
- )
205
-
206
- /**
207
- * 启动嵌入模式
208
- * @param el String
209
- * @returns Promise
210
- */
211
- async start(el?: string): Promise<User> {
212
- ;(this.options.config as Partial<GuardLocalConfig>).target = el
213
-
214
- this.render()
215
-
216
- const userInfo = await this.trackSession()
217
-
218
- if (userInfo) {
219
- return Promise.resolve(userInfo)
220
- }
221
-
222
- return new Promise(resolve => {
223
- this.on('login', userInfo => {
224
- resolve(userInfo)
225
- })
226
- })
227
- }
228
-
229
- startRegister() {
230
- this.options.defaultScene = GuardModuleType.REGISTER
231
-
232
- this.options.config = Object.assign({}, this.options.config, {
233
- defaultScenes: GuardModuleType.REGISTER
234
- })
235
-
236
- this.unmount()
237
- this.render()
238
- }
239
-
240
- async checkLoginStatus(): Promise<JwtTokenStatus | undefined> {
241
- const authClient = await this.getAuthClient()
242
- const user = await authClient.getCurrentUser()
243
-
244
- if (!user) {
245
- return
246
- }
247
-
248
- const token = user.token
249
-
250
- if (!token) {
251
- return
252
- }
253
-
254
- const loginStatus: JwtTokenStatus = await authClient.checkLoginStatus(token)
255
-
256
- if (loginStatus.status) {
257
- return loginStatus
258
- }
259
- }
260
-
261
- changeLang(lang: Lang) {
262
- this.options.lang = lang
263
-
264
- this.options.config = Object.assign({}, this.options.config, {
265
- lang
266
- })
267
-
268
- this.unmount()
269
- this.render()
270
- }
271
-
272
- changeContentCSS(contentCSS: string) {
273
- this.options.config = Object.assign({}, this.options.config, {
274
- contentCss: contentCSS
275
- })
276
-
277
- this.unmount()
278
- this.render()
279
- }
280
-
281
- /**
282
- * 启动跳转模式
283
- */
284
- async startWithRedirect(options: StartWithRedirectOptions = {}) {
285
- const getRandom = () => Math.random().toString().slice(2)
286
-
287
- const {
288
- codeChallengeMethod = 'S256',
289
- scope = 'openid profile email phone address',
290
- redirectUri,
291
- state = getRandom(),
292
- nonce = getRandom(),
293
- responseMode = 'query',
294
- responseType = 'code'
295
- } = options
296
-
297
- const authClient = await this.getAuthClient()
298
-
299
- // 生成一个 code_verifier
300
- const codeChallenge = authClient.generateCodeChallenge()
301
-
302
- localStorage.setItem('codeChallenge', codeChallenge)
303
-
304
- // 计算 code_verifier 的 SHA256 摘要
305
- const codeChallengeDigest = authClient.getCodeChallengeDigest({
306
- codeChallenge,
307
- method: codeChallengeMethod
308
- })
309
-
310
- // 构造 OIDC 授权码 + PKCE 模式登录 URL
311
- const url = authClient.buildAuthorizeUrl({
312
- codeChallenge: codeChallengeDigest,
313
- codeChallengeMethod,
314
- scope,
315
- redirectUri,
316
- state,
317
- nonce,
318
- responseMode,
319
- responseType
320
- })
321
-
322
- window.location.href = url
323
- }
324
-
325
- async handleRedirectCallback() {
326
- const { code, codeChallenge } = this.getCodeAndCodeChallenge()
327
-
328
- const { id_token, access_token } = await this.getAccessTokenByCode(
329
- code,
330
- codeChallenge
331
- )
332
-
333
- const authClient = await this.getAuthClient()
334
-
335
- const userInfo = await authClient.getUserInfoByAccessToken(access_token)
336
-
337
- this.setStorageCache(access_token, id_token, userInfo)
338
- }
339
-
340
- private async getAccessTokenByCode(code: string, codeChallenge: string) {
341
- const authClient = await this.getAuthClient()
342
-
343
- return await authClient.getAccessTokenByCode(code, {
344
- codeVerifier: codeChallenge
345
- })
346
- }
347
-
348
- private getCodeAndCodeChallenge() {
349
- const query = this.parseUrlQuery()
350
- const { code = '' } = query
351
- const codeChallenge = localStorage.getItem('codeChallenge') || ''
352
-
353
- return {
354
- code,
355
- codeChallenge
356
- }
357
- }
358
-
359
- private setStorageCache(
360
- accessToken: string,
361
- idToken: string,
362
- userInfo: string
363
- ) {
364
- localStorage.setItem('accessToken', accessToken)
365
- localStorage.setItem('idToken', idToken)
366
- localStorage.setItem('userInfo', JSON.stringify(userInfo))
367
- }
368
-
369
- private parseUrlQuery() {
370
- const query: Record<string, string> = {}
371
-
372
- let queryString = ''
373
-
374
- try {
375
- queryString = window.location.search.split('?')[1]
376
- } catch (e) {
377
- queryString = window.location.hash.split('#')[1]
378
- }
379
-
380
- if (!queryString) {
381
- return query
382
- }
383
-
384
- queryString.split('&').forEach(item => {
385
- const [key, value] = item.split('=')
386
- query[key] = value
387
- })
388
-
389
- return query
390
- }
391
-
392
- /**
393
- * 获取当前用户信息
394
- */
395
- async trackSession(): Promise<User | null> {
396
- const authClient = await this.getAuthClient()
397
-
398
- return authClient.getCurrentUser()
399
- }
400
-
401
- async logout() {
402
- const publicConfig = await this.then()
403
-
404
- let redirectUri = ''
405
-
406
- const origin = window.location.origin
407
-
408
- try {
409
- redirectUri = publicConfig.logoutRedirectUris[0]
410
- } catch (e) {
411
- redirectUri = origin
412
- } finally {
413
- if (!redirectUri) {
414
- redirectUri = origin
415
- }
416
- }
417
-
418
- const idToken = localStorage.getItem('idToken')
419
- let logoutUrl = ''
420
- const authClient = await this.getAuthClient()
421
-
422
- authClient.logout()
423
-
424
- if (idToken) {
425
- logoutUrl = authClient.buildLogoutUrl({
426
- expert: true,
427
- redirectUri,
428
- idToken
429
- })
430
- }
431
-
432
- localStorage.clear()
433
-
434
- window.location.href = logoutUrl || redirectUri
435
- }
436
-
437
- async render() {
438
- const evts: GuardEvents = Object.entries(
439
- GuardEventsCamelToKebabMapping
440
- ).reduce((acc, [reactEvt, nativeEvt]) => {
441
- return Object.assign({}, acc, {
442
- [reactEvt]: (...rest: any) => {
443
- if (nativeEvt === 'close') {
444
- this.hide()
445
- }
446
-
447
- // TODO 返回最后一个执行函数的值,实际应该只让监听一次
448
- return (
449
- (this.eventListeners as any)[nativeEvt as string]
450
- .map((item: any) => {
451
- return item(...rest)
452
- })
453
- .slice(-1)[0] ?? true
454
- )
455
- }
456
- })
457
- }, {} as GuardEvents)
458
-
459
- const publicConfig = await this.then()
460
- const authClient = await this.getAuthClient()
461
-
462
- if (this.options.config) {
463
- this.options.config.host =
464
- this.options.host || `https://${publicConfig.requestHostname}`
465
- }
466
-
467
- const target = Guard.getGuardContainer(this.options.config?.target)
468
-
469
- if (!target) {
470
- return
471
- }
472
-
473
- const root = createRoot(target)
474
-
475
- return root.render(
476
- <ReactAuthingGuard
477
- {...(evts as GuardEvents)}
478
- appId={this.options.appId}
479
- tenantId={this.options.tenantId}
480
- config={this.options.config}
481
- facePlugin={this.options.facePlugin}
482
- appendConfig={this.options.appendConfig}
483
- visible={this.visible}
484
- authClient={authClient}
485
- />
486
- )
487
- }
488
-
489
- on<T extends keyof GuardEventsKebabToCamelType>(
490
- evt: T,
491
- handler: Exclude<GuardEventsKebabToCamelType[T], undefined>
492
- ) {
493
- ;(this.eventListeners as any)[evt].push(handler as any)
494
- }
495
-
496
- show() {
497
- this.visible = true
498
- this.render()
499
- }
500
-
501
- hide() {
502
- this.visible = false
503
- this.render()
504
- }
505
-
506
- unmount() {
507
- const node = Guard.getGuardContainer(this.options.config?.target)
508
-
509
- if (node) {
510
- ReactDOM.unmountComponentAtNode(node)
511
- }
512
- }
513
- }
package/src/types.ts DELETED
@@ -1,93 +0,0 @@
1
- import {
2
- GuardEventsKebabToCamelType,
3
- Lang,
4
- GuardProps,
5
- GuardLocalConfig,
6
- CodeAction,
7
- ApiCode,
8
- GuardModuleType,
9
- LoginMethods,
10
- OIDCConnectionMode,
11
- SocialConnectionProvider,
12
- Protocol,
13
- RegisterMethods,
14
- GuardMode,
15
- InputMethod,
16
- GuardPageSene,
17
- EmailScene,
18
- SceneType
19
- } from '@authing/react18-components'
20
-
21
- export type ICodeAction = `${CodeAction}`
22
- export type IApiCode = `${ApiCode}`
23
- export type IGuardModuleType = `${GuardModuleType}`
24
- export type ILoginMethod = `${LoginMethods}`
25
- export type IOIDCConnectionMode = `${OIDCConnectionMode}`
26
- export type ISocialConnectionProvider = `${SocialConnectionProvider}`
27
- export type IProtocol = `${Protocol}`
28
- export type IRegisterMethod = `${RegisterMethods}`
29
- export type IGuardMode = `${GuardMode}`
30
- export type IInputMethod = `${InputMethod}`
31
- export type IGuardPageSene = `${GuardPageSene}`
32
- export type IEmailScene = `${EmailScene}`
33
- export type ISceneType = `${SceneType}`
34
-
35
- export type GuardEventListeners = {
36
- [key in keyof GuardEventsKebabToCamelType]: Exclude<
37
- Required<GuardEventsKebabToCamelType>[key],
38
- undefined
39
- >[]
40
- }
41
-
42
- export type CodeChallengeMethod = 'S256' | 'plain'
43
-
44
- export interface IGuardConfig extends GuardLocalConfig {
45
- // replace socialConnections
46
- socialConnectionList?: ISocialConnectionProvider[]
47
-
48
- // replace defaultLoginMethod
49
- loginMethod?: ILoginMethod
50
-
51
- // replace loginMethods
52
- loginMethodList: ILoginMethod[]
53
-
54
- // replace defaultRegisterMethod
55
- registerMethod?: IRegisterMethod
56
-
57
- // replace registerMethods
58
- registerMethodList?: IRegisterMethod[]
59
-
60
- // replace contentCss
61
- contentCSS?: string
62
- }
63
-
64
- export interface GuardOptions extends GuardProps {
65
- appId: string
66
- host?: string
67
- redirectUri?: string
68
- mode?: IGuardMode
69
- defaultScene?: IGuardModuleType
70
- tenantId?: string
71
- lang?: Lang
72
- isSSO?: boolean
73
- config?: Partial<IGuardConfig> // 兼容 4.x 的 config
74
- }
75
-
76
- export interface StartWithRedirectOptions {
77
- codeChallengeMethod?: CodeChallengeMethod
78
- scope?: string
79
- redirectUri?: string
80
- state?: string
81
- responseType?:
82
- | 'code'
83
- | 'code id_token token'
84
- | 'code id_token'
85
- | 'code token'
86
- | 'id_token token'
87
- | 'id_token'
88
- | 'none'
89
- responseMode?: 'query' | 'fragment' | 'form_post'
90
- nonce?: string
91
- }
92
-
93
- export * from '@authing/react18-components'
package/tsconfig.json DELETED
@@ -1,31 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "baseUrl": ".",
4
- "outDir": "dist",
5
- "target": "es5",
6
- "lib": ["dom", "esnext"],
7
- "allowJs": false,
8
- "skipLibCheck": true,
9
- "esModuleInterop": true,
10
- "allowSyntheticDefaultImports": true,
11
- "strict": true,
12
- "forceConsistentCasingInFileNames": true,
13
- "noFallthroughCasesInSwitch": true,
14
- "module": "esnext",
15
- "moduleResolution": "node",
16
- "resolveJsonModule": true,
17
- "declaration": true,
18
- "declarationDir": "./dist/typings",
19
- "noEmit": false,
20
- "jsx": "react",
21
- "downlevelIteration": true
22
- },
23
- "include": [
24
- "src/**/*.tsx",
25
- "src/**/*.ts"
26
- ],
27
- "exclude": [
28
- "node_modules",
29
- "dist"
30
- ]
31
- }