54 lines
1.7 KiB
TypeScript
54 lines
1.7 KiB
TypeScript
import type { Router } from 'vue-router'
|
|
|
|
let router: Router | null = null
|
|
let loginNavigationPending = false
|
|
|
|
const defaultAuthenticatedRoute = '/dashboard'
|
|
|
|
function browserRoute(): string {
|
|
if (import.meta.env.VITE_ROUTER_MODE === 'hash') {
|
|
const hashRoute = window.location.hash.replace(/^#/, '')
|
|
return hashRoute.startsWith('/') ? hashRoute : '/'
|
|
}
|
|
return window.location.pathname + window.location.search + window.location.hash
|
|
}
|
|
|
|
export function safeAuthRedirect(value: unknown): string {
|
|
if (typeof value !== 'string') return defaultAuthenticatedRoute
|
|
const path = value.trim()
|
|
if (!path.startsWith('/') || path.startsWith('//')) return defaultAuthenticatedRoute
|
|
|
|
const pathOnly = path.split(/[?#]/, 1)[0].replace(/\/+$/, '').toLowerCase()
|
|
if (pathOnly === '/login') return defaultAuthenticatedRoute
|
|
|
|
return path
|
|
}
|
|
|
|
export function setRouter(r: Router): void {
|
|
router = r
|
|
}
|
|
|
|
export function goLogin(redirect?: unknown): void {
|
|
if (router) {
|
|
if (router.currentRoute.value.name === 'login' || loginNavigationPending) return
|
|
|
|
const currentRoute = router.currentRoute.value
|
|
const returnUrl = safeAuthRedirect(
|
|
redirect ?? (currentRoute.name ? currentRoute.fullPath : browserRoute()),
|
|
)
|
|
loginNavigationPending = true
|
|
void router.push({ name: 'login', query: { redirect: returnUrl } })
|
|
.finally(() => {
|
|
loginNavigationPending = false
|
|
})
|
|
return
|
|
}
|
|
|
|
const returnUrl = safeAuthRedirect(redirect ?? browserRoute())
|
|
const query = `redirect=${encodeURIComponent(returnUrl)}`
|
|
const loginUrl = import.meta.env.VITE_ROUTER_MODE === 'hash'
|
|
? `${import.meta.env.BASE_URL}#/login?${query}`
|
|
: `/login?${query}`
|
|
window.location.assign(loginUrl)
|
|
}
|