68 lines
1.8 KiB
JavaScript
68 lines
1.8 KiB
JavaScript
/**
|
|
* Login storage for remote Sub-Store backend URI + admin token.
|
|
*/
|
|
|
|
const REMOTE_URI_KEY = 'sub_store_remote_uri'
|
|
const TOKEN_KEY = 'sub_store_admin_token'
|
|
const VALIDATED_KEY = 'sub_store_token_validated'
|
|
|
|
export function normalizeRemoteUri(uri) {
|
|
const value = (uri || '').trim().replace(/\/+$/, '').replace(/\/api$/, '')
|
|
if (!value) return ''
|
|
const parsed = new URL(value)
|
|
if (!['http:', 'https:'].includes(parsed.protocol)) {
|
|
throw new Error('Remote URI must use http or https')
|
|
}
|
|
return parsed.toString().replace(/\/+$/, '')
|
|
}
|
|
|
|
export function storeLogin(remoteUri, token) {
|
|
const normalizedRemoteUri = normalizeRemoteUri(remoteUri)
|
|
if (normalizedRemoteUri && token) {
|
|
localStorage.setItem(REMOTE_URI_KEY, normalizedRemoteUri)
|
|
localStorage.setItem(TOKEN_KEY, token)
|
|
localStorage.setItem(VALIDATED_KEY, 'true')
|
|
}
|
|
}
|
|
|
|
export function getStoredRemoteUri() {
|
|
return localStorage.getItem(REMOTE_URI_KEY) || ''
|
|
}
|
|
|
|
export function getStoredToken() {
|
|
return localStorage.getItem(TOKEN_KEY) || ''
|
|
}
|
|
|
|
export function isTokenValidated() {
|
|
return localStorage.getItem(VALIDATED_KEY) === 'true'
|
|
}
|
|
|
|
export function clearToken() {
|
|
localStorage.removeItem(REMOTE_URI_KEY)
|
|
localStorage.removeItem(TOKEN_KEY)
|
|
localStorage.removeItem(VALIDATED_KEY)
|
|
}
|
|
|
|
export async function validateToken(token, remoteUri) {
|
|
if (!token) return false
|
|
try {
|
|
const base = normalizeRemoteUri(remoteUri)
|
|
const resp = await fetch(`${base}/api/env`, {
|
|
headers: { Authorization: `Bearer ${token}` },
|
|
})
|
|
if (!resp.ok) return false
|
|
const data = await resp.json()
|
|
return data.status === 'success'
|
|
} catch {
|
|
return false
|
|
}
|
|
}
|
|
|
|
export function getEffectiveToken() {
|
|
return getStoredToken()
|
|
}
|
|
|
|
export function getApiBaseUrl() {
|
|
return getStoredRemoteUri() || (window.SUB_STORE_CONFIG?.apiBaseUrl) || ''
|
|
}
|