@zvonimirsun/iszy-nuxt-auth-layer 0.2.2 → 0.2.4

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,7 +1,8 @@
1
1
  <script setup lang="ts">
2
- import type { TableColumn } from '@nuxt/ui'
2
+ import type { FormSubmitEvent, TableColumn } from '@nuxt/ui'
3
3
  import type { Device } from '@zvonimirsun/iszy-common'
4
4
  import { RoleEnum } from '@zvonimirsun/iszy-common'
5
+ import * as z from 'zod'
5
6
  import { useUserStore } from '##stores/user'
6
7
 
7
8
  const props = defineProps<{
@@ -21,6 +22,96 @@ const showAdminLink = computed(() => {
21
22
  })
22
23
  })
23
24
 
25
+ /** ************** 账户资料 ***************/
26
+
27
+ const profileSaving = ref(false)
28
+ const passwordSaving = ref(false)
29
+ const profileState = reactive({
30
+ userName: '',
31
+ nickName: '',
32
+ email: '',
33
+ mobile: '',
34
+ })
35
+ const passwordState = reactive({
36
+ oldPasswd: '',
37
+ passwd: '',
38
+ confirmPasswd: '',
39
+ })
40
+
41
+ const profileSchema = z.object({
42
+ userName: z.string().trim().min(1, '请输入用户名'),
43
+ nickName: z.string().trim().min(1, '请输入昵称'),
44
+ email: z.string().trim().refine(value => !value || z.email().safeParse(value).success, '请输入有效的邮箱地址'),
45
+ mobile: z.string().trim().optional(),
46
+ })
47
+ const passwordSchema = z.object({
48
+ oldPasswd: z.string().optional(),
49
+ passwd: z.string().min(1, '请输入新密码'),
50
+ confirmPasswd: z.string().min(1, '请再次输入新密码'),
51
+ }).refine(data => data.passwd === data.confirmPasswd, {
52
+ message: '两次输入的新密码不一致',
53
+ path: ['confirmPasswd'],
54
+ })
55
+
56
+ type ProfileSchema = z.output<typeof profileSchema>
57
+ type PasswordSchema = z.output<typeof passwordSchema>
58
+
59
+ watch(
60
+ () => userStore.profile,
61
+ (profile) => {
62
+ profileState.userName = profile?.userName || ''
63
+ profileState.nickName = profile?.nickName || ''
64
+ profileState.email = profile?.email || ''
65
+ profileState.mobile = profile?.mobile || ''
66
+ },
67
+ { immediate: true },
68
+ )
69
+
70
+ async function updateProfile(payload: FormSubmitEvent<ProfileSchema>) {
71
+ if (profileSaving.value) {
72
+ return
73
+ }
74
+ profileSaving.value = true
75
+ try {
76
+ await userStore.updateCurrentUser({
77
+ userName: payload.data.userName.trim(),
78
+ nickName: payload.data.nickName.trim(),
79
+ email: payload.data.email?.trim() || undefined,
80
+ mobile: payload.data.mobile?.trim() || undefined,
81
+ })
82
+ toast.add({ title: '账户资料已更新', color: 'success' })
83
+ }
84
+ catch (error) {
85
+ toast.add({ title: '更新账户资料失败', description: getErrorMessage(error), color: 'error' })
86
+ }
87
+ finally {
88
+ profileSaving.value = false
89
+ }
90
+ }
91
+
92
+ async function updatePassword(payload: FormSubmitEvent<PasswordSchema>) {
93
+ if (passwordSaving.value) {
94
+ return
95
+ }
96
+ passwordSaving.value = true
97
+ try {
98
+ await userStore.updateCurrentUser({
99
+ oldPasswd: payload.data.oldPasswd || undefined,
100
+ passwd: payload.data.passwd,
101
+ })
102
+ passwordState.oldPasswd = ''
103
+ passwordState.passwd = ''
104
+ passwordState.confirmPasswd = ''
105
+ toast.add({ title: '登录密码已更新', color: 'success' })
106
+ }
107
+ catch (error) {
108
+ toast.add({ title: '更新登录密码失败', description: getErrorMessage(error), color: 'error' })
109
+ }
110
+ finally {
111
+ passwordSaving.value = false
112
+ }
113
+ }
114
+
24
115
  /** ************** 三方登录绑定 ***************/
