@zvonimirsun/iszy-nuxt-auth-layer 0.1.4 → 0.1.6

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.
@@ -0,0 +1 @@
1
+ <?xml version="1.0" encoding="UTF-8"?><svg version="1.2" baseProfile="tiny-ps" width="128" height="128" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg"><title>LINUX DO</title><clipPath id="a"><circle cx="60" cy="60" r="47"/></clipPath><circle fill="#f0f0f0" cx="60" cy="60" r="50"/><rect fill="#1c1c1e" clip-path="url(#a)" x="10" y="10" width="100" height="30"/><rect fill="#f0f0f0" clip-path="url(#a)" x="10" y="40" width="100" height="40"/><rect fill="#ffb003" clip-path="url(#a)" x="10" y="80" width="100" height="30"/></svg>
@@ -0,0 +1,387 @@
1
+ <script setup lang="ts">
2
+ import type { TableColumn } from '@nuxt/ui'
3
+ import type { Device } from '@zvonimirsun/iszy-common'
4
+ import { RoleEnum } from '@zvonimirsun/iszy-common'
5
+ import { useUserStore } from '##stores/user'
6
+
7
+ const props = defineProps<{
8
+ adminOrigin?: string
9
+ loginRedirect?: string
10
+ }>()
11
+
12
+ const userStore = useUserStore()
13
+ const authFeatures = await userStore.getAuthFeatures()
14
+ const toast = useToast()
15
+ const publicRegister = computed(() => authFeatures.authMode !== 'sso' && authFeatures.publicRegister)
16
+ const loginPath = computed(() => `/login?redirect=${encodeURIComponent(props.loginRedirect || '/settings')}`)
17
+ const adminRoleNames = new Set([RoleEnum.ADMIN, RoleEnum.SUPERADMIN]) as Set<string>
18
+ const showAdminLink = computed(() => {
19
+ return !!props.adminOrigin && !!userStore.profile?.roles?.some((role) => {
20
+ return adminRoleNames.has(role.name)
21
+ })
22
+ })
23
+
24
+ /** ************** 三方登录绑定 ***************/
25
+
26
+ type ThirdPartyType = 'github' | 'linuxdo' | 'sso'
27
+ type ThirdPartyProfile = {
28
+ [key in ThirdPartyType]?: string
29
+ }
30
+
31
+ const thirdParties: {
32
+ type: ThirdPartyType
33
+ title: string
34
+ icon: string
35
+ }[] = [
36
+ {
37
+ type: 'github',
38
+ title: 'Github',
39
+ icon: 'i-simple-icons:github',
40
+ },
41
+ {
42
+ type: 'linuxdo',
43
+ title: 'LINUX DO',
44
+ icon: 'i-iszy-auth:linuxdo',
45
+ },
46
+ {
47
+ type: 'sso',
48
+ title: authFeatures.sso.title,
49
+ icon: 'i-lucide:shield-check',
50
+ },
51
+ ]
52
+
53
+ const binding = ref(false)
54
+ let pollIndex: number | null = null
55
+
56
+ onBeforeUnmount(() => {
57
+ if (pollIndex != null) {
58
+ clearInterval(pollIndex)
59
+ pollIndex = null
60
+ }
61
+ window.removeEventListener('message', bindCallback)
62
+ })
63
+
64
+ async function bind(type: ThirdPartyType, title = '绑定第三方登录', width = 500, height = 600) {
65
+ if (isThirdPartyBound(type)) {
66
+ return
67
+ }
68
+ if (binding.value) {
69
+ toast.add({ title: '绑定中', description: '绑定进行中,请勿重复点击', color: 'warning' })
70
+ return
71
+ }
72
+ binding.value = true
73
+ window.addEventListener('message', bindCallback)
74
+ const top = (window.screen.height - width) / 2
75
+ const left = (window.screen.width - height) / 2
76
+ const page = window.open(`/api/oauth/${type}/bind`, title, `popup,width=${width},height=${height},top=${top},left=${left}`)
77
+ if (!page) {
78
+ binding.value = false
79
+ toast.add({ title: '登录失败', description: '请允许浏览器弹出窗口!', color: 'error' })
80
+ return
81
+ }
82
+ pollIndex = window.setInterval(() => {
83
+ if (page.closed) {
84
+ binding.value = false
85
+ if (pollIndex != null) {
86
+ clearInterval(pollIndex)
87
+ pollIndex = null
88
+ }
89
+ }
90
+ }, 500)
91
+ }
92
+
93
+ async function bindCallback(e: MessageEvent<{
94
+ success: boolean
95
+ message?: string
96
+ }>) {
97
+ const page = e.source as Window
98
+ if (e.origin !== window.location.origin) {
99
+ return
100
+ }
101
+ if (e.data.success == null) {
102
+ return
103
+ }
104
+ binding.value = false
105
+ window.removeEventListener('message', bindCallback)
106
+ if (pollIndex != null) {
107
+ clearInterval(pollIndex)
108
+ pollIndex = null
109
+ }
110
+ page.close()
111
+ if (e.data.success) {
112
+ await userStore.pullProfile(true)
113
+ toast.add({ title: '绑定成功', color: 'success' })
114
+ }
115
+ else {
116
+ toast.add({ title: '绑定失败', description: e.data.message, color: 'error' })
117
+ }
118
+ }
119
+
120
+ async function unbind(type: ThirdPartyType) {
121
+ if (!isThirdPartyBound(type)) {
122
+ return
123
+ }
124
+ try {
125
+ await userStore.thirdPartyUnbind(type)
126
+ toast.add({ title: '解绑成功', color: 'success' })
127
+ }
128
+ catch (e) {
129
+ toast.add({ title: '解绑失败', description: (e as Error).message, color: 'error' })
130
+ }
131
+ }
132
+
133
+ function isThirdPartyBound(type: ThirdPartyType) {
134
+ return !!(userStore.profile as ThirdPartyProfile | undefined)?.[type]
135
+ }
136
+
137
+ /** ************** 登录设备管理 ***************/
138
+ type DeviceRow = Device & {
139
+ createTime?: string
140
+ lastLoginTime?: string
141
+ }
142
+
143
+ const deviceColumns: TableColumn<DeviceRow>[] = [
144
+ {
145
+ accessorKey: 'name',
146
+ header: '设备名称',
147
+ size: 260,
148
+ },
149
+ {
150
+ accessorKey: 'lastLoginTime',
151
+ header: '最近登录时间',
152
+ meta: {
153
+ class: {
154
+ th: 'text-center',
155
+ td: 'text-center',
156
+ },
157
+ },
158
+ size: 180,
159
+ },
160
+ {
161
+ accessorKey: 'ip',
162
+ header: '登录网段',
163
+ meta: {
164
+ class: {
165
+ th: 'text-center',
166
+ td: 'text-center',
167
+ },
168
+ },
169
+ size: 240,
170
+ },
171
+ {
172
+ id: 'operations',
173
+ header: '操作',
174
+ enableHiding: false,
175
+ meta: {
176
+ class: {
177
+ th: 'text-center',
178
+ td: 'text-center',
179
+ },
180
+ },
181
+ size: 120,
182
+ },
183
+ ]
184
+
185
+ const devices = ref<DeviceRow[]>([])
186
+
187
+ async function manageDevices() {
188
+ try {
189
+ devices.value = await userStore.getDevices()
190
+ }
191
+ catch (e) {
192
+ toast.add({ title: '获取设备列表失败', description: (e as Error).message, color: 'error' })
193
+ }
194
+ }
195
+
196
+ async function removeDevice(options: {
197
+ deviceId?: string
198
+ other?: boolean
199
+ }) {
200
+ try {
201
+ await userStore.removeDevice(options)
202
+ toast.add({ title: '操作成功', color: 'success' })
203
+ await manageDevices()
204
+ }
205
+ catch (e) {}
206
+ }
207
+ </script>
208
+
209
+ <template>
210
+ <div class="w-full h-full flex flex-col gap-4 items-start">
211
+ <div v-if="!userStore.profile" class="flex gap-2">
212
+ <ULink :to="loginPath">
213
+ <UButton color="primary" class="cursor-pointer">
214
+ 登录
215
+ </UButton>
216
+ </ULink>
217
+ <ULink v-if="publicRegister" to="/register">
218
+ <UButton class="cursor-pointer">
219
+ 注册
220
+ </UButton>
221
+ </ULink>
222
+ </div>
223
+ <template v-else>
224
+ <h3 class="text-xl text-pretty font-semibold text-highlighted">
225
+ {{ userStore.profile.nickName }} 欢迎你~
226
+ </h3>
227
+ <div class="flex gap-2">
228
+ <ULink to="/logout">
229
+ <UButton class="cursor-pointer">
230
+ 登出
231
+ </UButton>
232
+ </ULink>
233
+ <ULink
234
+ v-if="showAdminLink"
235
+ :to="adminOrigin"
236
+ target="_blank"
237
+ >
238
+ <UButton
239
+ class="cursor-pointer"
240
+ color="neutral"
241
+ variant="outline"
242
+ icon="i-lucide:external-link"
243
+ >
244
+ 管理后台
245
+ </UButton>
246
+ </ULink>
247
+ </div>
248
+ <USeparator />
249
+ <h3 class="text-xl text-pretty font-semibold text-highlighted">
250
+ 账户信息
251
+ </h3>
252
+ <div class="flex flex-col items-start gap-2">
253
+ <div class="flex items-center gap-2">
254
+ <div class="w-20 text-right">
255
+ 用户名:
256
+ </div>
257
+ <div>
258
+ {{ userStore.profile.userName }}
259
+ </div>
260
+ </div>
261
+ <div class="flex items-center gap-2">
262
+ <div class="w-20 text-right">
263
+ 昵称:
264
+ </div>
265
+ <div>
266
+ {{ userStore.profile.nickName }}
267
+ </div>
268
+ </div>
269
+ <div class="flex items-center gap-2">
270
+ <div class="w-20 text-right">
271
+ 邮箱:
272
+ </div>
273
+ <div>
274
+ {{ userStore.profile.email }}
275
+ </div>
276
+ </div>
277
+ <div class="flex items-center gap-2">
278
+ <div class="w-20 text-right">
279
+ 角色:
280
+ </div>
281
+ <div>
282
+ {{ userStore.profile?.roles?.[0]?.alias ?? '注册用户' }}
283
+ </div>
284
+ </div>
285
+ <div class="flex items-start gap-2">
286
+ <div class="w-20 text-right">
287
+ 三方登录:
288
+ </div>
289
+ <div class="flex flex-col gap-2">
290
+ <div v-for="item in thirdParties" :key="item.type" class="flex gap-2 items-center">
291
+ <div class="w-30 flex gap-2 items-center justify-end">
292
+ <span>{{ item.title }}</span>
293
+ <UIcon :name="item.icon" class="size-5" />
294
+ <span>:</span>
295
+ </div>
296
+ <UButton v-if="isThirdPartyBound(item.type)" variant="link" class="p-0 cursor-pointer" @click="unbind(item.type)">
297
+ 解绑
298
+ </UButton>
299
+ <UButton v-else variant="link" class="p-0 cursor-pointer" @click="bind(item.type, item.title)">
300
+ 绑定
301
+ </UButton>
302
+ </div>
303
+ </div>
304
+ </div>
305
+ </div>
306
+ <div class="flex gap-2">
307
+ <UModal
308
+ title="管理登录设备"
309
+ :ui="{
310
+ content: 'modal-container',
311
+ }"
312
+ >
313
+ <UButton
314
+ class="cursor-pointer"
315
+ color="neutral"
316
+ variant="outline"
317
+ @click="manageDevices"
318
+ >
319
+ 登录设备管理
320
+ </UButton>
321
+ <template #body>
322
+ <div class="flex flex-col gap-3">
323
+ <div class="flex justify-end">
324
+ <UButton
325
+ size="sm"
326
+ color="neutral"
327
+ variant="outline"
328
+ @click="removeDevice({ other: true })"
329
+ >
330
+ 登出所有
331
+ </UButton>
332
+ </div>
333
+
334
+ <UAlert
335
+ v-if="!devices.length"
336
+ color="neutral"
337
+ variant="subtle"
338
+ title="暂无登录设备"
339
+ />
340
+
341
+ <UTable
342
+ v-else
343
+ :data="devices"
344
+ :columns="deviceColumns"
345
+ :column-pinning="{ right: ['operations'] }"
346
+ sticky
347
+ class="w-full rounded-lg border border-muted"
348
+ :ui="{ tr: 'whitespace-nowrap' }"
349
+ >
350
+ <template #name-cell="{ row }">
351
+ <div class="flex items-center gap-2">
352
+ <span class="overflow-hidden text-ellipsis font-medium" :title="row.original.name || row.original.id">
353
+ {{ row.original.name || row.original.id }}
354
+ </span>
355
+ <UBadge v-if="row.original.current" color="primary" variant="subtle">
356
+ 当前设备
357
+ </UBadge>
358
+ </div>
359
+ </template>
360
+
361
+ <template #lastLoginTime-cell="{ row }">
362
+ {{ row.original.lastLoginTime || '-' }}
363
+ </template>
364
+
365
+ <template #ip-cell="{ row }">
366
+ <span class="font-mono" :title="row.original.ip || '未知'">{{ row.original.ip || '未知' }}</span>
367
+ </template>
368
+
369
+ <template #operations-cell="{ row }">
370
+ <UButton
371
+ :disabled="row.original.current"
372
+ size="sm"
373
+ color="neutral"
374
+ variant="outline"
375
+ @click="removeDevice({ deviceId: row.original.id })"
376
+ >
377
+ 登出
378
+ </UButton>
379
+ </template>
380
+ </UTable>
381
+ </div>
382
+ </template>
383
+ </UModal>
384
+ </div>
385
+ </template>
386
+ </div>
387
+ </template>
@@ -0,0 +1,275 @@
1
+ <script setup lang="ts">
2
+ import type { AuthFormField, ButtonProps, FormSubmitEvent } from '@nuxt/ui'
3
+ import type { LocationQuery } from 'vue-router'
4
+ import * as z from 'zod'
5
+ import { useUserStore } from '##stores/user'
6
+
7
+ const { title } = usePublicConfig()
8
+ const router = useRouter()
9
+ const route = useRoute()
10
+ const toast = useToast()
11
+ const userStore = useUserStore()
12
+ const authFeatures = await userStore.getAuthFeatures()
13
+ const seoTitle = computed(() => `用户登录 - ${title}`)
14
+ const seoDescription = '登录账号后可使用需要权限的在线工具,管理个人设置、第三方账号绑定和设备会话。'
15
+ const publicRegister = computed(() => authFeatures.publicRegister)
16
+ const isSsoMode = computed(() => authFeatures.authMode === 'sso')
17
+
18
+ useSeoMeta({
19
+ title: () => seoTitle.value,
20
+ ogTitle: () => seoTitle.value,
21
+ description: seoDescription,
22
+ ogDescription: seoDescription,
23
+ robots: 'noindex,nofollow',
24
+ })
25
+
26
+ const redirect = ref<string>()
27
+ const otherQuery = ref({})
28
+ const error = ref<string>()
29
+ const loading = ref(false)
30
+ const activeLoginTab = ref(isSsoMode.value ? 'sso' : 'local')
31
+ let pollIndex: number | null = null
32
+
33
+ const query = route.query
34
+ if (query) {
35
+ if (typeof query.redirect === 'string') {
36
+ redirect.value = query.redirect
37
+ }
38
+ otherQuery.value = _getOtherQuery(query)
39
+ }
40
+
41
+ const fields: AuthFormField[] = [{
42
+ name: 'userName',
43
+ type: 'text',
44
+ label: '用户名',
45
+ }, {
46
+ name: 'password',
47
+ label: '密码',
48
+ type: 'password',
49
+ }]
50
+
51
+ const providers: ButtonProps[] = [
52
+ {
53
+ label: 'GitHub',
54
+ icon: 'i-simple-icons:github',
55
+ onClick: () => {
56
+ thirdPartyLogin('/api/oauth/github', 'GitHub 登录')
57
+ },
58
+ },
59
+ {
60
+ label: 'Linux Do',
61
+ icon: 'i-iszy-auth:linuxdo',
62
+ onClick: () => {
63
+ thirdPartyLogin('/api/oauth/linuxdo', 'LINUX DO 登录')
64
+ },
65
+ },
66
+ ]
67
+
68
+ const loginTabItems = [
69
+ {
70
+ label: '统一登录',
71
+ icon: 'i-lucide:shield-check',
72
+ value: 'sso',
73
+ },
74
+ {
75
+ label: '账号登录',
76
+ icon: 'i-lucide:lock-keyhole',
77
+ value: 'local',
78
+ },
79
+ ]
80
+
81
+ const schema = z.object({
82
+ userName: z.string('请输入用户名'),
83
+ password: z.string('请输入密码'),
84
+ })
85
+
86
+ type Schema = z.output<typeof schema>
87
+
88
+ onMounted(() => {
89
+ if (userStore.logged) {
90
+ router.push({ path: redirect.value || '/', query: otherQuery.value })
91
+ toast.add({ title: '已登录', description: '您已经登录,无需再次登录', color: 'info' })
92
+ }
93
+ })
94
+
95
+ onBeforeUnmount(() => {
96
+ if (pollIndex != null) {
97
+ clearInterval(pollIndex)
98
+ pollIndex = null
99
+ }
100
+ window.removeEventListener('message', thirdPartyLoginCallback)
101
+ })
102
+
103
+ async function login(payload: FormSubmitEvent<Schema>) {
104
+ if (loading.value) {
105
+ return
106
+ }
107
+ if (!navigator.onLine) {
108
+ toast.add({ title: '网络异常', description: '请检查您的网络连接', color: 'error' })
109
+ return
110
+ }
111
+ try {
112
+ loading.value = true
113
+ error.value = undefined
114
+ await userStore.login(payload.data)
115
+ _afterLogin()
116
+ }
117
+ catch (e) {
118
+ error.value = e instanceof Error ? e.message : '登录失败'
119
+ }
120
+ finally {
121
+ loading.value = false
122
+ }
123
+ }
124
+
125
+ function thirdPartyLogin(url: string, title = '第三方登录', width = 500, height = 600) {
126
+ if (loading.value) {
127
+ toast.add({ title: '登录中', description: '登录进行中,请勿重复点击', color: 'warning' })
128
+ return
129
+ }
130
+ loading.value = true
131
+ error.value = undefined
132
+ window.addEventListener('message', thirdPartyLoginCallback)
133
+ const top = (window.screen.height - width) / 2
134
+ const left = (window.screen.width - height) / 2
135
+ const page = window.open(url, title, `popup,width=${width},height=${height},top=${top},left=${left}`)
136
+ if (!page) {
137
+ loading.value = false
138
+ toast.add({ title: '登录失败', description: '请允许浏览器弹出窗口!', color: 'error' })
139
+ return
140
+ }
141
+ pollIndex = window.setInterval(() => {
142
+ if (page.closed) {
143
+ loading.value = false
144
+ if (pollIndex != null) {
145
+ clearInterval(pollIndex)
146
+ pollIndex = null
147
+ }
148
+ }
149
+ }, 500)
150
+ }
151
+
152
+ function ssoLogin() {
153
+ thirdPartyLogin('/api/oauth/sso', `${authFeatures.sso.title} 登录`, 500, 640)
154
+ }
155
+
156
+ async function thirdPartyLoginCallback(e: MessageEvent<{
157
+ success: boolean
158
+ message?: string
159
+ }>) {
160
+ const page = e.source as Window
161
+ if (e.origin !== window.location.origin) {
162
+ return
163
+ }
164
+ if (e.data.success == null) {
165
+ return
166
+ }
167
+ loading.value = false
168
+ window.removeEventListener('message', thirdPartyLoginCallback)
169
+ if (pollIndex != null) {
170
+ clearInterval(pollIndex)
171
+ pollIndex = null
172
+ }
173
+ page.close()
174
+ if (e.data.success) {
175
+ await userStore.pullProfile(true)
176
+ _afterLogin()
177
+ }
178
+ else {
179
+ error.value = e.data.message || '登录失败'
180
+ }
181
+ }
182
+
183
+ function _afterLogin() {
184
+ toast.add({ title: '登录成功', description: '欢迎回来!', color: 'success' })
185
+ router.push({ path: redirect.value || '/', query: otherQuery.value })
186
+ }
187
+
188
+ function _getOtherQuery(query: LocationQuery) {
189
+ const { redirect, ...result } = query
190
+ return result
191
+ }
192
+ </script>
193
+
194
+ <template>
195
+ <div class="flex flex-col items-center justify-center gap-4 p-4">
196
+ <UPageCard class="w-full max-w-md">
197
+ <template v-if="isSsoMode">
198
+ <div data-slot="header" class="mb-4 flex flex-col text-center">
199
+ <div data-slot="leading" class="mb-2">
200
+ <UIcon name="i-lucide:lock" data-slot="leadingIcon" class="size-8 shrink-0 inline-block" />
201
+ </div>
202
+ <div data-slot="title" class="text-xl text-pretty font-semibold text-highlighted">
203
+ 欢迎回来!
204
+ </div>
205
+ </div>
206
+ <UTabs
207
+ v-model="activeLoginTab"
208
+ class="mb-4"
209
+ :content="false"
210
+ :items="loginTabItems"
211
+ />
212
+ <div v-if="activeLoginTab === 'sso'" class="flex flex-col gap-4">
213
+ <UAlert v-if="error" color="error" icon="i-lucide:info" :title="error" />
214
+ <UButton
215
+ block
216
+ size="lg"
217
+ icon="i-lucide:shield-check"
218
+ :loading="loading"
219
+ @click="ssoLogin"
220
+ >
221
+ {{ authFeatures.sso.title }}
222
+ </UButton>
223
+ </div>
224
+ <UAuthForm
225
+ v-else
226
+ :schema="schema"
227
+ :fields="fields"
228
+ :providers="providers"
229
+ :loading="loading"
230
+ separator="或"
231
+ :submit="{
232
+ label: '登录',
233
+ }"
234
+ @submit="login"
235
+ >
236
+ <template v-if="publicRegister" #footer>
237
+ 没有账户?<ULink to="/register" class="text-primary font-medium">
238
+ 注册
239
+ </ULink>.
240
+ </template>
241
+ <template v-if="error" #validation>
242
+ <UAlert color="error" icon="i-lucide:info" :title="error" />
243
+ </template>
244
+ </UAuthForm>
245
+ </template>
246
+ <UAuthForm
247
+ v-else
248
+ :schema="schema"
249
+ title="欢迎回来!"
250
+ icon="i-lucide:lock"
251
+ :fields="fields"
252
+ :providers="providers"
253
+ :loading="loading"
254
+ separator="或"
255
+ :submit="{
256
+ label: '登录',
257
+ }"
258
+ @submit="login"
259
+ >
260
+ <template v-if="publicRegister" #footer>
261
+ 没有账户?<ULink to="/register" class="text-primary font-medium">
262
+ 注册
263
+ </ULink>.
264
+ </template>
265
+ <template v-if="error" #validation>
266
+ <UAlert color="error" icon="i-lucide:info" :title="error" />
267
+ </template>
268
+ </UAuthForm>
269
+ </UPageCard>
270
+ </div>
271
+ </template>
272
+
273
+ <style scoped lang="scss">
274
+
275
+ </style>
@@ -0,0 +1,53 @@
1
+ <script setup lang="ts">
2
+ import { useUserStore } from '##stores/user'
3
+
4
+ const userStore = useUserStore()
5
+ const router = useRouter()
6
+ const route = useRoute()
7
+ const toast = useToast()
8
+ const { title } = usePublicConfig()
9
+ const seoTitle = computed(() => `退出登录 - ${title}`)
10
+ const seoDescription = '正在退出账号并清理当前登录会话。'
11
+
12
+ definePageMeta({
13
+ layout: 'full',
14
+ })
15
+
16
+ useSeoMeta({
17
+ title: () => seoTitle.value,
18
+ ogTitle: () => seoTitle.value,
19
+ description: seoDescription,
20
+ ogDescription: seoDescription,
21
+ robots: 'noindex,nofollow',
22
+ })
23
+
24
+ onMounted(() => {
25
+ userStore.logout()
26
+ .then(() => {
27
+ toast.add({ title: '登出成功', color: 'success' })
28
+ })
29
+ .catch(() => {
30
+ toast.add({ title: '登出失败', description: '请稍后再试', color: 'error' })
31
+ })
32
+ .finally(() => {
33
+ router.push(!route.redirectedFrom || route.redirectedFrom.path === '/logout' ? '/' : route.redirectedFrom.path)
34
+ })
35
+ })
36
+ </script>
37
+
38
+ <template>
39
+ <div class="flex flex-col items-center justify-center gap-4 p-4">
40
+ <UPageCard class="w-full max-w-md">
41
+ <div data-slot="root" class="w-full space-y-6">
42
+ <div data-slot="header" class="flex flex-col text-center">
43
+ <div data-slot="leading" class="mb-2">
44
+ <UIcon name="i-lucide:lock" data-slot="leadingIcon" class="size-8 shrink-0 inline-block" />
45
+ </div>
46
+ <div data-slot="title" class="text-xl text-pretty font-semibold text-highlighted">
47
+ 登出中...
48
+ </div>
49
+ </div>
50
+ </div>
51
+ </UPageCard>
52
+ </div>
53
+ </template>
@@ -1,6 +1,6 @@
1
1
  import type { Device, ResultDto } from '@zvonimirsun/iszy-common'
