@zvonimirsun/iszy-nuxt-auth-layer 0.1.0 → 0.1.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.
@@ -1,5 +1,6 @@
1
1
  import type { Device, ResultDto } from '@zvonimirsun/iszy-common'
2
- import type { PublicSimpleUser } from '#shared/types/auth'
2
+ import type { PublicSimpleUser } from '##shared/types/auth'
3
+ import dayjs from 'dayjs'
3
4
  import { acceptHMRUpdate, defineStore } from 'pinia'
4
5
 
5
6
  interface LoginAttemptFailureData {
@@ -19,51 +20,56 @@ interface LoginBanFailureData {
19
20
  type LoginFailureData = LoginAttemptFailureData | LoginBanFailureData
20
21
  type LoginResultData = PublicSimpleUser | LoginFailureData
21
22
 
22
- type ProfileFetcher = <T>(request: string, opts?: {
23
- signal?: AbortSignal
24
- }) => Promise<T>
25
-
26
- const appFetch = $fetch as unknown as <T>(request: string, opts?: Record<string, unknown>) => Promise<T>
27
-
28
23
  export const useUserStore = defineStore('user', () => {
29
24
  const profilePulled = ref(false)
30
25
  const profile = ref<PublicSimpleUser>()
31
- const logged = computed(() => !!profile.value)
26
+ const logged = computed(() => {
27
+ return !!profile.value
28
+ })
32
29
 
33
- let pullProfilePromise: Promise<boolean> | null = null
34
- let pullProfileAbortController: AbortController | null = null
30
+ let pullProfilePromise: Promise<ResultDto<{
31
+ logged: boolean
32
+ profile?: PublicSimpleUser
33
+ }>> | null = null
34
+ let pullProfileResolve: ((value: ResultDto<{ logged: boolean, profile?: PublicSimpleUser }>) => void) | null
35
+ let pullProfileReject: ((value: unknown) => void) | null
36
+ let pullProfileAbortController: AbortController | null = null // 用于中断请求
35
37
 
36
- async function login(payload: {
38
+ async function login({ userName, password }: {
37
39
  userName: string
38
40
  password: string
39
41
  }) {
40
- const { userName, password } = payload
41
- if (!userName || !password) {
42
- throw new Error('请输入用户名和密码')
43
- }
44
-
42
+ let error = ''
45
43
  try {
46
- const res = await appFetch<ResultDto<LoginResultData>>('/api/auth/login', {
47
- method: 'post',
48
- body: {
49
- userName: userName.trim(),
50
- password,
51
- },
52
- })
53
-
54
- if (res.success) {
55
- profilePulled.value = true
56
- updateProfile(res.data as PublicSimpleUser)
57
- return
44
+ if (userName && password) {
45
+ const res = await $fetch<ResultDto<LoginResultData>>(`/api/auth/login`, {
46
+ method: 'post',
47
+ body: {
48
+ userName: userName.trim(),
49
+ password,
50
+ },
51
+ })
52
+ if (res.success) {
53
+ profilePulled.value = true
54
+ const nextProfile = res.data as PublicSimpleUser
55
+ await updateProfile(nextProfile)
56
+ authEvents.emit('loginSuccess', { profile: nextProfile })
57
+ return
58
+ }
59
+ else {
60
+ removeProfile()
61
+ error = formatLoginFailureMessage(res.message, res.data)
62
+ }
63
+ }
64
+ else {
65
+ error = '请输入用户名和密码'
58
66
  }
59
-
60
- removeProfile()
61
- throw new Error(formatLoginFailureMessage(res.message, res.data))
62
67
  }
63
- catch (error) {
68
+ catch (e) {
64
69
  removeProfile()
65
- throw error
70
+ throw e
66
71
  }
72
+ throw new Error(error)
67
73
  }
68
74
 
69
75
  function formatLoginFailureMessage(message: string, data?: LoginResultData) {
@@ -80,79 +86,110 @@ export const useUserStore = defineStore('user', () => {
80
86
  }
81
87
 
82
88
  async function logout() {
83
- const res = await appFetch<ResultDto<void>>('/api/auth/logout', {
89
+ const data = await $fetch<ResultDto<void>>(`/api/auth/logout`, {
84
90
  method: 'POST',
85
91
  })
86
-
87
- if (res?.success) {
88
- removeProfile()
89
- return
92
+ if (data && data.success) {
93
+ await removeProfile()
94
+ authEvents.emit('logoutSuccess', undefined)
95
+ }
96
+ else {
97
+ throw new Error(data?.message || '登出失败')
90
98
  }
91
-
92
- throw new Error(res?.message || '登出失败')
93
99
  }
94
100
 
95
- async function pullProfile(force = false, fetcher: ProfileFetcher = appFetch) {
101
+ async function pullProfile(force?: boolean, fetcher: typeof $fetch = $fetch) {
102
+ // 1. 非强制刷新且已拉取成功,直接返回
96
103
  if (profilePulled.value && !force) {
97
- return logged.value
104
+ return true
98
105
  }
99
106
 
107
+ // 2. 强制刷新:中断正在进行的请求并重置状态
100
108
  if (force) {
101
- pullProfileAbortController?.abort()
102
- pullProfileAbortController = null
109
+ // 中断之前的请求
110
+ if (pullProfileAbortController) {
111
+ pullProfileAbortController.abort()
112
+ pullProfileAbortController = null
113
+ }
114
+ // 重置 Promise 相关状态
103
115
  pullProfilePromise = null
116
+ pullProfileResolve = null
117
+ pullProfileReject = null
104
118
  }
105
119
 
120
+ // 3. 非强制刷新且已有请求中,返回现有 Promise
106
121
  if (pullProfilePromise && !force) {
107
122
  return pullProfilePromise
108
123
  }
109
124
 
110
- pullProfileAbortController = new AbortController()
111
- pullProfilePromise = (async () => {
112
- try {
113
- const res = await fetcher<ResultDto<{
114
- logged: boolean
115
- profile?: PublicSimpleUser
116
- }>>('/api/auth/check', {
117
- signal: pullProfileAbortController!.signal,
118
- })
119
-
120
- if (res?.success && res.data?.logged) {
121
- updateProfile(res.data.profile)
122
- profilePulled.value = true
123
- return true
124
- }
125
-
126
- removeProfile()
125
+ // 4. 创建新的 Promise 并发起请求
126
+ pullProfilePromise = new Promise<ResultDto<{
127
+ logged: boolean
128
+ profile?: PublicSimpleUser
129
+ }>>((resolve, reject) => {
130
+ pullProfileResolve = resolve
131
+ pullProfileReject = reject
132
+ })
133
+ try {
134
+ // 创建 AbortController 用于中断请求
135
+ pullProfileAbortController = new AbortController()
136
+ const res = await fetcher<ResultDto<{
137
+ logged: boolean
138
+ profile?: PublicSimpleUser
139
+ }>>(`/api/auth/check`, {
140
+ signal: pullProfileAbortController.signal, // 关联中断信号
141
+ })
142
+ if (res && res.success) {
143
+ await updateProfile(res.data?.profile, fetcher)
127
144
  profilePulled.value = true
128
- return false
145
+ // 安全调用 resolve(避免空值)
146
+ pullProfileResolve?.(res)
129
147
  }
130
- catch (error) {
131
- if ((error as Error).name !== 'AbortError') {
132
- removeProfile()
133
- profilePulled.value = true
134
- }
135
- throw error
148
+ else {
149
+ await removeProfile(fetcher)
150
+ // 安全调用 reject
151
+ pullProfileReject?.(new Error(res?.message || '拉取用户信息失败'))
136
152
  }
137
- finally {
138
- pullProfileAbortController = null
139
- pullProfilePromise = null
153
+ }
154
+ catch (error) {
155
+ // 处理中断错误(无需提示,属于正常取消)
156
+ if ((error as Error).name !== 'AbortError') {
157
+ await removeProfile(fetcher)
158
+ console.error('拉取用户信息异常:', error)
140
159
  }
141
- })()
142
-
160
+ // 安全调用 reject
161
+ pullProfileReject?.(error)
162
+ }
163
+ finally {
164
+ // 清理资源
165
+ pullProfileAbortController = null
166
+ pullProfileResolve = null
167
+ pullProfileReject = null
168
+ // 关键:请求完成后重置 Promise(避免复用旧 Promise)
169
+ pullProfilePromise = null
170
+ }
143
171
  return pullProfilePromise
144
172
  }
145
173
 
146
- function updateProfile(data?: PublicSimpleUser) {
174
+ async function updateProfile(data?: PublicSimpleUser, fetcher?: typeof $fetch) {
147
175
  profile.value = data
176
+ authEvents.emit('profileUpdated', {
177
+ profile: data,
178
+ fetcher,
179
+ })
148
180
  }
149
181
 
150
- function removeProfile() {
151
- updateProfile(undefined)
182
+ async function removeProfile(fetcher?: typeof $fetch) {
183
+ await updateProfile(undefined, fetcher)
184
+ authEvents.emit('profileRemoved', {
185
+ fetcher,
186
+ })
152
187
  }
153
188
 
154
189
  async function thirdPartyUnbind(type: string) {
155
- await appFetch<ResultDto<void>>('/api/oauth/unbind', {
190
+ await $fetch<{
191
+ success: boolean
192
+ }>('/api/oauth/unbind', {
156
193
  method: 'POST',
157
194
  body: {
158
195
  provider: type,
@@ -161,9 +198,22 @@ export const useUserStore = defineStore('user', () => {
161
198
  await pullProfile(true)
162
199
  }
163
200
 
164
- async function getDevices(): Promise<Device[]> {
165
- const res = await appFetch<ResultDto<Device[]>>('/api/auth/devices')
166
- return res.data || []
201
+ async function getDevices(): Promise<(Device & {
202
+ createTime?: string
203
+ lastLoginTime?: string
204
+ })[]> {
205
+ const res = await $fetch<ResultDto<Device[]>>(`/api/auth/devices`)
206
+ return res.data!.map((device: Device & {
207
+ createTime?: string
208
+ lastLoginTime?: string
209
+ }) => {
210
+ if (!device.ip) {
211
+ device.ip = '未知'
212
+ }
213
+ device.createTime = dayjs(device.createdAt!).format('YYYY年MM月DD日 HH:mm')
214
+ device.lastLoginTime = dayjs(device.updatedAt!).format('YYYY年MM月DD日 HH:mm')
215
+ return device
216
+ })
167
217
  }
168
218
 
169
219
  async function removeDevice({ deviceId, other }: {
@@ -171,13 +221,23 @@ export const useUserStore = defineStore('user', () => {
171
221
  all?: boolean
172
222
  other?: boolean
173
223
  }) {
174
- await appFetch('/api/auth/logout', {
175
- method: 'POST',
176
- query: {
177
- deviceId,
178
- other,
179
- },
180
- })
224
+ if (other) {
225
+ await $fetch(`/api/auth/logout`, {
226
+ method: 'POST',
227
+ query: {
228
+ other,
229
+ },
230
+ })
231
+ return
232
+ }
233
+ if (deviceId) {
234
+ await $fetch(`/api/auth/logout`, {
235
+ method: 'POST',
236
+ query: {
237
+ deviceId,
238
+ },
239
+ })
240
+ }
181
241
  }
182
242
 
183
243
  return {
@@ -0,0 +1,16 @@
1
+ import type { PublicSimpleUser } from '##shared/types/auth'
2
+ import mitt from 'mitt'
3
+
4
+ export interface AuthEventPayload {
5
+ profile?: PublicSimpleUser
6
+ fetcher?: typeof $fetch
7
+ }
8
+
9
+ export type AuthEvents = Record<string | symbol, unknown> & {
10
+ loginSuccess: AuthEventPayload
11
+ profileUpdated: AuthEventPayload
12
+ profileRemoved: AuthEventPayload
13
+ logoutSuccess: undefined
14
+ }
15
+
16
+ export const authEvents = mitt<AuthEvents>()
package/nuxt.config.ts CHANGED
@@ -1,4 +1,12 @@
1
+ import { fileURLToPath } from 'node:url'
2
+
1
3
  export default defineNuxtConfig({
4
+ $meta: {
5
+ name: 'iszy-nuxt-auth-layer',
6
+ },
7
+ alias: {
8
+ '##shared': fileURLToPath(new URL('./shared', import.meta.url)),
9
+ },
2
10
  runtimeConfig: {
3
11
  public: {
4
12
  title: '',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zvonimirsun/iszy-nuxt-auth-layer",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "description": "ISZY Nuxt 应用共享认证 layer。",
@@ -27,7 +27,10 @@
27
27
  ],
28
28
  "dependencies": {
29
29
  "@zvonimirsun/iszy-common": "^1.2.0",
30
- "ms": "^2.1.3"
30
+ "dayjs": "^1.11.21",
31
+ "mitt": "^3.0.1",
32
+ "ms": "^2.1.3",
33
+ "ofetch": "^1.5.1"
31
34
  },
32
35
  "peerDependencies": {
33
36
  "@pinia/nuxt": ">=0.11.0",
@@ -48,7 +51,7 @@
48
51
  "access": "public"
49
52
  },
50
53
  "scripts": {
51
- "postinstall": "nuxt prepare",
52
- "typecheck": "nuxt typecheck"
54
+ "prepare:types": "nuxt prepare",
55
+ "typecheck": "nuxt prepare && nuxt typecheck"
53
56
  }
54
57
  }
@@ -1,5 +1,5 @@
1
1
  import type { PublicUser, ResultDto } from '@zvonimirsun/iszy-common'
2
- import type { PublicSimpleUser } from '#shared/types/auth'
2
+ import type { PublicSimpleUser } from '##shared/types/auth'
3
3
 
4
4
  export default defineEventHandler(async (event): Promise<ResultDto<{
5
5
  logged: boolean
@@ -1,6 +1,6 @@
1
1
  import type { PublicUser, ResultDto } from '@zvonimirsun/iszy-common'
2
2
  import type { FetchError } from 'ofetch'
3
- import type { PublicSimpleUser } from '#shared/types/auth'
3
+ import type { PublicSimpleUser } from '##shared/types/auth'
4
4
 
5
5
  interface LoginFailureData {
6
6
  code: 'LOGIN_FAILED' | 'LOGIN_BANNED'
@@ -2,7 +2,7 @@ import type { PublicUser, ResultDto } from '@zvonimirsun/iszy-common'
2
2
  import type { H3Event } from 'h3'
3
3
  import type { NitroFetchRequest, TypedInternalResponse } from 'nitropack'
4
4
  import type { FetchError } from 'ofetch'
5
- import type { SessionData } from '#shared/types/auth'
5
+ import type { SessionData } from '##shared/types/auth'
6
6
  import { getProxyRequestHeaders } from 'h3'
7
7
 
8
8
  export async function proxyFetch(event: H3Event) {
@@ -1,6 +1,6 @@
1
1
  import type { H3Event } from 'h3'
2
2
  import type { StringValue } from 'ms'
3
- import type { SessionData, SessionTombstone } from '#shared/types/auth'
3
+ import type { SessionData, SessionTombstone } from '##shared/types/auth'
4
4
  import { randomBytes } from 'node:crypto'
5
5
  import ms from 'ms'
6
6
 
@@ -1,4 +1,4 @@
1
- import type { OAuthStateData } from '#shared/types/auth'
1
+ import type { OAuthStateData } from '##shared/types/auth'
2
2
  import ms from 'ms'
3
3
 
4
4
  export function getStateKey(state: string): string {
@@ -1,5 +1,5 @@
1
1
  import type { PublicUser } from '@zvonimirsun/iszy-common'
2
- import type { PublicSimpleUser } from '#shared/types/auth'
2
+ import type { PublicSimpleUser } from '##shared/types/auth'
3
3
 
4
4
  export function toPublicSimpleUser(user: PublicUser): PublicSimpleUser {
5
5
  const { status, createBy, updateBy, privileges, ...result } = user