miaopanel
1<script setup lang="ts">
2import { computed, onBeforeUnmount, ref, watch } from 'vue'
3import { api, ApiError, setCsrf } from '../api'
4import type { SessionPayload } from '../types'
5import QrCode from '../components/QrCode.vue'
6
7defineProps<{ notice?: string }>()
8const emit = defineEmits<{ (e: 'success', s: SessionPayload): void }>()
9
10type Mode = 'password' | 'qr'
11
12interface QrCreate {
13 ticket: string
14 secret: string
15 payload: string
16 expires_at: number
17 poll_interval: number
18 entry: string
19 scheme: string
20}
21
22interface QrStatus {
23 status: string
24 expires_at: number
25 username?: string
26 approved_at?: number
27}
28
29const mode = ref<Mode>('password')
30const showPassword = ref(false)
31
32const username = ref('admin')
33const password = ref('')
34const code = ref('')
35const recovery = ref('')
36const ticket = ref('')
37const useRecovery = ref(false)
38const error = ref('')
39const busy = ref(false)
40
41const qr = ref<QrCreate | null>(null)
42const qrState = ref('idle')
43const qrError = ref('')
44const qrBusy = ref(false)
45const remaining = ref(0)
46let pollTimer: number | undefined
47let tickTimer: number | undefined
48// Guards against a second exchange while the first POST is still in flight:
49// the ticket is single use, so a duplicate would only produce a 409.
50let exchanging = false
51
52const statusText = computed(() => {
53 switch (qrState.value) {
54 case 'idle':
55 return '正在生成二维码…'
56 case 'pending':
57 return '等待手机扫码'
58 case 'scanned':
59 return '手机已扫码,请在手机上确认登录'
60 case 'confirmed':
61 return '已确认,正在进入面板…'
62 case 'denied':
63 return '本次登录已被拒绝'
64 case 'expired':
65 return '二维码已过期,请刷新'
66 case 'invalid':
67 case 'consumed':
68 return '二维码已失效,请刷新'
69 case 'error':
70 return '二维码不可用'
71 default:
72 return ''
73 }
74})
75
76// The QR panel is unusable once it is no longer pending: dim it and let the
77// operator ask for a fresh code instead of silently polling a dead ticket.
78const qrDead = computed(() =>
79 ['denied', 'expired', 'invalid', 'consumed', 'error'].includes(qrState.value),
80)
81
82const veilText = computed(() => {
83 if (qrState.value === 'denied') return '已在手机上拒绝'
84 if (qrState.value === 'error') return '二维码不可用'
85 return '二维码已失效'
86})
87
88function finish(s: SessionPayload) {
89 setCsrf(s.csrf)
90 emit('success', s)
91}
92
93async function submit() {
94 error.value = ''
95 busy.value = true
96 try {
97 if (!ticket.value) {
98 const res = await api.post<SessionPayload | { need_otp: boolean; ticket: string }>(
99 'api/v1/auth/login',
100 { username: username.value.trim(), password: password.value },
101 )
102 if ('need_otp' in res) {
103 ticket.value = res.ticket
104 return
105 }
106 finish(res)
107 return
108 }
109 const res = await api.post<SessionPayload>('api/v1/auth/otp', {
110 ticket: ticket.value,
111 code: useRecovery.value ? '' : code.value.replace(/\s/g, ''),
112 recovery: useRecovery.value ? recovery.value.trim() : '',
113 })
114 finish(res)
115 } catch (e) {
116 const err = e as ApiError
117 error.value = err.message
118 if (err.status === 401 && ticket.value) {
119 ticket.value = ''
120 code.value = ''
121 }
122 } finally {
123 busy.value = false
124 }
125}
126
127function stopTimers() {
128 if (pollTimer !== undefined) {
129 window.clearInterval(pollTimer)
130 pollTimer = undefined
131 }
132 if (tickTimer !== undefined) {
133 window.clearInterval(tickTimer)
134 tickTimer = undefined
135 }
136}
137
138function secondsLeft(expiresAt: number) {
139 return Math.max(0, Math.round(expiresAt - Date.now() / 1000))
140}
141
142async function startQR() {
143 stopTimers()
144 qr.value = null
145 qrError.value = ''
146 qrState.value = 'idle'
147 remaining.value = 0
148 exchanging = false
149 qrBusy.value = true
150 try {
151 const res = await api.post<QrCreate>('api/v1/auth/qr/create')
152 qr.value = res
153 qrState.value = 'pending'
154 remaining.value = secondsLeft(res.expires_at)
155 tickTimer = window.setInterval(() => {
156 remaining.value = secondsLeft(res.expires_at)
157 if (remaining.value <= 0 && (qrState.value === 'pending' || qrState.value === 'scanned')) {
158 qrState.value = 'expired'
159 stopTimers()
160 // A dead QR is useless; fetch a fresh one instead of waiting for a click.
161 window.setTimeout(() => {
162 if (mode.value === 'qr' && qrState.value === 'expired') startQR()
163 }, 1200)
164 }
165 }, 1000)
166 pollTimer = window.setInterval(pollQR, Math.max(800, res.poll_interval || 1500))
167 } catch (e) {
168 qrError.value = (e as ApiError).message
169 qrState.value = 'error'
170 } finally {
171 qrBusy.value = false
172 }
173}
174
175async function pollQR() {
176 const cur = qr.value
177 if (!cur) return
178 if (qrState.value !== 'pending' && qrState.value !== 'scanned') return
179 try {
180 const st = await api.get<QrStatus>(
181 'api/v1/auth/qr/status?ticket=' + encodeURIComponent(cur.ticket),
182 )
183 // A refresh may have replaced the ticket while this request was in flight.
184 if (!qr.value || qr.value.ticket !== cur.ticket) return
185 if (st.expires_at) remaining.value = secondsLeft(st.expires_at)
186 qrState.value = st.status
187 if (st.status === 'confirmed') {
188 stopTimers()
189 await exchange()
190 } else if (st.status !== 'pending' && st.status !== 'scanned') {
191 stopTimers()
192 }
193 } catch {
194 // A single failed poll (sleeping laptop, flaky wifi) must not kill the
195 // flow: the countdown still ends it.
196 }
197}
198
199async function exchange() {
200 const cur = qr.value
201 if (!cur || exchanging) return
202 exchanging = true
203 qrBusy.value = true
204 try {
205 const s = await api.post<SessionPayload>('api/v1/auth/qr/exchange', {
206 ticket: cur.ticket,
207 secret: cur.secret,
208 })
209 finish(s)
210 } catch (e) {
211 qrError.value = (e as ApiError).message
212 qrState.value = 'error'
213 } finally {
214 exchanging = false
215 qrBusy.value = false
216 }
217}
218
219// Submitting as soon as the sixth digit is typed saves a click and avoids the
220// "nothing happened" moment when the user expects automatic continuation.
221watch(code, (value) => {
222 if (ticket.value && !busy.value && value.replace(/\s/g, '').length === 6) void submit()
223})
224
225watch(mode, (next) => {
226 if (next === 'qr') {
227 startQR()
228 } else {
229 stopTimers()
230 qr.value = null
231 qrState.value = 'idle'
232 qrError.value = ''
233 }
234})
235
236onBeforeUnmount(stopTimers)
237</script>
238
239<template>
240 <div class="login-page">
241 <div class="login-card">
242 <div class="brand">
243 <div class="brand-mark">喵</div>
244 <div class="brand-text">
245 <b>MiaoPanel</b>
246 <span>服务器运维面板</span>
247 </div>
248 </div>
249
250 <div v-if="notice" class="alert" style="margin-bottom: 14px">{{ notice }}</div>
251
252 <div v-if="!ticket" class="login-tabs">
253 <button
254 class="login-tab"
255 :class="{ active: mode === 'password' }"
256 type="button"
257 @click="mode = 'password'"
258 >
259 账号密码
260 </button>
261 <button class="login-tab" :class="{ active: mode === 'qr' }" type="button" @click="mode = 'qr'">
262 扫码登录
263 </button>
264 </div>
265
266 <!-- 账号密码 -->
267 <template v-if="!ticket && mode === 'password'">
268 <h2>登录</h2>
269 <p class="hint">请输入面板账号密码,连续失败 5 次将锁定 10 分钟。</p>
270 <form @submit.prevent="submit">
271 <label class="field">
272 用户名
273 <input v-model="username" class="input" autocomplete="username" autofocus />
274 </label>
275 <label class="field">
276 密码
277 <div class="input-group">
278 <input
279 v-model="password"
280 class="input"
281 :type="showPassword ? 'text' : 'password'"
282 autocomplete="current-password"
283 />
284 <button
285 class="btn btn-ghost btn-sm"
286 type="button"
287 :aria-label="showPassword ? '隐藏密码' : '显示密码'"
288 @click="showPassword = !showPassword"
289 >
290 {{ showPassword ? '隐藏' : '显示' }}
291 </button>
292 </div>
293 </label>
294 <div v-if="error" class="alert">{{ error }}</div>
295 <button class="btn btn-primary" :disabled="busy" type="submit">
296 <span v-if="busy" class="spin"></span>
297 登录
298 </button>
299 </form>
300 <p class="hint" style="margin-top: 12px">
301 忘记密码?在服务器上执行 <code>miaopanel passwd</code> 重置。连续失败 5 次会锁定 10 分钟。
302 </p>
303 </template>
304
305 <!-- 两步验证(账号密码流程的第二段) -->
306 <template v-if="ticket">
307 <h2>两步验证</h2>
308 <p class="hint">请输入身份验证器中的 6 位动态口令。</p>
309 <form @submit.prevent="submit">
310 <label v-if="!useRecovery" class="field">
311 动态口令
312 <input v-model="code" class="input mono" inputmode="numeric" maxlength="6" autofocus />
313 </label>
314 <label v-else class="field">
315 恢复码
316 <input v-model="recovery" class="input mono" placeholder="XXXXX-XXXXX" />
317 </label>
318 <div v-if="error" class="alert">{{ error }}</div>
319 <button class="btn btn-primary" :disabled="busy" type="submit">
320 <span v-if="busy" class="spin"></span>
321 验证
322 </button>
323 <button class="btn btn-ghost btn-sm" type="button" @click="useRecovery = !useRecovery">
324 {{ useRecovery ? '使用动态口令' : '使用恢复码' }}
325 </button>
326 </form>
327 </template>
328
329 <!-- 扫码登录 -->
330 <template v-if="!ticket && mode === 'qr'">
331 <h2>扫码登录</h2>
332 <p class="hint">用已登录的「喵喵面板」手机 App 扫描二维码,并在手机上确认。</p>
333
334 <div class="qr-stage">
335 <QrCode v-if="qr" :text="qr.payload" :size="196" label="登录二维码" />
336 <div v-else class="qr-placeholder">
337 <span class="spin"></span>
338 </div>
339 <div v-if="qrDead" class="qr-veil">
340 <span class="qr-veil-text">{{ veilText }}</span>
341 <button
342 class="btn btn-primary btn-sm"
343 type="button"
344 :disabled="qrBusy"
345 @click="startQR"
346 >
347 刷新二维码
348 </button>
349 </div>
350 </div>
351
352 <div class="qr-meta">
353 <span class="qr-state" :class="{ active: qrState === 'scanned' }">{{ statusText }}</span>
354 <span v-if="qr && (qrState === 'pending' || qrState === 'scanned')" class="qr-timer mono">
355 {{ remaining }}s
356 </span>
357 </div>
358
359 <div v-if="qrError" class="alert">{{ qrError }}</div>
360
361 <p class="hint qr-help">
362 App 入口:首页右上角「扫」,或「设置 → 扫码登录」。二维码 2 分钟内有效,且只能使用一次。
363 </p>
364 <button class="btn btn-ghost btn-sm qr-switch" type="button" @click="mode = 'password'">
365 改用账号密码登录
366 </button>
367 </template>
368 </div>
369 </div>
370</template>