@zvonimirsun/iszy-nuxt-auth-layer 0.2.6 → 0.3.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.
package/README.md CHANGED
@@ -31,6 +31,12 @@ export default defineNuxtConfig({
31
31
 
32
32
  消费方应用需要按部署环境配置 API origin、Redis 连接信息和 session cookie 选项。服务端请求优先使用私有的 `apiOrigin`,未配置时回退到 `public.apiOrigin`;OAuth 浏览器跳转和客户端直连仍使用公开地址。
33
33
 
34
+ ### 公开页面缓存
35
+
36
+ `runtimeConfig.session.renewalScope` 默认为 `all`,保持所有响应续期 session 的行为。
37
+ 采用共享 HTML 缓存的应用应设置为 `api`:仅 `/api` 及其子路径续期,页面和静态资源响应不访问 Redis、不写 session cookie。API 响应使用 `private, no-store`。
38
+ 消费方还必须将用户资料加载移到客户端,禁止将用户资料序列化进共享页面;需要权限的页面须等待认证和权限检查完成。layer 不自动更改消费方的认证启动时机。
39
+
34
40
  ## 文档
35
41
 
36
42
  详细架构、运行时配置和接入说明请查看 [DeepWiki](https://deepwiki.com/ZvonimirSun/iszy-nuxt-auth-layer)。
@@ -85,8 +85,12 @@ const schema = z.object({
85
85
 
86
86
  type Schema = z.output<typeof schema>
87
87
 
88
+ const mounted = ref(false)
88
89
  onMounted(() => {
89
- if (userStore.logged) {
90
+ mounted.value = true
91
+ })
92
+ const stopAutoRedirect = watch(() => mounted.value && userStore.logged, (logged) => {
93
+ if (logged) {
90
94
  router.push({ path: redirect.value || '/', query: otherQuery.value })
91
95
  toast.add({ title: '已登录', description: '您已经登录,无需再次登录', color: 'info' })
92
96
  }
@@ -108,6 +112,7 @@ async function login(payload: FormSubmitEvent<Schema>) {
108
112
  toast.add({ title: '网络异常', description: '请检查您的网络连接', color: 'error' })
109
113
  return
110
114
  }
115
+ stopAutoRedirect()
111
116
  try {
112
117
  loading.value = true
113
118
  error.value = undefined
@@ -127,6 +132,7 @@ function thirdPartyLogin(url: string, title = '第三方登录', width = 500, he
127
132
  toast.add({ title: '登录中', description: '登录进行中,请勿重复点击', color: 'warning' })
128
133
  return
129
134
  }
135
+ stopAutoRedirect()
130
136
  loading.value = true
131
137
  error.value = undefined
132
138
  window.addEventListener('message', thirdPartyLoginCallback)
@@ -45,8 +45,6 @@ export const useUserStore = defineStore('user', () => {
45
45
  profile?: PublicSimpleUser
46
46
  }>> | null = null
47
47
  let authFeaturesPromise: Promise<AuthFeatures> | null = null
48
- let pullProfileResolve: ((value: ResultDto<{ logged: boolean, profile?: PublicSimpleUser }>) => void) | null
49
- let pullProfileReject: ((value: unknown) => void) | null
50
48
  let pullProfileAbortController: AbortController | null = null // 用于中断请求
51
49
 
52
50
  async function login({ userName, password }: {
@@ -137,80 +135,52 @@ export const useUserStore = defineStore('user', () => {
137
135
  }
138
136
  }
139
137
 
140
- async function pullProfile(force?: boolean, fetcher: Fetcher = $fetch) {
141
- // 1. 非强制刷新且已拉取成功,直接返回
138
+ function pullProfile(force = false, fetcher: Fetcher = $fetch) {
142
139
  if (profilePulled.value && !force) {
143
- return true
144
- }
145
-
146
- // 2. 强制刷新:中断正在进行的请求并重置状态
147
- if (force) {
148
- // 中断之前的请求
149
- if (pullProfileAbortController) {
150
- pullProfileAbortController.abort()
151
- pullProfileAbortController = null
152
- }
153
- // 重置 Promise 相关状态
154
- pullProfilePromise = null
155
- pullProfileResolve = null
156
- pullProfileReject = null
140
+ return Promise.resolve({
141
+ success: true,
142
+ data: { logged: logged.value, profile: profile.value },
143
+ message: '',
144
+ })
157
145
  }
158
-
159
- // 3. 非强制刷新且已有请求中,返回现有 Promise
160
146
  if (pullProfilePromise && !force) {
161
147
  return pullProfilePromise
162
148
  }
163
149
 
164
- // 4. 创建新的 Promise 并发起请求
165
- pullProfilePromise = new Promise<ResultDto<{
166
- logged: boolean
167
- profile?: PublicSimpleUser
168
- }>>((resolve, reject) => {
169
- pullProfileResolve = resolve
170
- pullProfileReject = reject
171
- })
172
- try {
173
- // 创建 AbortController 用于中断请求
174
- pullProfileAbortController = new AbortController()
150
+ pullProfileAbortController?.abort()
151
+ const controller = new AbortController()
152
+ pullProfileAbortController = controller
153
+ const request = (async () => {
175
154
  const res = await fetcher<ResultDto<{
176
155
  logged: boolean
177
156
  profile?: PublicSimpleUser
178
- }>>(`/api/auth/check`, {
179
- signal: pullProfileAbortController.signal, // 关联中断信号
180
- })
181
- if (res && res.success) {
182
- await updateProfile(res.data?.profile, fetcher)
183
- profilePulled.value = true
184
- // 安全调用 resolve(避免空值)
185
- pullProfileResolve?.(res)
157
+ }>>('/api/auth/check', { signal: controller.signal })
158
+ if (controller.signal.aborted) {
159
+ throw new DOMException('Aborted', 'AbortError')
186
160
  }
187
- else {
188
- await removeProfile(fetcher)
189
- // 安全调用 reject
190
- pullProfileReject?.(new Error(res?.message || '拉取用户信息失败'))
161
+ if (!res.success || !res.data) {
162
+ throw new Error(res.message || '获取登录状态失败')
191
163
  }
192
- }
193
- catch (error) {
194
- // 处理中断错误(无需提示,属于正常取消)
195
- if ((error as Error).name !== 'AbortError') {
196
- await removeProfile(fetcher)
197
- console.error('拉取用户信息异常:', error)
164
+ profile.value = res.data.logged ? res.data.profile : undefined
165
+ profilePulled.value = true
166
+ authEvents.emit('profileUpdated', { profile: profile.value, fetcher })
167
+ return res
168
+ })()
169
+ const pending = request.finally(() => {
170
+ if (pullProfileAbortController === controller) {
171
+ pullProfileAbortController = null
172
+ pullProfilePromise = null
198
173
  }
199
- // 安全调用 reject
200
- pullProfileReject?.(error)
201
- }
202
- finally {
203
- // 清理资源
204
- pullProfileAbortController = null
205
- pullProfileResolve = null
206
- pullProfileReject = null
207
- // 关键:请求完成后重置 Promise(避免复用旧 Promise)
208
- pullProfilePromise = null
209
- }
210
- return pullProfilePromise
174
+ })
175
+ pullProfilePromise = pending
176
+ return pending
211
177
  }
212
178
 
213
179
  async function updateProfile(data?: PublicSimpleUser, fetcher?: Fetcher) {
180
+ pullProfileAbortController?.abort()
181
+ pullProfileAbortController = null
182
+ pullProfilePromise = null
183
+ profilePulled.value = true
214
184
  profile.value = data
215
185
  authEvents.emit('profileUpdated', {
216
186
  profile: data,
package/nuxt.config.ts CHANGED
@@ -33,6 +33,7 @@ export default defineNuxtConfig({
33
33
  password: undefined,
34
34
  },
35
35
  session: {
36
+ renewalScope: 'all' as 'all' | 'api',
36
37
  cookieName: 'NUXT_SESSION_ID',
37
38
  maxAge: '7d',
38
39
  domain: '',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zvonimirsun/iszy-nuxt-auth-layer",
3
- "version": "0.2.6",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "description": "ISZY Nuxt 应用共享认证 layer。",
@@ -51,12 +51,14 @@
51
51
  "pinia": "^3.0.4",
52
52
  "tailwindcss": "^4.3.2",
53
53
  "typescript": "^6.0.3",
54
+ "vue": "^3.5.39",
54
55
  "vue-tsc": "^3.3.3"
55
56
  },
56
57
  "publishConfig": {
57
58
  "access": "public"
58
59
  },
59
60
  "scripts": {
61
+ "test": "node --test tests/*.test.mjs",
60
62
  "dev": "nuxt dev .playground",
61
63
  "postinstall": "nuxt prepare .playground",
62
64
  "typecheck": "nuxt typecheck .playground"
@@ -28,9 +28,14 @@ export default defineEventHandler(async (event): Promise<ResultDto<{
28
28
  message: '已登录',
29
29
  }
30
30
  }
31
+ throw createError({ statusCode: 503, statusMessage: 'Authentication service unavailable' })
31
32
  }
32
- catch {
33
- // fall through to the unauthenticated response below
33
+ catch (error) {
34
+ const status = (error as { statusCode?: number, response?: { status?: number } }).response?.status
35
+ || (error as { statusCode?: number }).statusCode
36
+ if (status !== 401) {
37
+ throw createError({ statusCode: 503, statusMessage: 'Authentication service unavailable' })
38
+ }
34
39
  }
35
40
 
36
41
  return {
@@ -1,3 +1,11 @@
1
1
  export default defineResponseMiddleware(async (event) => {
2
+ const { session } = useRuntimeConfig(event)
3
+ const path = getRequestURL(event).pathname
4
+ if (session.renewalScope === 'api' && path !== '/api' && !path.startsWith('/api/')) {
5
+ return
6
+ }
7
+ if (path === '/api' || path.startsWith('/api/')) {
8
+ setResponseHeader(event, 'Cache-Control', 'private, no-store')
9
+ }
2
10
  await setRedisSession(event, await getRedisSession(event))
3
11
  })