25
116
 
26
117
  type LoginProviderType = 'github' | 'linuxdo' | 'sso'
@@ -127,7 +218,7 @@ async function unbind(type: LoginProviderType) {
127
218
  toast.add({ title: '解绑成功', color: 'success' })
128
219
  }
129
220
  catch (e) {
130
- toast.add({ title: '解绑失败', description: (e as Error).message, color: 'error' })
221
+ toast.add({ title: '解绑失败', description: getErrorMessage(e), color: 'error' })
131
222
  }
132
223
  }
133
224
 
@@ -205,6 +296,14 @@ async function removeDevice(options: {
205
296
  }
206
297
  catch (e) {}
207
298
  }
299
+
300
+ function getErrorMessage(error: unknown) {
301
+ const normalized = error as {
302
+ data?: { message?: string }
303
+ message?: string
304
+ }
305
+ return normalized.data?.message || normalized.message || '操作失败'
306
+ }
208
307
  </script>
209
308
 
210
309
  <template>
@@ -247,9 +346,79 @@ async function removeDevice(options: {
247
346
  </ULink>
248
347
  </div>
249
348
  <USeparator />
250
- <h3 class="text-xl text-pretty font-semibold text-highlighted">
251
- 账户信息
252
- </h3>
349
+ <div class="flex items-center gap-3">
350
+ <h3 class="text-xl text-pretty font-semibold text-highlighted">
351
+ 账户信息
352
+ </h3>
353
+ <UModal title="编辑账户资料">
354
+ <UButton
355
+ size="sm"
356
+ color="neutral"
357
+ variant="outline"
358
+ icon="i-lucide:edit-3"
359
+ >
360
+ 编辑资料
361
+ </UButton>
362
+ <template #body>
363
+ <UForm
364
+ :schema="profileSchema"
365
+ :state="profileState"
366
+ class="flex flex-col gap-4"
367
+ @submit="updateProfile"
368
+ >
369
+ <UFormField label="用户名" name="userName" required>
370
+ <UInput v-model="profileState.userName" class="w-full" autocomplete="username" />
371
+ </UFormField>
372
+ <UFormField label="昵称" name="nickName" required>
373
+ <UInput v-model="profileState.nickName" class="w-full" autocomplete="nickname" />
374
+ </UFormField>
375
+ <UFormField label="邮箱" name="email">
376
+ <UInput v-model="profileState.email" class="w-full" type="email" autocomplete="email" />
377
+ </UFormField>
378
+ <UFormField label="手机号" name="mobile">
379
+ <UInput v-model="profileState.mobile" class="w-full" autocomplete="tel" />
380
+ </UFormField>
381
+ <UButton block type="submit" :loading="profileSaving">
382
+ 保存
383
+ </UButton>
384
+ </UForm>
385
+ </template>
386
+ </UModal>
387
+ <UModal title="设置或修改登录密码">
388
+ <UButton
389
+ size="sm"
390
+ color="neutral"
391
+ variant="outline"
392
+ icon="i-lucide:key-round"
393
+ >
394
+ 设置密码
395
+ </UButton>
396
+ <template #body>
397
+ <UForm
398
+ :schema="passwordSchema"
399
+ :state="passwordState"
400
+ class="flex flex-col gap-4"
401
+ @submit="updatePassword"
402
+ >
403
+ <p class="text-sm text-muted">
404
+ 已有登录密码时需要填写旧密码;历史 SSO 无密码账户可直接设置新密码。
405
+ </p>
406
+ <UFormField label="旧密码" name="oldPasswd">
407
+ <UInput v-model="passwordState.oldPasswd" class="w-full" type="password" autocomplete="current-password" />
408
+ </UFormField>
409
+ <UFormField label="新密码" name="passwd" required>
410
+ <UInput v-model="passwordState.passwd" class="w-full" type="password" autocomplete="new-password" />
411
+ </UFormField>
412
+ <UFormField label="确认新密码" name="confirmPasswd" required>
413
+ <UInput v-model="passwordState.confirmPasswd" class="w-full" type="password" autocomplete="new-password" />
414
+ </UFormField>
415
+ <UButton block type="submit" :loading="passwordSaving">
416
+ 保存
417
+ </UButton>
418
+ </UForm>
419
+ </template>
420
+ </UModal>
421
+ </div>
253
422
  <div class="flex flex-col items-start gap-2">
254
423
  <div class="flex items-center gap-2">
255
424
  <div class="w-20 text-right">
@@ -272,7 +441,15 @@ async function removeDevice(options: {
272
441
  邮箱:
273
442
  </div>
274
443
  <div>
275
- {{ userStore.profile.email }}
444
+ {{ userStore.profile.email || '-' }}
445
+ </div>
446
+ </div>
447
+ <div class="flex items-center gap-2">
448
+ <div class="w-20 text-right">
449
+ 手机号:
450
+ </div>
451
+ <div>
452
+ {{ userStore.profile.mobile || '-' }}
276
453
  </div>
277
454
  </div>
278
455
  <div class="flex items-center gap-2">
@@ -1,5 +1,5 @@
1
- import type { Device, ResultDto } from '@zvonimirsun/iszy-common'
2
- import type { AuthFeatures, PublicSimpleUser } from '##shared/types/auth'
1
+ import type { Device, PublicUser, ResultDto } from '@zvonimirsun/iszy-common'
2
+ import type { AuthFeatures, PublicSimpleUser, UpdateUser } from '##shared/types/auth'
3
3
  import type { Fetcher } from '##shared/types/fetcher'
4
4
  import { acceptHMRUpdate, defineStore } from 'pinia'
5
5
 
@@ -237,6 +237,18 @@ export const useUserStore = defineStore('user', () => {
237
237
  await pullProfile(true)
238
238
  }
239
239
 
240
+ async function updateCurrentUser(profile: UpdateUser) {
241
+ const res = await $fetch<ResultDto<PublicUser>>('/api/user/me', {
242
+ method: 'PUT',
243
+ body: profile,
244
+ })
245
+ if (!res.success || !res.data) {
246
+ throw new Error(res.message || '更新账户信息失败')
247
+ }
248
+ await updateProfile(res.data)
249
+ return res.data
250
+ }
251
+
240
252
  async function getDevices(): Promise<(Device & {
241
253
  createTime?: string
242
254
  lastLoginTime?: string
@@ -290,6 +302,7 @@ export const useUserStore = defineStore('user', () => {
290
302
  pullProfile,
291
303
  updateProfile,
292
304
  removeProfile,
305
+ updateCurrentUser,
293
306
  thirdPartyUnbind,
294
307
  getDevices,
295
308
  removeDevice,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zvonimirsun/iszy-nuxt-auth-layer",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "description": "ISZY Nuxt 应用共享认证 layer。",
@@ -41,6 +41,7 @@
41
41
  "pinia": ">=3.0.0"
42
42
  },
43
43
  "devDependencies": {
44
+ "@iconify-json/lucide": "^1.2.117",
44
45
  "@nuxt/eslint": "^1.15.2",
45
46
  "@nuxt/ui": "^4.9.0",
46
47
  "@pinia/nuxt": "0.11.3",
@@ -1,19 +1,4 @@
1
- import type { ResultDto } from '@zvonimirsun/iszy-common'
2
-
3
1
  export default defineEventHandler(async (event) => {
4
- const { apiOrigin } = usePublicConfig()
5
2
  const { provider } = event.context.params as { provider: string }
6
- const url = getRequestURL(event)
7
-
8
- const res = await authFetch(event)<ResultDto<string>>('/oauth/code', {
9
- method: 'POST',
10
- })
11
- const code = res.data!
12
- const state = randomState()
13
-
14
- await setState(state, {
15
- isBind: true,
16
- })
17
-
18
- return sendRedirect(event, `${apiOrigin}/oauth/${provider}/bind?state=${state}&client=${encodeURIComponent(url.origin)}&access_token=${code}`)
3
+ return redirectToOAuthProviderBind(event, provider)
19
4
  })
@@ -1,106 +1,4 @@
1
- import type { PublicUser, ResultDto } from '@zvonimirsun/iszy-common'
2
-
3
- function renderCallbackPage(title: string, origin: string, body: string, payload: { success: boolean, message?: string }) {
4
- return `
5
- <head>
6
- <title>${title}</title>
7
- <meta charset="UTF-8">
8
- </head>
9
- <body>
10
- ${body}
11
- <script>
12
- if (window.opener && !window.opener.closed) {
13
- window.opener.postMessage(${JSON.stringify(payload)}, '${origin}');
14
- }
15
- </script>
16
- </body>
17
- `
18
- }
19
-
20
1
  export default defineEventHandler(async (event) => {
21
- const { title } = usePublicConfig()
22
2
  const { provider } = event.context.params as { provider: string }
23
- const url = getRequestURL(event)
24
- const query = getQuery(event)
25
- const state = query.state as string
26
-
27
- if (!state) {
28
- throw createError({
29
- statusCode: 400,
30
- message: '缺少 state 参数',
31
- })
32
- }
33
-
34
- const stateData = await getState(state)
35
- if (!stateData) {
36
- throw createError({
37
- statusCode: 400,
38
- message: '无效的 state 参数',
39
- })
40
- }
41
-
42
- await removeState(state)
43
-
44
- if (stateData.isBind) {
45
- const error = query.error as string | undefined
46
- if (error) {
47
- return renderCallbackPage(`${title} - 绑定失败`, url.origin, error, {
48
- success: false,
49
- message: error,
50
- })
51
- }
52
-
53
- return renderCallbackPage(`${title} - 绑定成功`, url.origin, '验证成功', {
54
- success: true,
55
- })
56
- }
57
-
58
- const pendingToken = typeof query.pending_token === 'string' ? query.pending_token : undefined
59
- if (provider === 'sso' && pendingToken) {
60
- const completionId = await createSsoCompletion(event, pendingToken)
61
- return sendRedirect(event, `/sso/complete?flow=${completionId}`)
62
- }
63
-
64
- const code = query.code as string
65
- const error = query.error as string | undefined
66
- let errorMessage = error || (!code ? '缺少 code 参数' : '')
67
-
68
- if (!errorMessage) {
69
- try {
70
- const res = await authFetch(event)<ResultDto<{
71
- access_token: string
72
- refresh_token: string
73
- profile: PublicUser
74
- }>>('/oauth/token', {
75
- method: 'POST',
76
- query: {
77
- access_token: code,
78
- },
79
- })
80
-
81
- if (!res.success) {
82
- errorMessage = '获取 token 失败'
83
- }
84
- else {
85
- await setRedisSession(event, {
86
- access_token: res.data!.access_token,
87
- refresh_token: res.data!.refresh_token,
88
- })
89
- }
90
- }
91
- catch {
92
- errorMessage = '获取 token 失败'
93
- }
94
- }
95
-
96
- if (errorMessage) {
97
- return renderCallbackPage(`${title} - 登录失败`, url.origin, errorMessage, {
98
- success: false,
99
- message: errorMessage,
100
- })
101
- }
102
-
103
- return renderCallbackPage(`${title} - 登录成功`, url.origin, '登录成功', {
104
- success: true,
105
- })
3
+ return handleOAuthProviderCallback(event, provider)
106
4
  })
@@ -1,10 +1,4 @@
1
1
  export default defineEventHandler(async (event) => {
2
- const { apiOrigin } = usePublicConfig()
3
2
  const { provider } = event.context.params as { provider: string }
4
- const url = getRequestURL(event)
5
- const state = randomState()
6
-
7
- await setState(state, {})
8
-
9
- return sendRedirect(event, `${apiOrigin}/oauth/${provider}?state=${state}&client=${encodeURIComponent(url.origin)}`)
3
+ return redirectToOAuthProvider(event, provider)
10
4
  })
@@ -0,0 +1,3 @@
1
+ export default defineEventHandler(async (event) => {
2
+ return redirectToOAuthProviderBind(event, 'sso')
3
+ })
@@ -0,0 +1,3 @@
1
+ export default defineEventHandler(async (event) => {
2
+ return handleOAuthProviderCallback(event, 'sso')
3
+ })
@@ -0,0 +1,3 @@
1
+ export default defineEventHandler(async (event) => {
2
+ return redirectToOAuthProvider(event, 'sso')
3
+ })
@@ -0,0 +1,133 @@
1
+ import type { PublicUser, ResultDto } from '@zvonimirsun/iszy-common'
2
+ import type { H3Event } from 'h3'
3
+
4
+ function renderCallbackPage(title: string, origin: string, body: string, payload: { success: boolean, message?: string }) {
5
+ return `
6
+ <head>
7
+ <title>${title}</title>
8
+ <meta charset="UTF-8">
9
+ </head>
10
+ <body>
11
+ ${body}
12
+ <script>
13
+ if (window.opener && !window.opener.closed) {
14
+ window.opener.postMessage(${JSON.stringify(payload)}, '${origin}');
15
+ }
16
+ </script>
17
+ </body>
18
+ `
19
+ }
20
+
21
+ export async function redirectToOAuthProvider(event: H3Event, provider: string) {
22
+ const { apiOrigin } = usePublicConfig()
23
+ const url = getRequestURL(event)
24
+ const state = randomState()
25
+
26
+ await setState(state, {})
27
+
28
+ return sendRedirect(event, `${apiOrigin}/oauth/${provider}?state=${state}&client=${encodeURIComponent(url.origin)}`)
29
+ }
30
+
31
+ export async function redirectToOAuthProviderBind(event: H3Event, provider: string) {
32
+ const { apiOrigin } = usePublicConfig()
33
+ const url = getRequestURL(event)
34
+
35
+ const res = await authFetch(event)<ResultDto<string>>('/oauth/code', {
36
+ method: 'POST',
37
+ })
38
+ const code = res.data!
39
+ const state = randomState()
40
+
41
+ await setState(state, {
42
+ isBind: true,
43
+ })
44
+
45
+ return sendRedirect(event, `${apiOrigin}/oauth/${provider}/bind?state=${state}&client=${encodeURIComponent(url.origin)}&access_token=${code}`)
46
+ }
47
+
48
+ export async function handleOAuthProviderCallback(event: H3Event, provider: string) {
49
+ const { title } = usePublicConfig()
50
+ const url = getRequestURL(event)
51
+ const query = getQuery(event)
52
+ const state = query.state as string
53
+
54
+ if (!state) {
55
+ throw createError({
56
+ statusCode: 400,
57
+ message: '缺少 state 参数',
58
+ })
59
+ }
60
+
61
+ const stateData = await getState(state)
62
+ if (!stateData) {
63
+ throw createError({
64
+ statusCode: 400,
65
+ message: '无效的 state 参数',
66
+ })
67
+ }
68
+
69
+ await removeState(state)
70
+
71
+ if (stateData.isBind) {
72
+ const error = query.error as string | undefined
73
+ if (error) {
74
+ return renderCallbackPage(`${title} - 绑定失败`, url.origin, error, {
75
+ success: false,
76
+ message: error,
77
+ })
78
+ }
79
+
80
+ return renderCallbackPage(`${title} - 绑定成功`, url.origin, '验证成功', {
81
+ success: true,
82
+ })
83
+ }
84
+
85
+ const pendingToken = typeof query.pending_token === 'string' ? query.pending_token : undefined
86
+ if (provider === 'sso' && pendingToken) {
87
+ const completionId = await createSsoCompletion(event, pendingToken)
88
+ return sendRedirect(event, `/sso/complete?flow=${completionId}`)
89
+ }
90
+
91
+ const code = query.code as string
92
+ const error = query.error as string | undefined
93
+ let errorMessage = error || (!code ? '缺少 code 参数' : '')
94
+
95
+ if (!errorMessage) {
96
+ try {
97
+ const res = await authFetch(event)<ResultDto<{
98
+ access_token: string
99
+ refresh_token: string
100
+ profile: PublicUser
101
+ }>>('/oauth/token', {
102
+ method: 'POST',
103
+ query: {
104
+ access_token: code,
105
+ },
106
+ })
107
+
108
+ if (!res.success) {
109
+ errorMessage = '获取 token 失败'
110
+ }
111
+ else {
112
+ await setRedisSession(event, {
113
+ access_token: res.data!.access_token,
114
+ refresh_token: res.data!.refresh_token,
115
+ })
116
+ }
117
+ }
118
+ catch {
119
+ errorMessage = '获取 token 失败'
120
+ }
121
+ }
122
+
123
+ if (errorMessage) {
124
+ return renderCallbackPage(`${title} - 登录失败`, url.origin, errorMessage, {
125
+ success: false,
126
+ message: errorMessage,
127
+ })
128
+ }
129
+
130
+ return renderCallbackPage(`${title} - 登录成功`, url.origin, '登录成功', {
131
+ success: true,
132
+ })
133
+ }
@@ -1,6 +0,0 @@
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
- })