mirror of
https://github.com/vastsa/FileCodeBoxFronted.git
synced 2026-11-24 21:58:01 +08:00
feat: show admin session status and settings (#484)
This commit is contained in:
1 parent
343635d832
commit
1cec0a46db
17 files changed
+210
-60
No files matched your search
+26
-9
@@ -1,14 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { RouterLink, RouterView } from 'vue-router'
|
||||
import { ShieldCheckIcon } from 'lucide-vue-next'
|
||||
import { LogInIcon, ShieldCheckIcon } from 'lucide-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import ThemeToggle from './components/common/ThemeToggle.vue'
|
||||
import LanguageSwitcher from './components/common/LanguageSwitcher.vue'
|
||||
import AlertComponent from '@/components/common/AlertComponent.vue'
|
||||
import { useAppShell } from '@/composables'
|
||||
import { useAdminSession, useAppShell } from '@/composables'
|
||||
import { ROUTES } from '@/constants'
|
||||
import { useConfigStore } from '@/stores/configStore'
|
||||
import { useAdminStore } from '@/stores/adminStore'
|
||||
|
||||
const {
|
||||
isDarkMode,
|
||||
@@ -21,7 +23,17 @@ const {
|
||||
|
||||
const configStore = useConfigStore()
|
||||
const { config } = storeToRefs(configStore)
|
||||
const adminStore = useAdminStore()
|
||||
const { t } = useI18n()
|
||||
const { verifySession } = useAdminSession()
|
||||
const showAdminAddress = computed(() => config.value.showAdminAddr === 1)
|
||||
const adminEntryLabel = computed(() =>
|
||||
t(adminStore.isAuthenticated ? 'admin.session.loggedIn' : 'admin.session.loggedOut')
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
if (adminStore.hasToken) void verifySession()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -35,14 +47,19 @@ const showAdminAddress = computed(() => config.value.showAdminAddr === 1)
|
||||
:to="ROUTES.ADMIN"
|
||||
class="rounded-full border p-2.5 shadow-sm backdrop-blur-xl transition-all duration-300 hover:scale-105 active:scale-95 sm:p-3"
|
||||
:class="
|
||||
isDarkMode
|
||||
? 'border-white/10 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700'
|
||||
: 'border-slate-200/50 bg-white/80 text-slate-500 hover:text-slate-700'
|
||||
adminStore.isAuthenticated
|
||||
? isDarkMode
|
||||
? 'border-emerald-400/30 bg-emerald-500/15 text-emerald-300 hover:bg-emerald-500/25'
|
||||
: 'border-emerald-200 bg-emerald-50 text-emerald-700 hover:bg-emerald-100'
|
||||
: isDarkMode
|
||||
? 'border-white/10 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700'
|
||||
: 'border-slate-200/50 bg-white/80 text-slate-500 hover:text-slate-700'
|
||||
"
|
||||
aria-label="进入管理员页面"
|
||||
title="进入管理员页面"
|
||||
:aria-label="adminEntryLabel"
|
||||
:title="adminEntryLabel"
|
||||
>
|
||||
<ShieldCheckIcon class="h-5 w-5" />
|
||||
<ShieldCheckIcon v-if="adminStore.isAuthenticated" class="h-5 w-5" />
|
||||
<LogInIcon v-else class="h-5 w-5" />
|
||||
</RouterLink>
|
||||
<LanguageSwitcher />
|
||||
<ThemeToggle v-model="isDarkMode" />
|
||||
|
||||
@@ -10,6 +10,9 @@
|
||||
<input
|
||||
type="number"
|
||||
:value="modelValue"
|
||||
:min="min"
|
||||
:max="max"
|
||||
step="1"
|
||||
class="w-24 rounded-xl border px-4 py-2.5 shadow-sm outline-none transition-all duration-200 ease-in-out focus:border-zinc-500 focus:ring-2 focus:ring-zinc-500"
|
||||
:class="[
|
||||
isDarkMode
|
||||
@@ -26,10 +29,12 @@
|
||||
<script setup lang="ts">
|
||||
import { inject } from 'vue'
|
||||
|
||||
defineProps<{
|
||||
const props = defineProps<{
|
||||
label: string
|
||||
modelValue: number
|
||||
suffix: string
|
||||
min?: number
|
||||
max?: number
|
||||
}>()
|
||||
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
@@ -41,13 +46,16 @@ const emit = defineEmits<{
|
||||
const handleInput = (event: Event) => {
|
||||
const input = event.target as HTMLInputElement
|
||||
if (!input.value) {
|
||||
emit('update:modelValue', 0)
|
||||
emit('update:modelValue', props.min ?? 0)
|
||||
return
|
||||
}
|
||||
|
||||
const nextValue = input.valueAsNumber
|
||||
if (!Number.isNaN(nextValue)) {
|
||||
emit('update:modelValue', nextValue)
|
||||
const integerValue = Math.round(nextValue)
|
||||
const lowerBound = props.min ?? Number.NEGATIVE_INFINITY
|
||||
const upperBound = props.max ?? Number.POSITIVE_INFINITY
|
||||
emit('update:modelValue', Math.min(upperBound, Math.max(lowerBound, integerValue)))
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -30,7 +30,7 @@ export function useAdminLogin() {
|
||||
isLoading.value = true
|
||||
try {
|
||||
const response = await AuthService.login(password.value)
|
||||
if (!response.detail?.token) {
|
||||
if (!response.detail?.token || !response.detail.expires_at) {
|
||||
alertStore.showAlert('登录失败:未获取到有效令牌', 'error')
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -13,10 +13,9 @@ export function useAdminSession() {
|
||||
adminStore.login(response.detail)
|
||||
return true
|
||||
}
|
||||
} catch {
|
||||
adminStore.logout()
|
||||
}
|
||||
} catch {}
|
||||
|
||||
adminStore.logout()
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ROUTES } from '@/constants'
|
||||
import { useTheme } from './useTheme'
|
||||
import { usePublicConfigBootstrap } from './usePublicConfigBootstrap'
|
||||
import { useRouteLoading } from './useRouteLoading'
|
||||
import { useAdminStore } from '@/stores/adminStore'
|
||||
|
||||
export function useAppShell() {
|
||||
const route = useRoute()
|
||||
@@ -12,6 +13,7 @@ export function useAppShell() {
|
||||
const { isDarkMode, toggleTheme, initTheme } = useTheme()
|
||||
const { isLoading, setupRouteLoading } = useRouteLoading(router)
|
||||
const { syncPublicConfig } = usePublicConfigBootstrap()
|
||||
const adminStore = useAdminStore()
|
||||
const showGlobalControls = computed(() => route.meta.showGlobalControls !== false)
|
||||
const routeTransitionName = computed(() => String(route.meta.routeTransition || 'fade'))
|
||||
const routeTransitionMode = computed(() => (route.meta.routeTransition ? undefined : 'out-in'))
|
||||
@@ -25,6 +27,7 @@ export function useAppShell() {
|
||||
let setupRedirecting = false
|
||||
|
||||
const handleUnauthorized = () => {
|
||||
adminStore.logout()
|
||||
if (router.currentRoute.value.path !== ROUTES.LOGIN) {
|
||||
void router.push({
|
||||
path: ROUTES.LOGIN,
|
||||
@@ -41,7 +44,11 @@ export function useAppShell() {
|
||||
? event.detail.setupPath
|
||||
: '/setup'
|
||||
|
||||
if (!setupPath || setupRedirecting || window.location.pathname.replace(/\/+$/, '') === setupPath) {
|
||||
if (
|
||||
!setupPath ||
|
||||
setupRedirecting ||
|
||||
window.location.pathname.replace(/\/+$/, '') === setupPath
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,9 @@ import {
|
||||
type SaveTimeUnit
|
||||
} from '@/utils/config-form'
|
||||
|
||||
type ConfigFlagKey = 'enableChunk' | 's3_proxy' | 'openUpload'
|
||||
type ConfigFlagKey = 'enableChunk' | 's3_proxy' | 'openUpload' | 'showAdminAddr'
|
||||
|
||||
const SECONDS_PER_DAY = 24 * 60 * 60
|
||||
|
||||
export function useSystemConfig() {
|
||||
const alertStore = useAlertStore()
|
||||
@@ -28,6 +30,7 @@ export function useSystemConfig() {
|
||||
const sizeUnit = ref<FileSizeUnit>('MB')
|
||||
const saveTime = ref(1)
|
||||
const saveTimeUnit = ref<SaveTimeUnit>('天')
|
||||
const adminSessionDays = ref(30)
|
||||
|
||||
const isLoading = computed(() => isRefreshing.value || isSaving.value)
|
||||
|
||||
@@ -37,6 +40,7 @@ export function useSystemConfig() {
|
||||
{ value: fileSize.value, unit: sizeUnit.value },
|
||||
{ value: saveTime.value, unit: saveTimeUnit.value }
|
||||
)
|
||||
payload.adminSessionExpire = Math.round(adminSessionDays.value * SECONDS_PER_DAY)
|
||||
|
||||
if (!payload.admin_token) {
|
||||
delete payload.admin_token
|
||||
@@ -168,6 +172,10 @@ export function useSystemConfig() {
|
||||
const saveTimeForm = secondsToSaveTimeForm(nextConfig.max_save_seconds)
|
||||
saveTime.value = saveTimeForm.value
|
||||
saveTimeUnit.value = saveTimeForm.unit
|
||||
adminSessionDays.value = Math.max(
|
||||
1,
|
||||
Math.round(nextConfig.adminSessionExpire / SECONDS_PER_DAY)
|
||||
)
|
||||
}
|
||||
|
||||
const refreshConfig = async () => {
|
||||
@@ -220,6 +228,7 @@ export function useSystemConfig() {
|
||||
sizeUnit,
|
||||
saveTime,
|
||||
saveTimeUnit,
|
||||
adminSessionDays,
|
||||
|
||||
// 计算属性
|
||||
maxFileSizeMB,
|
||||
|
||||
@@ -5,6 +5,7 @@ export const STORAGE_KEYS = {
|
||||
COLOR_MODE: 'colorMode',
|
||||
ADMIN_PASSWORD: 'adminPassword',
|
||||
TOKEN: 'token',
|
||||
TOKEN_EXPIRES_AT: 'tokenExpiresAt',
|
||||
CONFIG: 'config',
|
||||
NOTIFY: 'notify'
|
||||
} as const
|
||||
|
||||
@@ -54,6 +54,10 @@ export default {
|
||||
// Admin module
|
||||
admin: {
|
||||
logout: 'Logout',
|
||||
session: {
|
||||
loggedIn: 'Signed in, open admin console',
|
||||
loggedOut: 'Sign in to admin console'
|
||||
},
|
||||
dashboard: {
|
||||
title: 'Dashboard',
|
||||
totalFiles: 'Total Files',
|
||||
@@ -123,6 +127,9 @@ export default {
|
||||
websiteDescription: 'Site Description',
|
||||
siteName: 'Site Name',
|
||||
adminPassword: 'Admin Password',
|
||||
sessionDuration: 'Login Session Duration',
|
||||
sessionDurationHelp: 'Applies to new logins only. Allowed range: 1 to 365 days.',
|
||||
showAdminAddress: 'Show Admin Entry on Home Pages',
|
||||
passwordPlaceholder: 'Enter new password to change',
|
||||
passwordNote: 'Leave empty to keep current',
|
||||
keywords: 'SEO Keywords',
|
||||
@@ -171,11 +178,13 @@ export default {
|
||||
fileSizeLimit: 'Max File Size',
|
||||
allowedFileTypes: 'Allowed File Types',
|
||||
allowedFileTypesPlaceholder: '* or .rar, .zip, image/*',
|
||||
allowedFileTypesHelp: 'Separate multiple types with commas. * allows all; extensions and MIME wildcards are supported.',
|
||||
allowedFileTypesHelp:
|
||||
'Separate multiple types with commas. * allows all; extensions and MIME wildcards are supported.',
|
||||
codeGenerateType: 'Passcode Rule',
|
||||
codeGenerateNumber: 'Numeric Passcode',
|
||||
codeGenerateSecret: 'Secret Passcode',
|
||||
codeGenerateTypeHelp: 'Numeric keeps the existing 5-digit code. Secret uses a random alphanumeric code.',
|
||||
codeGenerateTypeHelp:
|
||||
'Numeric keeps the existing 5-digit code. Secret uses a random alphanumeric code.',
|
||||
expirationMethod: 'Expiration Options',
|
||||
expirationType: 'Expiration Options',
|
||||
expiration: {
|
||||
@@ -704,11 +713,13 @@ export default {
|
||||
fileSizeLimit: 'Max File Size',
|
||||
allowedFileTypes: 'Allowed File Types',
|
||||
allowedFileTypesPlaceholder: '* or .rar, .zip, image/*',
|
||||
allowedFileTypesHelp: 'Separate multiple types with commas. * allows all; extensions and MIME wildcards are supported.',
|
||||
allowedFileTypesHelp:
|
||||
'Separate multiple types with commas. * allows all; extensions and MIME wildcards are supported.',
|
||||
codeGenerateType: 'Passcode Rule',
|
||||
codeGenerateNumber: 'Numeric Passcode',
|
||||
codeGenerateSecret: 'Secret Passcode',
|
||||
codeGenerateTypeHelp: 'Numeric keeps the existing 5-digit code. Secret uses a random alphanumeric code.',
|
||||
codeGenerateTypeHelp:
|
||||
'Numeric keeps the existing 5-digit code. Secret uses a random alphanumeric code.',
|
||||
expirationMethod: 'Expiration Options',
|
||||
expirationType: 'Expiration Options',
|
||||
expiration: {
|
||||
@@ -781,7 +792,8 @@ export default {
|
||||
codeGenerateType: 'Passcode Rule',
|
||||
codeGenerateNumber: 'Numeric Passcode',
|
||||
codeGenerateSecret: 'Secret Passcode',
|
||||
codeGenerateTypeHelp: 'Numeric keeps the existing 5-digit code. Secret uses a random alphanumeric code.',
|
||||
codeGenerateTypeHelp:
|
||||
'Numeric keeps the existing 5-digit code. Secret uses a random alphanumeric code.',
|
||||
expirationMethod: 'Expiration Options',
|
||||
expirationMethods: {
|
||||
day: 'Days',
|
||||
|
||||
@@ -54,6 +54,10 @@ export default {
|
||||
// 管理员模块
|
||||
admin: {
|
||||
logout: '退出登录',
|
||||
session: {
|
||||
loggedIn: '已登录,进入管理后台',
|
||||
loggedOut: '登录管理后台'
|
||||
},
|
||||
dashboard: {
|
||||
title: '仪表盘',
|
||||
totalFiles: '总文件数',
|
||||
@@ -123,6 +127,9 @@ export default {
|
||||
websiteDescription: '网站描述',
|
||||
siteName: '网站名称',
|
||||
adminPassword: '管理员密码',
|
||||
sessionDuration: '登录会话时长',
|
||||
sessionDurationHelp: '仅影响新登录,允许设置 1 至 365 天。',
|
||||
showAdminAddress: '在主页显示管理入口',
|
||||
passwordPlaceholder: '如需修改请输入新密码',
|
||||
passwordNote: '不修改请留空',
|
||||
keywords: 'SEO 关键词',
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import { createRouter, createWebHashHistory } from 'vue-router'
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
import { ROUTE_NAMES, ROUTES } from '@/constants'
|
||||
import { readStoredToken } from '@/utils/auth-storage'
|
||||
import { hasValidStoredAdminSession } from '@/utils/auth-storage'
|
||||
|
||||
const publicPageMeta = {
|
||||
showGlobalControls: true,
|
||||
@@ -92,7 +92,7 @@ const router = createRouter({
|
||||
})
|
||||
|
||||
router.beforeEach((to) => {
|
||||
if (to.meta.requiresAuth && !readStoredToken()) {
|
||||
if (to.meta.requiresAuth && !hasValidStoredAdminSession()) {
|
||||
return {
|
||||
path: ROUTES.LOGIN,
|
||||
query: {
|
||||
|
||||
+8
-15
@@ -1,7 +1,7 @@
|
||||
import axios, { type AxiosError, type InternalAxiosRequestConfig } from 'axios'
|
||||
import { API_STATUS_CODES, TIME_CONSTANTS } from '@/constants'
|
||||
import type { ApiErrorPayload } from '@/types'
|
||||
import { clearStoredToken, readStoredToken } from '@/utils/auth-storage'
|
||||
import { clearStoredToken, hasValidStoredAdminSession, readStoredToken } from '@/utils/auth-storage'
|
||||
|
||||
export const AUTH_EVENTS = {
|
||||
UNAUTHORIZED: 'filecodebox:auth:unauthorized',
|
||||
@@ -27,9 +27,11 @@ const apiClient = axios.create(clientOptions)
|
||||
export const rawApiClient = axios.create(clientOptions)
|
||||
|
||||
const attachAuthToken = (config: InternalAxiosRequestConfig) => {
|
||||
const token = readStoredToken()
|
||||
if (token) {
|
||||
if (hasValidStoredAdminSession()) {
|
||||
const token = readStoredToken()
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
} else {
|
||||
clearStoredToken()
|
||||
}
|
||||
return config
|
||||
}
|
||||
@@ -58,20 +60,11 @@ const handleAuthError = (error: AxiosError<ApiErrorPayload>) => {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
apiClient.interceptors.request.use(
|
||||
attachAuthToken,
|
||||
(error) => Promise.reject(error)
|
||||
)
|
||||
apiClient.interceptors.request.use(attachAuthToken, (error) => Promise.reject(error))
|
||||
|
||||
rawApiClient.interceptors.request.use(
|
||||
attachAuthToken,
|
||||
(error) => Promise.reject(error)
|
||||
)
|
||||
rawApiClient.interceptors.request.use(attachAuthToken, (error) => Promise.reject(error))
|
||||
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => response.data,
|
||||
handleAuthError
|
||||
)
|
||||
apiClient.interceptors.response.use((response) => response.data, handleAuthError)
|
||||
|
||||
rawApiClient.interceptors.response.use((response) => response, handleAuthError)
|
||||
|
||||
|
||||
+58
-18
@@ -3,74 +3,114 @@ import { ref, computed } from 'vue'
|
||||
import type { AdminUser } from '@/types'
|
||||
import {
|
||||
clearStoredAuth,
|
||||
clearStoredToken,
|
||||
hasValidStoredAdminSession,
|
||||
readStoredAdminPassword,
|
||||
readStoredToken,
|
||||
readStoredTokenExpiresAt,
|
||||
writeStoredAdminPassword,
|
||||
writeStoredToken
|
||||
} from '@/utils/auth-storage'
|
||||
|
||||
export const useAdminStore = defineStore('admin', () => {
|
||||
const MAX_TIMER_DELAY = 2_147_483_647
|
||||
let expirationTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
// 状态
|
||||
const storedSessionIsValid = hasValidStoredAdminSession()
|
||||
if (!storedSessionIsValid) clearStoredToken()
|
||||
const adminPassword = ref(readStoredAdminPassword())
|
||||
const token = ref(readStoredToken())
|
||||
const isLoggedIn = ref(false)
|
||||
const token = ref(storedSessionIsValid ? readStoredToken() : '')
|
||||
const expiresAt = ref(storedSessionIsValid ? readStoredTokenExpiresAt() : null)
|
||||
const isLoggedIn = ref(!!token.value)
|
||||
const userInfo = ref<AdminUser | null>(null)
|
||||
|
||||
|
||||
// 计算属性
|
||||
const isAuthenticated = computed(() => {
|
||||
return isLoggedIn.value && !!token.value
|
||||
})
|
||||
const hasToken = computed(() => !!token.value)
|
||||
|
||||
|
||||
const clearExpirationTimer = () => {
|
||||
if (expirationTimer) clearTimeout(expirationTimer)
|
||||
expirationTimer = null
|
||||
}
|
||||
|
||||
const scheduleExpiration = (sessionExpiresAt: number | null) => {
|
||||
clearExpirationTimer()
|
||||
if (!sessionExpiresAt) return
|
||||
|
||||
const remaining = sessionExpiresAt * 1000 - Date.now()
|
||||
if (remaining <= 0) {
|
||||
logout()
|
||||
return
|
||||
}
|
||||
expirationTimer = setTimeout(
|
||||
() => scheduleExpiration(sessionExpiresAt),
|
||||
Math.min(remaining, MAX_TIMER_DELAY)
|
||||
)
|
||||
}
|
||||
|
||||
// 方法
|
||||
const updateAdminPassword = (pwd: string) => {
|
||||
adminPassword.value = pwd
|
||||
writeStoredAdminPassword(pwd)
|
||||
}
|
||||
|
||||
const setToken = (newToken: string) => {
|
||||
|
||||
const setToken = (newToken: string, newExpiresAt?: number) => {
|
||||
token.value = newToken
|
||||
writeStoredToken(newToken)
|
||||
expiresAt.value = newExpiresAt ?? null
|
||||
writeStoredToken(newToken, newExpiresAt)
|
||||
scheduleExpiration(expiresAt.value)
|
||||
}
|
||||
|
||||
|
||||
const setUserInfo = (user: AdminUser) => {
|
||||
userInfo.value = user
|
||||
isLoggedIn.value = true
|
||||
setToken(user.token)
|
||||
setToken(user.token, user.expires_at)
|
||||
}
|
||||
|
||||
|
||||
const login = (user: AdminUser) => {
|
||||
setUserInfo(user)
|
||||
}
|
||||
|
||||
|
||||
const logout = () => {
|
||||
clearExpirationTimer()
|
||||
adminPassword.value = ''
|
||||
token.value = ''
|
||||
expiresAt.value = null
|
||||
isLoggedIn.value = false
|
||||
userInfo.value = null
|
||||
|
||||
|
||||
clearStoredAuth()
|
||||
}
|
||||
|
||||
|
||||
const initAuth = () => {
|
||||
const storedToken = readStoredToken()
|
||||
if (storedToken) {
|
||||
if (hasValidStoredAdminSession()) {
|
||||
const storedToken = readStoredToken()
|
||||
token.value = storedToken
|
||||
expiresAt.value = readStoredTokenExpiresAt()
|
||||
isLoggedIn.value = true
|
||||
scheduleExpiration(expiresAt.value)
|
||||
} else {
|
||||
logout()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
scheduleExpiration(expiresAt.value)
|
||||
|
||||
return {
|
||||
// 状态
|
||||
adminPassword,
|
||||
token,
|
||||
expiresAt,
|
||||
isLoggedIn,
|
||||
userInfo,
|
||||
|
||||
|
||||
// 计算属性
|
||||
isAuthenticated,
|
||||
hasToken,
|
||||
|
||||
|
||||
// 方法
|
||||
updateAdminPassword,
|
||||
setToken,
|
||||
|
||||
+2
-1
@@ -3,5 +3,6 @@ export interface AdminUser {
|
||||
username: string
|
||||
token: string
|
||||
token_type?: string
|
||||
expires_at?: number
|
||||
expires_at: number
|
||||
expires_in?: number
|
||||
}
|
||||
@@ -34,6 +34,7 @@ export interface ConfigState {
|
||||
themesChoices: ThemeChoice[]
|
||||
expireStyle: string[]
|
||||
code_generate_type: 'number' | 'secret'
|
||||
adminSessionExpire: number
|
||||
admin_token: string
|
||||
robotsText: string
|
||||
keywords: string
|
||||
|
||||
@@ -12,15 +12,45 @@ export function readStoredToken(): string {
|
||||
return localStorage.getItem(STORAGE_KEYS.TOKEN) || ''
|
||||
}
|
||||
|
||||
export function writeStoredToken(token: string) {
|
||||
const readTokenPayloadExpiration = (token: string): number | null => {
|
||||
try {
|
||||
const payload = JSON.parse(atob(token.split('.')[1] || '')) as { exp?: unknown }
|
||||
const expiresAt = Number(payload.exp)
|
||||
return Number.isFinite(expiresAt) ? expiresAt : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function readStoredTokenExpiresAt(): number | null {
|
||||
const storedValue = Number(localStorage.getItem(STORAGE_KEYS.TOKEN_EXPIRES_AT))
|
||||
if (Number.isFinite(storedValue) && storedValue > 0) return storedValue
|
||||
return readTokenPayloadExpiration(readStoredToken())
|
||||
}
|
||||
|
||||
export function hasValidStoredAdminSession(): boolean {
|
||||
const token = readStoredToken()
|
||||
const expiresAt = readStoredTokenExpiresAt()
|
||||
return !!token && expiresAt !== null && expiresAt > Date.now() / 1000
|
||||
}
|
||||
|
||||
export function writeStoredToken(token: string, expiresAt?: number) {
|
||||
localStorage.setItem(STORAGE_KEYS.TOKEN, token)
|
||||
const normalizedExpiresAt = Number(expiresAt) || readTokenPayloadExpiration(token)
|
||||
if (normalizedExpiresAt) {
|
||||
localStorage.setItem(STORAGE_KEYS.TOKEN_EXPIRES_AT, String(normalizedExpiresAt))
|
||||
} else {
|
||||
localStorage.removeItem(STORAGE_KEYS.TOKEN_EXPIRES_AT)
|
||||
}
|
||||
}
|
||||
|
||||
export function clearStoredAuth() {
|
||||
localStorage.removeItem(STORAGE_KEYS.ADMIN_PASSWORD)
|
||||
localStorage.removeItem(STORAGE_KEYS.TOKEN)
|
||||
localStorage.removeItem(STORAGE_KEYS.TOKEN_EXPIRES_AT)
|
||||
}
|
||||
|
||||
export function clearStoredToken() {
|
||||
localStorage.removeItem(STORAGE_KEYS.TOKEN)
|
||||
localStorage.removeItem(STORAGE_KEYS.TOKEN_EXPIRES_AT)
|
||||
}
|
||||
@@ -43,6 +43,7 @@ export const DEFAULT_CONFIG_STATE: ConfigState = {
|
||||
themesChoices: [],
|
||||
expireStyle: DEFAULT_PUBLIC_CONFIG.expireStyle,
|
||||
code_generate_type: DEFAULT_PUBLIC_CONFIG.code_generate_type || 'secret',
|
||||
adminSessionExpire: 30 * 24 * 60 * 60,
|
||||
admin_token: '',
|
||||
robotsText: '',
|
||||
keywords: '',
|
||||
|
||||
@@ -18,6 +18,7 @@ const {
|
||||
sizeUnit,
|
||||
saveTime,
|
||||
saveTimeUnit,
|
||||
adminSessionDays,
|
||||
refreshConfig,
|
||||
submitConfig,
|
||||
toggleConfigFlag
|
||||
@@ -168,6 +169,29 @@ onMounted(() => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
|
||||
<div>
|
||||
<SettingNumberInput
|
||||
v-model="adminSessionDays"
|
||||
:label="t('admin.settings.sessionDuration')"
|
||||
:suffix="t('common.day')"
|
||||
:min="1"
|
||||
:max="365"
|
||||
/>
|
||||
<p class="mt-2 text-xs" :class="[isDarkMode ? 'text-zinc-400' : 'text-zinc-500']">
|
||||
{{ t('admin.settings.sessionDurationHelp') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<SettingSwitch
|
||||
:label="t('admin.settings.showAdminAddress')"
|
||||
:model-value="config.showAdminAddr"
|
||||
:enabled-text="t('common.enabled')"
|
||||
:disabled-text="t('common.disabled')"
|
||||
@toggle="toggleConfigFlag('showAdminAddr')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<label
|
||||
class="block text-sm font-medium"
|
||||
|
||||
Reference in new issue
Block a user