2
- import type { PublicSimpleUser } from '##shared/types/auth'
3
- import dayjs from 'dayjs'
2
+ import type { AuthFeatures, PublicSimpleUser } from '##shared/types/auth'
3
+ import type { Fetcher } from '##shared/types/fetcher'
4
4
  import { acceptHMRUpdate, defineStore } from 'pinia'
5
5
 
6
6
  interface LoginAttemptFailureData {
@@ -20,9 +20,22 @@ interface LoginBanFailureData {
20
20
  type LoginFailureData = LoginAttemptFailureData | LoginBanFailureData
21
21
  type LoginResultData = PublicSimpleUser | LoginFailureData
22
22
 
23
+ function formatDeviceTime(value?: string | number | Date) {
24
+ if (!value) {
25
+ return ''
26
+ }
27
+ const date = new Date(value)
28
+ if (Number.isNaN(date.getTime())) {
29
+ return ''
30
+ }
31
+ const pad = (item: number) => item.toString().padStart(2, '0')
32
+ return `${date.getFullYear()}年${pad(date.getMonth() + 1)}月${pad(date.getDate())}日 ${pad(date.getHours())}:${pad(date.getMinutes())}`
33
+ }
34
+
23
35
  export const useUserStore = defineStore('user', () => {
24
36
  const profilePulled = ref(false)
25
37
  const profile = ref<PublicSimpleUser>()
38
+ const authFeatures = ref<AuthFeatures>()
26
39
  const logged = computed(() => {
27
40
  return !!profile.value
28
41
  })
@@ -31,6 +44,7 @@ export const useUserStore = defineStore('user', () => {
31
44
  logged: boolean
32
45
  profile?: PublicSimpleUser
33
46
  }>> | null = null
47
+ let authFeaturesPromise: Promise<AuthFeatures> | null = null
34
48
  let pullProfileResolve: ((value: ResultDto<{ logged: boolean, profile?: PublicSimpleUser }>) => void) | null
35
49
  let pullProfileReject: ((value: unknown) => void) | null
36
50
  let pullProfileAbortController: AbortController | null = null // 用于中断请求
@@ -98,7 +112,32 @@ export const useUserStore = defineStore('user', () => {
98
112
  }
99
113
  }
100
114
 
101
- async function pullProfile(force?: boolean, fetcher: typeof $fetch = $fetch) {
115
+ async function getAuthFeatures(force = false, fetcher: Fetcher = $fetch) {
116
+ if (authFeatures.value && !force) {
117
+ return authFeatures.value
118
+ }
119
+ if (authFeaturesPromise && !force) {
120
+ return authFeaturesPromise
121
+ }
122
+
123
+ authFeaturesPromise = (async () => {
124
+ const res = await fetcher<ResultDto<AuthFeatures>>('/api/auth/features')
125
+ if (!res.success || !res.data) {
126
+ throw new Error(res.message || '获取认证配置失败')
127
+ }
128
+ authFeatures.value = res.data
129
+ return res.data
130
+ })()
131
+
132
+ try {
133
+ return await authFeaturesPromise
134
+ }
135
+ finally {
136
+ authFeaturesPromise = null
137
+ }
138
+ }
139
+
140
+ async function pullProfile(force?: boolean, fetcher: Fetcher = $fetch) {
102
141
  // 1. 非强制刷新且已拉取成功,直接返回
103
142
  if (profilePulled.value && !force) {
104
143
  return true
@@ -171,7 +210,7 @@ export const useUserStore = defineStore('user', () => {
171
210
  return pullProfilePromise
172
211
  }
173
212
 
174
- async function updateProfile(data?: PublicSimpleUser, fetcher?: typeof $fetch) {
213
+ async function updateProfile(data?: PublicSimpleUser, fetcher?: Fetcher) {
175
214
  profile.value = data
176
215
  authEvents.emit('profileUpdated', {
177
216
  profile: data,
@@ -179,7 +218,7 @@ export const useUserStore = defineStore('user', () => {
179
218
  })
180
219
  }
181
220
 
182
- async function removeProfile(fetcher?: typeof $fetch) {
221
+ async function removeProfile(fetcher?: Fetcher) {
183
222
  await updateProfile(undefined, fetcher)
184
223
  authEvents.emit('profileRemoved', {
185
224
  fetcher,
@@ -210,8 +249,8 @@ export const useUserStore = defineStore('user', () => {
210
249
  if (!device.ip) {
211
250
  device.ip = '未知'
212
251
  }
213
- device.createTime = dayjs(device.createdAt!).format('YYYY年MM月DD日 HH:mm')
214
- device.lastLoginTime = dayjs(device.updatedAt!).format('YYYY年MM月DD日 HH:mm')
252
+ device.createTime = formatDeviceTime(device.createdAt)
253
+ device.lastLoginTime = formatDeviceTime(device.updatedAt)
215
254
  return device
216
255
  })
217
256
  }
@@ -243,9 +282,11 @@ export const useUserStore = defineStore('user', () => {
243
282
  return {
244
283
  profilePulled,
245
284
  profile,
285
+ authFeatures,
246
286
  logged,
247
287
  login,
248
288
  logout,
289
+ getAuthFeatures,
249
290
  pullProfile,
250
291
  updateProfile,
251
292
  removeProfile,
@@ -1,9 +1,10 @@
1
1
  import type { PublicSimpleUser } from '##shared/types/auth'
2
+ import type { Fetcher } from '##shared/types/fetcher'
2
3
  import mitt from 'mitt'
3
4
 
4
5
  export interface AuthEventPayload {
5
6
  profile?: PublicSimpleUser
6
- fetcher?: typeof $fetch
7
+ fetcher?: Fetcher
7
8
  }
8
9
 
9
10
  export type AuthEvents = Record<string | symbol, unknown> & {
package/nuxt.config.ts CHANGED
@@ -4,16 +4,27 @@ export default defineNuxtConfig({
4
4
  $meta: {
5
5
  name: 'iszy-nuxt-auth-layer',
6
6
  },
7
+ modules: [
8
+ '@pinia/nuxt',
9
+ '@nuxt/ui',
10
+ ],
7
11
  alias: {
8
12
  '##shared': fileURLToPath(new URL('./shared', import.meta.url)),
13
+ '##stores': fileURLToPath(new URL('./app/stores', import.meta.url)),
9
14
  },
15
+ icon: {
16
+ customCollections: [
17
+ {
18
+ prefix: 'iszy-auth',
19
+ dir: fileURLToPath(new URL('./app/assets/icons', import.meta.url)),
20
+ },
21
+ ],
22
+ },
23
+ compatibilityDate: '2026-06-30',
10
24
  runtimeConfig: {
11
25
  public: {
12
26
  title: '',
13
27
  apiOrigin: '',
14
- features: {
15
- publicRegister: false,
16
- },
17
28
  },
18
29
  redis: {
19
30
  host: '',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zvonimirsun/iszy-nuxt-auth-layer",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "description": "ISZY Nuxt 应用共享认证 layer。",
@@ -27,23 +27,26 @@
27
27
  ],
28
28
  "dependencies": {
29
29
  "@zvonimirsun/iszy-common": "^1.2.0",
30
- "dayjs": "^1.11.21",
31
30
  "mitt": "^3.0.1",
32
31
  "ms": "^2.1.3",
33
- "ofetch": "^1.5.1"
32
+ "ofetch": "^1.5.1",
33
+ "zod": "^4.4.3"
34
34
  },
35
35
  "peerDependencies": {
36
+ "@nuxt/ui": ">=4.0.0",
36
37
  "@pinia/nuxt": ">=0.11.0",
37
38
  "nuxt": ">=4.0.0",
38
39
  "pinia": ">=3.0.0"
39
40
  },
40
41
  "devDependencies": {
41
42
  "@nuxt/eslint": "^1.15.2",
43
+ "@nuxt/ui": "^4.9.0",
42
44
  "@pinia/nuxt": "0.11.3",
43
45
  "@types/ms": "^2.1.0",
44
46
  "@types/node": "^25.9.1",
45
47
  "nuxt": "^4.4.8",
46
48
  "pinia": "^3.0.4",
49
+ "tailwindcss": "^4.3.2",
47
50
  "typescript": "^6.0.3",
48
51
  "vue-tsc": "^3.3.3"
49
52
  },
@@ -51,7 +54,8 @@
51
54
  "access": "public"
52
55
  },
53
56
  "scripts": {
54
- "prepare:types": "nuxt prepare",
55
- "typecheck": "nuxt prepare && nuxt typecheck"
57
+ "dev": "nuxt dev .playground",
58
+ "postinstall": "nuxt prepare .playground",
59
+ "typecheck": "nuxt typecheck .playground"
56
60
  }
57
61
  }
@@ -17,7 +17,7 @@ export default defineEventHandler(async (event): Promise<ResultDto<{
17
17
  }
18
18
 
19
19
  try {
20
- const res = await authFetch<ResultDto<PublicUser>>(event, '/user/me')
20
+ const res = await authFetch(event)<ResultDto<PublicUser>>('/user/me')
21
21
  if (res.success && res.data) {
22
22
  return {
23
23
  success: true,
@@ -0,0 +1,6 @@
1
+ import type { ResultDto } from '@zvonimirsun/iszy-common'
2
+ import type { AuthFeatures } from '##shared/types/auth'
3
+
4
+ export default defineEventHandler(async (event): Promise<ResultDto<AuthFeatures>> => {
5
+ return await authFetch(event)<ResultDto<AuthFeatures>>('/auth/features')
6
+ })
@@ -26,11 +26,11 @@ export default defineEventHandler(async (event): Promise<ResultDto<PublicSimpleU
26
26
  }
27
27
 
28
28
  try {
29
- const res = await authFetch<ResultDto<{
29
+ const res = await authFetch(event)<ResultDto<{
30
30
  access_token: string
31
31
  refresh_token: string
32
32
  profile: PublicUser
33
- }>>(event, '/auth/login', {
33
+ }>>('/auth/login', {
34
34
  method: 'POST',
35
35
  body: {
36
36
  username: body.userName.trim(),
@@ -16,7 +16,7 @@ export default defineEventHandler(async (event): Promise<ResultDto<void>> => {
16
16
  }
17
17
 
18
18
  try {
19
- await authFetch(event, '/auth/logout', {
19
+ await authFetch(event)('/auth/logout', {
20
20
  method: 'POST',
21
21
  query,
22
22
  })
@@ -5,7 +5,7 @@ export default defineEventHandler(async (event) => {
5
5
  const { provider } = event.context.params as { provider: string }
6
6
  const url = getRequestURL(event)
7
7
 
8
- const res = await authFetch<ResultDto<string>>(event, '/oauth/code', {
8
+ const res = await authFetch(event)<ResultDto<string>>('/oauth/code', {
9
9
  method: 'POST',
10
10
  })
11
11
  const code = res.data!
@@ -60,11 +60,11 @@ export default defineEventHandler(async (event) => {
60
60
 
61
61
  if (!errorMessage) {
62
62
  try {
63
- const res = await authFetch<ResultDto<{
63
+ const res = await authFetch(event)<ResultDto<{
64
64
  access_token: string
65
65
  refresh_token: string
66
66
  profile: PublicUser
67
- }>>(event, '/oauth/token', {
67
+ }>>('/oauth/token', {
68
68
  method: 'POST',
69
69
  query: {
70
70
  access_token: code,
@@ -1,8 +1,8 @@
1
1
  import type { PublicUser, ResultDto } from '@zvonimirsun/iszy-common'
2
2
  import type { H3Event } from 'h3'
3
- import type { NitroFetchRequest, TypedInternalResponse } from 'nitropack'
4
3
  import type { FetchError } from 'ofetch'
5
4
  import type { SessionData } from '##shared/types/auth'
5
+ import type { Fetcher } from '##shared/types/fetcher'
6
6
  import { getProxyRequestHeaders } from 'h3'
7
7
 
8
8
  export async function proxyFetch(event: H3Event) {
@@ -10,7 +10,7 @@ export async function proxyFetch(event: H3Event) {
10
10
  const { apiOrigin } = usePublicConfig()
11
11
  const target = apiOrigin + event.path.slice(4)
12
12
 
13
- const headers = getForwardRequestHeaders(event)
13
+ const headers = _getForwardRequestHeaders(event)
14
14
  headers['accept-encoding'] = 'identity'
15
15
 
16
16
  const body = ['GET', 'HEAD'].includes(event.method) ? undefined : await readRawBody(event)
@@ -34,59 +34,63 @@ export async function proxyFetch(event: H3Event) {
34
34
  let res = await doRequest()
35
35
  if (sessionId && res.status === 401) {
36
36
  try {
37
- useRedisSession(event, await refreshWithLock(sessionId, async () => refreshToken(event)))
37
+ useRedisSession(event, await _refreshWithLock(sessionId, async () => _refreshToken(event)))
38
38
  }
39
39
  catch {
40
40
  await destroyRedisSession(event)
41
- return pipeResponse(event, res)
41
+ return _pipeResponse(event, res)
42
42
  }
43
43
  res = await doRequest()
44
44
  }
45
- return pipeResponse(event, res)
45
+ return _pipeResponse(event, res)
46
46
  }
47
47
 
48
- export async function authFetch<T = unknown>(event: H3Event, ...params: Parameters<typeof $fetch>): Promise<TypedInternalResponse<NitroFetchRequest, T>> {
48
+ export function authFetch(event: H3Event): Fetcher {
49
+ return createAuthFetch(event)
50
+ }
51
+
52
+ function createAuthFetch(event: H3Event): Fetcher {
49
53
  const sessionId = getSessionId(event)
50
54
  const { apiOrigin } = usePublicConfig()
51
- const [url, opts = {}] = params
52
- const headers: Record<string, string> = {
53
- ...getForwardRequestHeaders(event),
54
- ...(opts.headers as Record<string, string> | undefined),
55
- }
55
+ const baseFetch = $fetch as (request: unknown, options?: Record<string, unknown>) => Promise<unknown>
56
56
 
57
- opts.headers = headers
58
- opts.baseURL = apiOrigin
59
- const fetcher = $fetch as unknown as (request: NitroFetchRequest, options?: typeof opts) => Promise<T>
60
-
61
- const doRequest = async () => {
57
+ const authFetcher = async (url: unknown, opts: Record<string, unknown> = {}) => {
58
+ const headers: Record<string, string> = {
59
+ ..._getForwardRequestHeaders(event),
60
+ ...(opts.headers as Record<string, string> | undefined),
61
+ }
62
+ opts.headers = headers
63
+ opts.baseURL = apiOrigin
62
64
  if (sessionId) {
63
65
  const sessionData = await getRedisSession(event)
64
66
  if (sessionData) {
65
67
  headers.authorization = `Bearer ${sessionData.access_token}`
66
68
  }
67
69
  }
68
- return fetcher(url, opts)
70
+ return baseFetch(url, opts)
69
71
  }
70
72
 
71
- try {
72
- return await doRequest() as TypedInternalResponse<NitroFetchRequest, T>
73
- }
74
- catch (error) {
75
- if (sessionId && (error as FetchError)?.response?.status === 401) {
76
- try {
77
- useRedisSession(event, await refreshWithLock(sessionId, async () => refreshToken(event)))
78
- return await doRequest() as TypedInternalResponse<NitroFetchRequest, T>
79
- }
80
- catch {
81
- await destroyRedisSession(event)
82
- throw error
73
+ return (async (url: unknown, opts?: Record<string, unknown>) => {
74
+ try {
75
+ return await authFetcher(url, opts)
76
+ }
77
+ catch (error) {
78
+ if (sessionId && (error as FetchError)?.response?.status === 401) {
79
+ try {
80
+ useRedisSession(event, await _refreshWithLock(sessionId, async () => _refreshToken(event)))
81
+ return await authFetcher(url, opts)
82
+ }
83
+ catch {
84
+ await destroyRedisSession(event)
85
+ throw error
86
+ }
83
87
  }
88
+ throw error
84
89
  }
85
- throw error
86
- }
90
+ }) as Fetcher
87
91
  }
88
92
 
89
- async function refreshToken(event: H3Event): Promise<SessionData> {
93
+ async function _refreshToken(event: H3Event): Promise<SessionData> {
90
94
  const sessionData = await getRedisSession(event)
91
95
  if (!sessionData) {
92
96
  throw new Error('REFRESH_FAILED')
@@ -100,7 +104,7 @@ async function refreshToken(event: H3Event): Promise<SessionData> {
100
104
  }>>(`${apiOrigin}/auth/refresh`, {
101
105
  method: 'POST',
102
106
  headers: {
103
- ...getForwardRequestHeaders(event),
107
+ ..._getForwardRequestHeaders(event),
104
108
  Authorization: `Bearer ${sessionData.refresh_token}`,
105
109
  },
106
110
  })
@@ -117,7 +121,7 @@ async function refreshToken(event: H3Event): Promise<SessionData> {
117
121
 
118
122
  const locks = new Map<string, Promise<SessionData>>()
119
123
 
120
- async function refreshWithLock(sessionId: string, fn: () => Promise<SessionData>) {
124
+ async function _refreshWithLock(sessionId: string, fn: () => Promise<SessionData>) {
121
125
  if (locks.has(sessionId)) {
122
126
  return locks.get(sessionId)!
123
127
  }
@@ -135,7 +139,7 @@ async function refreshWithLock(sessionId: string, fn: () => Promise<SessionData>
135
139
  return promise
136
140
  }
137
141
 
138
- function getForwardRequestHeaders(event: H3Event) {
142
+ function _getForwardRequestHeaders(event: H3Event) {
139
143
  const headers = getProxyRequestHeaders(event, { host: false })
140
144
  const remoteAddr = getRequestIP(event, { xForwardedFor: true }) || ''
141
145
  const xForwardedFor = headers['x-forwarded-for'] || remoteAddr
@@ -149,7 +153,7 @@ function getForwardRequestHeaders(event: H3Event) {
149
153
  return headers
150
154
  }
151
155
 
152
- async function pipeResponse(event: H3Event, res: Response) {
156
+ async function _pipeResponse(event: H3Event, res: Response) {
153
157
  setResponseStatus(event, res.status)
154
158
  for (const [key, value] of res.headers) {
155
159
  if (key.toLowerCase() === 'set-cookie') {
@@ -17,3 +17,11 @@ export interface SessionTombstone {
17
17
  export interface OAuthStateData {
18
18
  isBind?: boolean
19
19
  }
20
+
21
+ export interface AuthFeatures {
22
+ authMode: 'local' | 'sso'
23
+ publicRegister: boolean
24
+ sso: {
25
+ title: string
26
+ }
27
+ }
@@ -0,0 +1,3 @@
1
+ import type { $Fetch } from 'nitropack'
2
+
3
+ export type Fetcher = $Fetch