fix(backend): add token expiration handling for beszel auth
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 1m18s
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 1m18s
- Track token expiry time to prevent using expired tokens - Set token lifetime to 50 minutes (safe margin before 1hr expiry) - Add comprehensive logging for auth events and errors - Improve error responses with status text - Fixes system tiles stopping after ~1 hour of operation Co-authored-by: Ona <no-reply@ona.com>
This commit is contained in:
@@ -32,6 +32,7 @@ beszel.get("/systems", async (c) => {
|
|||||||
const token = c.get("beszelToken")
|
const token = c.get("beszelToken")
|
||||||
|
|
||||||
if (!beszelHost) {
|
if (!beszelHost) {
|
||||||
|
console.error("[Beszel API] BESZEL_HOST environment variable not set")
|
||||||
return c.json({ error: "BESZEL_HOST environment variable not set" }, 500)
|
return c.json({ error: "BESZEL_HOST environment variable not set" }, 500)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,10 +43,17 @@ beszel.get("/systems", async (c) => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
|
const errorText = await response.text()
|
||||||
|
console.error(
|
||||||
|
`[Beszel API] Failed to fetch systems: ${response.status} ${response.statusText}`,
|
||||||
|
errorText ? `- ${errorText}` : "",
|
||||||
|
)
|
||||||
|
|
||||||
return new Response(
|
return new Response(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
error: "Failed to fetch Beszel data",
|
error: "Failed to fetch Beszel data",
|
||||||
status: response.status,
|
status: response.status,
|
||||||
|
statusText: response.statusText,
|
||||||
}),
|
}),
|
||||||
{
|
{
|
||||||
status: response.status,
|
status: response.status,
|
||||||
@@ -66,12 +74,15 @@ beszel.get("/systems", async (c) => {
|
|||||||
},
|
},
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
console.log(`[Beszel API] Successfully fetched ${systems.length} systems`)
|
||||||
|
|
||||||
return c.json({
|
return c.json({
|
||||||
lastUpdated: new Date().toISOString(),
|
lastUpdated: new Date().toISOString(),
|
||||||
systems,
|
systems,
|
||||||
totalSystems: systems.length,
|
totalSystems: systems.length,
|
||||||
})
|
})
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
console.error("[Beszel API] Internal server error:", error)
|
||||||
return c.json({ error: "Internal server error", message: String(error) }, 500)
|
return c.json({ error: "Internal server error", message: String(error) }, 500)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -6,12 +6,26 @@ interface BeszelAuthResponse {
|
|||||||
|
|
||||||
export function beszelAuth(): MiddlewareHandler {
|
export function beszelAuth(): MiddlewareHandler {
|
||||||
let cachedToken: string | null = null
|
let cachedToken: string | null = null
|
||||||
|
let tokenExpiry: number | null = null
|
||||||
|
|
||||||
|
// Token lifetime: 50 minutes (tokens typically expire after 1 hour, refresh before that)
|
||||||
|
const TOKEN_LIFETIME_MS = 50 * 60 * 1000
|
||||||
|
|
||||||
const authenticate = async (): Promise<string> => {
|
const authenticate = async (): Promise<string> => {
|
||||||
if (cachedToken) {
|
const now = Date.now()
|
||||||
|
|
||||||
|
// Return cached token if it exists and hasn't expired
|
||||||
|
if (cachedToken && tokenExpiry && now < tokenExpiry) {
|
||||||
return cachedToken
|
return cachedToken
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Log re-authentication for debugging
|
||||||
|
if (cachedToken && tokenExpiry && now >= tokenExpiry) {
|
||||||
|
console.log("[Beszel Auth] Token expired, re-authenticating...")
|
||||||
|
} else {
|
||||||
|
console.log("[Beszel Auth] Initial authentication...")
|
||||||
|
}
|
||||||
|
|
||||||
const beszelHost = process.env.BESZEL_HOST
|
const beszelHost = process.env.BESZEL_HOST
|
||||||
const beszelEmail = process.env.BESZEL_EMAIL
|
const beszelEmail = process.env.BESZEL_EMAIL
|
||||||
const beszelPassword = process.env.BESZEL_PASSWORD
|
const beszelPassword = process.env.BESZEL_PASSWORD
|
||||||
@@ -34,11 +48,16 @@ export function beszelAuth(): MiddlewareHandler {
|
|||||||
})
|
})
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
|
const errorText = await response.text()
|
||||||
|
console.error(`[Beszel Auth] Authentication failed: ${response.status} - ${errorText}`)
|
||||||
throw new Error(`Beszel authentication failed: ${response.status}`)
|
throw new Error(`Beszel authentication failed: ${response.status}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = (await response.json()) as BeszelAuthResponse
|
const data = (await response.json()) as BeszelAuthResponse
|
||||||
cachedToken = data.token
|
cachedToken = data.token
|
||||||
|
tokenExpiry = now + TOKEN_LIFETIME_MS
|
||||||
|
|
||||||
|
console.log(`[Beszel Auth] Authentication successful, token valid until ${new Date(tokenExpiry).toISOString()}`)
|
||||||
|
|
||||||
return cachedToken
|
return cachedToken
|
||||||
}
|
}
|
||||||
@@ -49,6 +68,7 @@ export function beszelAuth(): MiddlewareHandler {
|
|||||||
c.set("beszelToken", token)
|
c.set("beszelToken", token)
|
||||||
await next()
|
await next()
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
console.error("[Beszel Auth] Middleware error:", error)
|
||||||
return c.json({ error: "Authentication failed", message: String(error) }, 500)
|
return c.json({ error: "Authentication failed", message: String(error) }, 500)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user