@zvonimirsun/iszy-nuxt-auth-layer 0.1.9 → 0.2.1
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 +11 -1
- package/app/pages/login.vue +62 -3
- package/app/pages/sso/complete.vue +308 -0
- package/package.json +3 -1
- package/server/api/oauth/[provider]/callback.get.ts +7 -0
- package/server/api/oauth/sso/completion/bind.post.ts +71 -0
- package/server/api/oauth/sso/completion/create.post.ts +74 -0
- package/server/api/oauth/sso/completion/start.post.ts +31 -0
- package/server/api/oauth/sso/completion.get.ts +31 -0
- package/server/utils/ssoCompletionError.ts +13 -0
- package/server/utils/ssoCompletionStore.ts +77 -0
- package/shared/types/auth.ts +32 -0
package/README.md
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
- session 轮换与短 TTL tombstone,降低并发刷新 token 时的竞态影响。
|
|
9
9
|
- 后端 API 代理工具,自动注入 access token,并在 401 时尝试 refresh token。
|
|
10
10
|
- 本地登录、登出、登录态检查和 OAuth 回调路由。
|
|
11
|
+
- SSO 首次登录账户完成流程:可验证并绑定已有账户,或创建并绑定新账户。
|
|
11
12
|
- 通用用户 store、公开用户类型和用户信息裁剪工具。
|
|
12
13
|
|
|
13
14
|
## 使用方式
|
|
@@ -60,4 +61,13 @@ export default defineNuxtConfig({
|
|
|
60
61
|
|
|
61
62
|
- `iszy-admin` 仍应在消费方保留 admin/superadmin 鉴权和 403 页面语义。
|
|
62
63
|
- `iszy-tools-next` 仍应在消费方保留工具权限、工具目录刷新和设置页展示逻辑。
|
|
63
|
-
|
|
64
|
+
|
|
65
|
+
## SSO 首次登录
|
|
66
|
+
|
|
67
|
+
当 SSO subject 尚未关联本地用户时,回调不会直接创建账户,而是进入短期的账户完成流程:
|
|
68
|
+
|
|
69
|
+
- 选择“绑定已有账户”时,通过用户名或 SSO 建议邮箱及密码验证本地账户,验证成功后绑定 SSO。
|
|
70
|
+
- 选择“创建新账户”时,可以使用 SSO 建议的用户名、昵称和邮箱创建账户,并同时绑定 SSO。
|
|
71
|
+
- SSO 创建的账户始终为启用状态,不受 `publicRegister` 配置影响。
|
|
72
|
+
- 待完成凭证只保存在服务端 Redis 中;浏览器只持有独立的 opaque flow ID 与对应的 httpOnly 流程 cookie,多个并发登录流程不会相互覆盖。
|
|
73
|
+
- 当前流程不包含邮箱验证码、邀请码或头像同步。
|
package/app/pages/login.vue
CHANGED
|
@@ -4,7 +4,7 @@ import type { LocationQuery } from 'vue-router'
|
|
|
4
4
|
import * as z from 'zod'
|
|
5
5
|
import { useUserStore } from '##stores/user'
|
|
6
6
|
|
|
7
|
-
const { title } = usePublicConfig()
|
|
7
|
+
const { title, apiOrigin } = usePublicConfig()
|
|
8
8
|
const router = useRouter()
|
|
9
9
|
const route = useRoute()
|
|
10
10
|
const toast = useToast()
|
|
@@ -150,15 +150,24 @@ function thirdPartyLogin(url: string, title = '第三方登录', width = 500, he
|
|
|
150
150
|
}
|
|
151
151
|
|
|
152
152
|
function ssoLogin() {
|
|
153
|
-
thirdPartyLogin('/api/oauth/sso', `${authFeatures.sso.title} 登录`,
|
|
153
|
+
thirdPartyLogin('/api/oauth/sso', `${authFeatures.sso.title} 登录`, 560, 760)
|
|
154
154
|
}
|
|
155
155
|
|
|
156
156
|
async function thirdPartyLoginCallback(e: MessageEvent<{
|
|
157
157
|
success: boolean
|
|
158
158
|
message?: string
|
|
159
|
+
type?: string
|
|
160
|
+
data?: {
|
|
161
|
+
pending_token?: string
|
|
162
|
+
pendingToken?: string
|
|
163
|
+
}
|
|
159
164
|
}>) {
|
|
160
165
|
const page = e.source as Window
|
|
161
|
-
if (e.origin
|
|
166
|
+
if (!isAllowedOAuthMessageOrigin(e.origin)) {
|
|
167
|
+
return
|
|
168
|
+
}
|
|
169
|
+
if (e.data.type === 'sso_completion_required') {
|
|
170
|
+
await startSsoCompletion(page, e.data.data?.pending_token || e.data.data?.pendingToken)
|
|
162
171
|
return
|
|
163
172
|
}
|
|
164
173
|
if (e.data.success == null) {
|
|
@@ -180,6 +189,56 @@ async function thirdPartyLoginCallback(e: MessageEvent<{
|
|
|
180
189
|
}
|
|
181
190
|
}
|
|
182
191
|
|
|
192
|
+
async function startSsoCompletion(page: Window, pendingToken?: string) {
|
|
193
|
+
if (!pendingToken) {
|
|
194
|
+
loading.value = false
|
|
195
|
+
error.value = 'SSO 登录缺少待绑定凭证'
|
|
196
|
+
return
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
try {
|
|
200
|
+
const res = await $fetch<{
|
|
201
|
+
success: boolean
|
|
202
|
+
message: string
|
|
203
|
+
data?: {
|
|
204
|
+
flow: string
|
|
205
|
+
}
|
|
206
|
+
}>('/api/oauth/sso/completion/start', {
|
|
207
|
+
method: 'POST',
|
|
208
|
+
body: {
|
|
209
|
+
pendingToken,
|
|
210
|
+
},
|
|
211
|
+
})
|
|
212
|
+
|
|
213
|
+
if (!res.success || !res.data?.flow) {
|
|
214
|
+
throw new Error(res.message || 'SSO 登录流程创建失败')
|
|
215
|
+
}
|
|
216
|
+
page.location.href = `/sso/complete?flow=${encodeURIComponent(res.data.flow)}`
|
|
217
|
+
}
|
|
218
|
+
catch (err) {
|
|
219
|
+
loading.value = false
|
|
220
|
+
window.removeEventListener('message', thirdPartyLoginCallback)
|
|
221
|
+
if (pollIndex != null) {
|
|
222
|
+
clearInterval(pollIndex)
|
|
223
|
+
pollIndex = null
|
|
224
|
+
}
|
|
225
|
+
error.value = err instanceof Error ? err.message : 'SSO 登录流程创建失败'
|
|
226
|
+
page.close()
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function isAllowedOAuthMessageOrigin(origin: string) {
|
|
231
|
+
if (origin === window.location.origin) {
|
|
232
|
+
return true
|
|
233
|
+
}
|
|
234
|
+
try {
|
|
235
|
+
return origin === new URL(apiOrigin).origin
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
return false
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
183
242
|
function _afterLogin() {
|
|
184
243
|
toast.add({ title: '登录成功', description: '欢迎回来!', color: 'success' })
|
|
185
244
|
router.push({ path: redirect.value || '/', query: otherQuery.value })
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
import type { FormSubmitEvent } from '@nuxt/ui'
|
|
3
|
+
import type { ResultDto } from '@zvonimirsun/iszy-common'
|
|
4
|
+
import type {
|
|
5
|
+
PublicSimpleUser,
|
|
6
|
+
SsoCompletionBindBody,
|
|
7
|
+
SsoCompletionCreateBody,
|
|
8
|
+
SsoCompletionProfile,
|
|
9
|
+
} from '##shared/types/auth'
|
|
10
|
+
import * as z from 'zod'
|
|
11
|
+
|
|
12
|
+
definePageMeta({
|
|
13
|
+
layout: false,
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
const { title } = usePublicConfig()
|
|
17
|
+
const route = useRoute()
|
|
18
|
+
const requestFetch = useRequestFetch()
|
|
19
|
+
const step = ref<'choice' | 'bind' | 'create'>('choice')
|
|
20
|
+
const loading = ref(false)
|
|
21
|
+
const submitError = ref<string>()
|
|
22
|
+
const completionExpired = ref(false)
|
|
23
|
+
const flowId = typeof route.query.flow === 'string' ? route.query.flow : ''
|
|
24
|
+
const completionQuery = `?flow=${encodeURIComponent(flowId)}`
|
|
25
|
+
|
|
26
|
+
useSeoMeta({
|
|
27
|
+
title: () => `完成 SSO 登录 - ${title}`,
|
|
28
|
+
robots: 'noindex,nofollow',
|
|
29
|
+
})
|
|
30
|
+
useHead({
|
|
31
|
+
meta: [
|
|
32
|
+
{ name: 'referrer', content: 'no-referrer' },
|
|
33
|
+
],
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
const { data: profile, error: profileError } = await useAsyncData('sso-completion-profile', async () => {
|
|
37
|
+
try {
|
|
38
|
+
const res = await requestFetch<ResultDto<SsoCompletionProfile>>(`/api/oauth/sso/completion${completionQuery}`)
|
|
39
|
+
if (!res.success || !res.data) {
|
|
40
|
+
throw new Error(res.message || '获取 SSO 账户信息失败')
|
|
41
|
+
}
|
|
42
|
+
return res.data
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
if (getErrorStatus(error) === 410) {
|
|
46
|
+
completionExpired.value = true
|
|
47
|
+
}
|
|
48
|
+
throw new Error(getErrorMessage(error, '获取 SSO 账户信息失败'))
|
|
49
|
+
}
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
const bindState = reactive<SsoCompletionBindBody>({
|
|
53
|
+
username: profile.value?.email || profile.value?.suggestedUserName || '',
|
|
54
|
+
password: '',
|
|
55
|
+
useSsoNickname: true,
|
|
56
|
+
})
|
|
57
|
+
const createState = reactive<SsoCompletionCreateBody>({
|
|
58
|
+
userName: profile.value?.suggestedUserName || '',
|
|
59
|
+
nickName: profile.value?.nickName || '',
|
|
60
|
+
email: profile.value?.email || '',
|
|
61
|
+
passwd: '',
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
const bindSchema = z.object({
|
|
65
|
+
username: z.string().trim().min(1, '请输入用户名或邮箱'),
|
|
66
|
+
password: z.string().min(1, '请输入密码'),
|
|
67
|
+
useSsoNickname: z.boolean().optional(),
|
|
68
|
+
})
|
|
69
|
+
const createSchema = z.object({
|
|
70
|
+
userName: z.string().trim().min(1, '请输入用户名'),
|
|
71
|
+
nickName: z.string().trim().min(1, '请输入昵称'),
|
|
72
|
+
email: z.string().trim().refine(value => !value || z.email().safeParse(value).success, '请输入有效的邮箱地址'),
|
|
73
|
+
passwd: z.string().min(1, '请输入密码'),
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
type BindSchema = z.output<typeof bindSchema>
|
|
77
|
+
type CreateSchema = z.output<typeof createSchema>
|
|
78
|
+
|
|
79
|
+
const pageTitle = computed(() => `完成 ${profile.value?.providerTitle || 'SSO'} 登录`)
|
|
80
|
+
const suggestedEmail = computed(() => profile.value?.email || '未提供')
|
|
81
|
+
const terminalError = computed(() => profileError.value?.message || (completionExpired.value ? 'SSO 登录流程无效或已过期' : ''))
|
|
82
|
+
|
|
83
|
+
function selectStep(nextStep: 'bind' | 'create') {
|
|
84
|
+
submitError.value = undefined
|
|
85
|
+
step.value = nextStep
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function goBack() {
|
|
89
|
+
submitError.value = undefined
|
|
90
|
+
step.value = 'choice'
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function bindAccount(payload: FormSubmitEvent<BindSchema>) {
|
|
94
|
+
await submitCompletion('/api/oauth/sso/completion/bind', payload.data)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function createAccount(payload: FormSubmitEvent<CreateSchema>) {
|
|
98
|
+
await submitCompletion('/api/oauth/sso/completion/create', {
|
|
99
|
+
...payload.data,
|
|
100
|
+
email: payload.data.email || undefined,
|
|
101
|
+
})
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function submitCompletion(url: string, body: SsoCompletionBindBody | SsoCompletionCreateBody) {
|
|
105
|
+
if (loading.value) {
|
|
106
|
+
return
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
loading.value = true
|
|
110
|
+
submitError.value = undefined
|
|
111
|
+
try {
|
|
112
|
+
const res = await $fetch<ResultDto<PublicSimpleUser>>(`${url}${completionQuery}`, {
|
|
113
|
+
method: 'POST',
|
|
114
|
+
body,
|
|
115
|
+
})
|
|
116
|
+
if (!res.success || !res.data) {
|
|
117
|
+
throw new Error(res.message || 'SSO 登录失败')
|
|
118
|
+
}
|
|
119
|
+
await finishLogin()
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
if (getErrorStatus(error) === 410) {
|
|
123
|
+
completionExpired.value = true
|
|
124
|
+
}
|
|
125
|
+
submitError.value = getErrorMessage(error, 'SSO 登录失败')
|
|
126
|
+
}
|
|
127
|
+
finally {
|
|
128
|
+
loading.value = false
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function finishLogin() {
|
|
133
|
+
if (window.opener && !window.opener.closed) {
|
|
134
|
+
window.opener.postMessage({ success: true }, window.location.origin)
|
|
135
|
+
window.close()
|
|
136
|
+
return
|
|
137
|
+
}
|
|
138
|
+
await navigateTo('/')
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function returnToLogin() {
|
|
142
|
+
const message = terminalError.value || submitError.value || 'SSO 登录未完成'
|
|
143
|
+
if (window.opener && !window.opener.closed) {
|
|
144
|
+
window.opener.postMessage({ success: false, message }, window.location.origin)
|
|
145
|
+
window.close()
|
|
146
|
+
return
|
|
147
|
+
}
|
|
148
|
+
await navigateTo('/login')
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function getErrorStatus(error: unknown) {
|
|
152
|
+
const normalized = error as {
|
|
153
|
+
status?: number
|
|
154
|
+
statusCode?: number
|
|
155
|
+
response?: { status?: number }
|
|
156
|
+
}
|
|
157
|
+
return normalized.statusCode || normalized.status || normalized.response?.status
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function getErrorMessage(error: unknown, fallback: string) {
|
|
161
|
+
const normalized = error as {
|
|
162
|
+
data?: { message?: string }
|
|
163
|
+
message?: string
|
|
164
|
+
}
|
|
165
|
+
return normalized.data?.message || normalized.message || fallback
|
|
166
|
+
}
|
|
167
|
+
</script>
|
|
168
|
+
|
|
169
|
+
<template>
|
|
170
|
+
<div class="min-h-screen flex items-center justify-center p-4">
|
|
171
|
+
<UPageCard class="w-full max-w-lg">
|
|
172
|
+
<div class="flex flex-col gap-5">
|
|
173
|
+
<div class="flex flex-col items-center text-center gap-2">
|
|
174
|
+
<UIcon name="i-lucide:shield-check" class="size-9 text-primary" />
|
|
175
|
+
<h1 class="text-xl text-pretty font-semibold text-highlighted">
|
|
176
|
+
{{ pageTitle }}
|
|
177
|
+
</h1>
|
|
178
|
+
<p class="text-sm text-muted">
|
|
179
|
+
选择绑定已有账户,或创建一个新账户继续登录。
|
|
180
|
+
</p>
|
|
181
|
+
</div>
|
|
182
|
+
|
|
183
|
+
<template v-if="profile && !completionExpired">
|
|
184
|
+
<div class="rounded-lg border border-default bg-muted/30 p-4">
|
|
185
|
+
<div class="text-sm font-medium text-highlighted">
|
|
186
|
+
{{ profile.providerTitle }} 账户
|
|
187
|
+
</div>
|
|
188
|
+
<div class="mt-2 text-base text-highlighted break-words">
|
|
189
|
+
{{ profile.nickName }}
|
|
190
|
+
</div>
|
|
191
|
+
<div class="mt-1 text-sm text-muted break-all">
|
|
192
|
+
建议邮箱:{{ suggestedEmail }}
|
|
193
|
+
</div>
|
|
194
|
+
</div>
|
|
195
|
+
|
|
196
|
+
<template v-if="step === 'choice'">
|
|
197
|
+
<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
|
198
|
+
<UButton
|
|
199
|
+
block
|
|
200
|
+
color="neutral"
|
|
201
|
+
variant="outline"
|
|
202
|
+
icon="i-lucide:log-in"
|
|
203
|
+
@click="selectStep('bind')"
|
|
204
|
+
>
|
|
205
|
+
绑定已有账户
|
|
206
|
+
</UButton>
|
|
207
|
+
<UButton
|
|
208
|
+
block
|
|
209
|
+
icon="i-lucide:user-plus"
|
|
210
|
+
@click="selectStep('create')"
|
|
211
|
+
>
|
|
212
|
+
创建新账户
|
|
213
|
+
</UButton>
|
|
214
|
+
</div>
|
|
215
|
+
</template>
|
|
216
|
+
|
|
217
|
+
<UForm
|
|
218
|
+
v-else-if="step === 'bind'"
|
|
219
|
+
:schema="bindSchema"
|
|
220
|
+
:state="bindState"
|
|
221
|
+
class="flex flex-col gap-4"
|
|
222
|
+
@submit="bindAccount"
|
|
223
|
+
>
|
|
224
|
+
<p class="text-sm text-muted">
|
|
225
|
+
登录已有账户,并将本次 {{ profile.providerTitle }} 登录与其绑定。
|
|
226
|
+
</p>
|
|
227
|
+
<UFormField label="用户名或邮箱" name="username" required>
|
|
228
|
+
<UInput
|
|
229
|
+
v-model="bindState.username"
|
|
230
|
+
class="w-full"
|
|
231
|
+
autocomplete="username"
|
|
232
|
+
placeholder="请输入用户名或邮箱"
|
|
233
|
+
/>
|
|
234
|
+
</UFormField>
|
|
235
|
+
<UFormField label="密码" name="password" required>
|
|
236
|
+
<UInput
|
|
237
|
+
v-model="bindState.password"
|
|
238
|
+
class="w-full"
|
|
239
|
+
type="password"
|
|
240
|
+
autocomplete="current-password"
|
|
241
|
+
placeholder="请输入密码"
|
|
242
|
+
/>
|
|
243
|
+
</UFormField>
|
|
244
|
+
<UCheckbox
|
|
245
|
+
v-model="bindState.useSsoNickname"
|
|
246
|
+
:label="`使用 ${profile.providerTitle} 昵称:${profile.nickName}`"
|
|
247
|
+
/>
|
|
248
|
+
<UAlert v-if="submitError" color="error" icon="i-lucide:info" :title="submitError" />
|
|
249
|
+
<div class="grid grid-cols-2 gap-3">
|
|
250
|
+
<UButton block color="neutral" variant="outline" type="button" :disabled="loading" @click="goBack">
|
|
251
|
+
返回
|
|
252
|
+
</UButton>
|
|
253
|
+
<UButton block type="submit" :loading="loading">
|
|
254
|
+
登录并绑定
|
|
255
|
+
</UButton>
|
|
256
|
+
</div>
|
|
257
|
+
</UForm>
|
|
258
|
+
|
|
259
|
+
<UForm
|
|
260
|
+
v-else
|
|
261
|
+
:schema="createSchema"
|
|
262
|
+
:state="createState"
|
|
263
|
+
class="flex flex-col gap-4"
|
|
264
|
+
@submit="createAccount"
|
|
265
|
+
>
|
|
266
|
+
<p class="text-sm text-muted">
|
|
267
|
+
创建新账户后会自动绑定 {{ profile.providerTitle }} 并完成登录。
|
|
268
|
+
</p>
|
|
269
|
+
<UFormField label="用户名" name="userName" required>
|
|
270
|
+
<UInput v-model="createState.userName" class="w-full" autocomplete="username" placeholder="请输入用户名" />
|
|
271
|
+
</UFormField>
|
|
272
|
+
<UFormField label="昵称" name="nickName" required>
|
|
273
|
+
<UInput v-model="createState.nickName" class="w-full" autocomplete="nickname" placeholder="请输入昵称" />
|
|
274
|
+
</UFormField>
|
|
275
|
+
<UFormField label="邮箱" name="email">
|
|
276
|
+
<UInput v-model="createState.email" class="w-full" type="email" autocomplete="email" placeholder="请输入邮箱(可选)" />
|
|
277
|
+
</UFormField>
|
|
278
|
+
<UFormField label="密码" name="passwd" required>
|
|
279
|
+
<UInput v-model="createState.passwd" class="w-full" type="password" autocomplete="new-password" placeholder="请输入密码" />
|
|
280
|
+
</UFormField>
|
|
281
|
+
<UAlert v-if="submitError" color="error" icon="i-lucide:info" :title="submitError" />
|
|
282
|
+
<div class="grid grid-cols-2 gap-3">
|
|
283
|
+
<UButton block color="neutral" variant="outline" type="button" :disabled="loading" @click="goBack">
|
|
284
|
+
返回
|
|
285
|
+
</UButton>
|
|
286
|
+
<UButton block type="submit" :loading="loading">
|
|
287
|
+
创建并登录
|
|
288
|
+
</UButton>
|
|
289
|
+
</div>
|
|
290
|
+
</UForm>
|
|
291
|
+
</template>
|
|
292
|
+
|
|
293
|
+
<template v-else>
|
|
294
|
+
<UAlert
|
|
295
|
+
color="error"
|
|
296
|
+
icon="i-lucide:circle-alert"
|
|
297
|
+
title="无法继续 SSO 登录"
|
|
298
|
+
:description="terminalError || 'SSO 登录流程无效或已过期'"
|
|
299
|
+
/>
|
|
300
|
+
<UButton block color="neutral" variant="outline" @click="returnToLogin">
|
|
301
|
+
返回登录页重试
|
|
302
|
+
</UButton>
|
|
303
|
+
</template>
|
|
304
|
+
|
|
305
|
+
</div>
|
|
306
|
+
</UPageCard>
|
|
307
|
+
</div>
|
|
308
|
+
</template>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zvonimirsun/iszy-nuxt-auth-layer",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"private": false,
|
|
6
6
|
"description": "ISZY Nuxt 应用共享认证 layer。",
|
|
@@ -30,6 +30,8 @@
|
|
|
30
30
|
"mitt": "^3.0.1",
|
|
31
31
|
"ms": "^2.1.3",
|
|
32
32
|
"ofetch": "^1.5.1",
|
|
33
|
+
"unstorage": "^1.17.5",
|
|
34
|
+
"vue-router": "^5.1.0",
|
|
33
35
|
"zod": "^4.4.3"
|
|
34
36
|
},
|
|
35
37
|
"peerDependencies": {
|
|
@@ -19,6 +19,7 @@ function renderCallbackPage(title: string, origin: string, body: string, payload
|
|
|
19
19
|
|
|
20
20
|
export default defineEventHandler(async (event) => {
|
|
21
21
|
const { title } = usePublicConfig()
|
|
22
|
+
const { provider } = event.context.params as { provider: string }
|
|
22
23
|
const url = getRequestURL(event)
|
|
23
24
|
const query = getQuery(event)
|
|
24
25
|
const state = query.state as string
|
|
@@ -54,6 +55,12 @@ export default defineEventHandler(async (event) => {
|
|
|
54
55
|
})
|
|
55
56
|
}
|
|
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
|
+
|
|
57
64
|
const code = query.code as string
|
|
58
65
|
const error = query.error as string | undefined
|
|
59
66
|
let errorMessage = error || (!code ? '缺少 code 参数' : '')
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { ResultDto } from '@zvonimirsun/iszy-common'
|
|
2
|
+
import type {
|
|
3
|
+
AuthTokenData,
|
|
4
|
+
PublicSimpleUser,
|
|
5
|
+
SsoCompletionBindBody,
|
|
6
|
+
} from '##shared/types/auth'
|
|
7
|
+
|
|
8
|
+
export default defineEventHandler(async (event): Promise<ResultDto<PublicSimpleUser>> => {
|
|
9
|
+
const query = getQuery(event)
|
|
10
|
+
const flowId = typeof query.flow === 'string' ? query.flow : undefined
|
|
11
|
+
const completion = await requireSsoCompletion(event, flowId)
|
|
12
|
+
const body = await readBody<SsoCompletionBindBody>(event)
|
|
13
|
+
const username = body?.username?.trim()
|
|
14
|
+
|
|
15
|
+
if (!username || !body?.password) {
|
|
16
|
+
throw createError({
|
|
17
|
+
statusCode: 400,
|
|
18
|
+
message: '用户名或邮箱和密码不能为空',
|
|
19
|
+
})
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
let res: ResultDto<AuthTokenData>
|
|
23
|
+
try {
|
|
24
|
+
res = await authFetch(event)<ResultDto<AuthTokenData>>('/oauth/sso/completion/bind', {
|
|
25
|
+
method: 'POST',
|
|
26
|
+
body: {
|
|
27
|
+
pendingToken: completion.pendingToken,
|
|
28
|
+
username,
|
|
29
|
+
password: body.password,
|
|
30
|
+
useSsoNickname: body.useSsoNickname,
|
|
31
|
+
},
|
|
32
|
+
})
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
const completionError = getSsoCompletionError(error, '登录并绑定失败')
|
|
36
|
+
if (completionError.status === 410) {
|
|
37
|
+
await removeSsoCompletion(event, flowId)
|
|
38
|
+
throw createError({
|
|
39
|
+
statusCode: 410,
|
|
40
|
+
message: completionError.message,
|
|
41
|
+
})
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
success: false,
|
|
45
|
+
message: completionError.message,
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (!res.success || !res.data) {
|
|
50
|
+
return {
|
|
51
|
+
success: false,
|
|
52
|
+
message: res.message || '登录并绑定失败',
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
try {
|
|
57
|
+
await setRedisSession(event, {
|
|
58
|
+
access_token: res.data.access_token,
|
|
59
|
+
refresh_token: res.data.refresh_token,
|
|
60
|
+
})
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
await removeSsoCompletion(event, flowId)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return {
|
|
67
|
+
success: true,
|
|
68
|
+
message: res.message || '登录并绑定成功',
|
|
69
|
+
data: toPublicSimpleUser(res.data.profile),
|
|
70
|
+
}
|
|
71
|
+
})
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { ResultDto } from '@zvonimirsun/iszy-common'
|
|
2
|
+
import type {
|
|
3
|
+
AuthTokenData,
|
|
4
|
+
PublicSimpleUser,
|
|
5
|
+
SsoCompletionCreateBody,
|
|
6
|
+
} from '##shared/types/auth'
|
|
7
|
+
|
|
8
|
+
export default defineEventHandler(async (event): Promise<ResultDto<PublicSimpleUser>> => {
|
|
9
|
+
const query = getQuery(event)
|
|
10
|
+
const flowId = typeof query.flow === 'string' ? query.flow : undefined
|
|
11
|
+
const completion = await requireSsoCompletion(event, flowId)
|
|
12
|
+
const body = await readBody<SsoCompletionCreateBody>(event)
|
|
13
|
+
const userName = body?.userName?.trim()
|
|
14
|
+
const nickName = body?.nickName?.trim()
|
|
15
|
+
const email = body?.email?.trim() || undefined
|
|
16
|
+
|
|
17
|
+
if (!userName || !nickName || !body?.passwd) {
|
|
18
|
+
throw createError({
|
|
19
|
+
statusCode: 400,
|
|
20
|
+
message: '用户名、昵称和密码不能为空',
|
|
21
|
+
})
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
let res: ResultDto<AuthTokenData>
|
|
25
|
+
try {
|
|
26
|
+
res = await authFetch(event)<ResultDto<AuthTokenData>>('/oauth/sso/completion/create', {
|
|
27
|
+
method: 'POST',
|
|
28
|
+
body: {
|
|
29
|
+
pendingToken: completion.pendingToken,
|
|
30
|
+
userName,
|
|
31
|
+
nickName,
|
|
32
|
+
email,
|
|
33
|
+
passwd: body.passwd,
|
|
34
|
+
},
|
|
35
|
+
})
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
const completionError = getSsoCompletionError(error, '创建账户失败')
|
|
39
|
+
if (completionError.status === 410) {
|
|
40
|
+
await removeSsoCompletion(event, flowId)
|
|
41
|
+
throw createError({
|
|
42
|
+
statusCode: 410,
|
|
43
|
+
message: completionError.message,
|
|
44
|
+
})
|
|
45
|
+
}
|
|
46
|
+
return {
|
|
47
|
+
success: false,
|
|
48
|
+
message: completionError.message,
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (!res.success || !res.data) {
|
|
53
|
+
return {
|
|
54
|
+
success: false,
|
|
55
|
+
message: res.message || '创建账户失败',
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
await setRedisSession(event, {
|
|
61
|
+
access_token: res.data.access_token,
|
|
62
|
+
refresh_token: res.data.refresh_token,
|
|
63
|
+
})
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
await removeSsoCompletion(event, flowId)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return {
|
|
70
|
+
success: true,
|
|
71
|
+
message: res.message || '账户创建成功',
|
|
72
|
+
data: toPublicSimpleUser(res.data.profile),
|
|
73
|
+
}
|
|
74
|
+
})
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ResultDto } from '@zvonimirsun/iszy-common'
|
|
2
|
+
|
|
3
|
+
interface SsoCompletionStartBody {
|
|
4
|
+
pendingToken?: string
|
|
5
|
+
pending_token?: string
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
interface SsoCompletionStartResult {
|
|
9
|
+
flow: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export default defineEventHandler(async (event): Promise<ResultDto<SsoCompletionStartResult>> => {
|
|
13
|
+
const body = await readBody<SsoCompletionStartBody>(event)
|
|
14
|
+
const pendingToken = body?.pendingToken || body?.pending_token
|
|
15
|
+
|
|
16
|
+
if (!pendingToken) {
|
|
17
|
+
throw createError({
|
|
18
|
+
statusCode: 400,
|
|
19
|
+
message: '缺少 SSO 待绑定凭证',
|
|
20
|
+
})
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const flow = await createSsoCompletion(event, pendingToken)
|
|
24
|
+
return {
|
|
25
|
+
success: true,
|
|
26
|
+
message: 'SSO 登录流程已创建',
|
|
27
|
+
data: {
|
|
28
|
+
flow,
|
|
29
|
+
},
|
|
30
|
+
}
|
|
31
|
+
})
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ResultDto } from '@zvonimirsun/iszy-common'
|
|
2
|
+
import type { SsoCompletionProfile } from '##shared/types/auth'
|
|
3
|
+
|
|
4
|
+
export default defineEventHandler(async (event): Promise<ResultDto<SsoCompletionProfile>> => {
|
|
5
|
+
const query = getQuery(event)
|
|
6
|
+
const flowId = typeof query.flow === 'string' ? query.flow : undefined
|
|
7
|
+
const completion = await requireSsoCompletion(event, flowId)
|
|
8
|
+
|
|
9
|
+
try {
|
|
10
|
+
return await authFetch(event)<ResultDto<SsoCompletionProfile>>('/oauth/sso/completion', {
|
|
11
|
+
method: 'POST',
|
|
12
|
+
body: {
|
|
13
|
+
pendingToken: completion.pendingToken,
|
|
14
|
+
},
|
|
15
|
+
})
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
const completionError = getSsoCompletionError(error, '获取 SSO 账户信息失败')
|
|
19
|
+
if (completionError.status === 410) {
|
|
20
|
+
await removeSsoCompletion(event, flowId)
|
|
21
|
+
throw createError({
|
|
22
|
+
statusCode: 410,
|
|
23
|
+
message: completionError.message,
|
|
24
|
+
})
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
success: false,
|
|
28
|
+
message: completionError.message,
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
})
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { FetchError } from 'ofetch'
|
|
2
|
+
|
|
3
|
+
interface ErrorData {
|
|
4
|
+
message?: string
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function getSsoCompletionError(error: unknown, fallback: string) {
|
|
8
|
+
const fetchError = error as FetchError<ErrorData>
|
|
9
|
+
return {
|
|
10
|
+
message: fetchError.data?.message || (error instanceof Error ? error.message : fallback),
|
|
11
|
+
status: fetchError.response?.status,
|
|
12
|
+
}
|
|
13
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { H3Event } from 'h3'
|
|
2
|
+
import type { SsoCompletionState } from '##shared/types/auth'
|
|
3
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto'
|
|
4
|
+
import ms from 'ms'
|
|
5
|
+
|
|
6
|
+
const SSO_COMPLETION_COOKIE_PATH = '/'
|
|
7
|
+
const SSO_COMPLETION_TTL = ms('10m') / 1000
|
|
8
|
+
const SSO_COMPLETION_ID_PATTERN = /^[0-9a-f]{64}$/
|
|
9
|
+
|
|
10
|
+
function createCompletionId() {
|
|
11
|
+
return randomBytes(32).toString('hex')
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function getCompletionCookieName(id: string) {
|
|
15
|
+
const { session } = useRuntimeConfig()
|
|
16
|
+
return `${session.cookieName}_SSO_COMPLETION_${id}`
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function getCompletionKey(id: string) {
|
|
20
|
+
return `oauth:sso:completion-flow:${id}`
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function clearCompletionCookie(event: H3Event, id: string) {
|
|
24
|
+
deleteCookie(event, getCompletionCookieName(id), {
|
|
25
|
+
path: SSO_COMPLETION_COOKIE_PATH,
|
|
26
|
+
})
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function createSsoCompletion(event: H3Event, pendingToken: string) {
|
|
30
|
+
const id = createCompletionId()
|
|
31
|
+
const browserSecret = createCompletionId()
|
|
32
|
+
const storage = useStorage<SsoCompletionState>('redis')
|
|
33
|
+
|
|
34
|
+
await storage.setItem(getCompletionKey(id), { pendingToken, browserSecret }, {
|
|
35
|
+
ttl: SSO_COMPLETION_TTL,
|
|
36
|
+
})
|
|
37
|
+
setCookie(event, getCompletionCookieName(id), browserSecret, {
|
|
38
|
+
httpOnly: true,
|
|
39
|
+
maxAge: SSO_COMPLETION_TTL,
|
|
40
|
+
path: SSO_COMPLETION_COOKIE_PATH,
|
|
41
|
+
sameSite: 'lax',
|
|
42
|
+
secure: true,
|
|
43
|
+
})
|
|
44
|
+
return id
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function requireSsoCompletion(event: H3Event, id?: string) {
|
|
48
|
+
if (id && SSO_COMPLETION_ID_PATTERN.test(id)) {
|
|
49
|
+
const browserSecret = getCookie(event, getCompletionCookieName(id))
|
|
50
|
+
const storage = useStorage<SsoCompletionState>('redis')
|
|
51
|
+
const completion = await storage.getItem(getCompletionKey(id))
|
|
52
|
+
if (completion && browserSecret && secretsMatch(browserSecret, completion.browserSecret)) {
|
|
53
|
+
return completion
|
|
54
|
+
}
|
|
55
|
+
clearCompletionCookie(event, id)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
throw createError({
|
|
59
|
+
statusCode: 410,
|
|
60
|
+
message: 'SSO 登录流程无效或已过期',
|
|
61
|
+
})
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function removeSsoCompletion(event: H3Event, id?: string) {
|
|
65
|
+
if (id && SSO_COMPLETION_ID_PATTERN.test(id)) {
|
|
66
|
+
const storage = useStorage<SsoCompletionState>('redis')
|
|
67
|
+
await storage.removeItem(getCompletionKey(id))
|
|
68
|
+
clearCompletionCookie(event, id)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function secretsMatch(left: string, right: string) {
|
|
73
|
+
if (!SSO_COMPLETION_ID_PATTERN.test(left) || !SSO_COMPLETION_ID_PATTERN.test(right)) {
|
|
74
|
+
return false
|
|
75
|
+
}
|
|
76
|
+
return timingSafeEqual(Buffer.from(left, 'hex'), Buffer.from(right, 'hex'))
|
|
77
|
+
}
|
package/shared/types/auth.ts
CHANGED
|
@@ -18,6 +18,38 @@ export interface OAuthStateData {
|
|
|
18
18
|
isBind?: boolean
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
export interface SsoCompletionState {
|
|
22
|
+
pendingToken: string
|
|
23
|
+
browserSecret: string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface SsoCompletionProfile {
|
|
27
|
+
provider: 'sso'
|
|
28
|
+
providerTitle: string
|
|
29
|
+
suggestedUserName: string
|
|
30
|
+
nickName: string
|
|
31
|
+
email?: string
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface SsoCompletionBindBody {
|
|
35
|
+
username: string
|
|
36
|
+
password: string
|
|
37
|
+
useSsoNickname?: boolean
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface SsoCompletionCreateBody {
|
|
41
|
+
userName: string
|
|
42
|
+
nickName: string
|
|
43
|
+
email?: string
|
|
44
|
+
passwd: string
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface AuthTokenData {
|
|
48
|
+
access_token: string
|
|
49
|
+
refresh_token: string
|
|
50
|
+
profile: PublicUser
|
|
51
|
+
}
|
|
52
|
+
|
|
21
53
|
export interface AuthFeatures {
|
|
22
54
|
authMode: 'local' | 'sso'
|
|
23
55
|
publicRegister: boolean
|