Clear sessionStorage on 403 and retry with fresh visitor
When SECRET_ANALYTICS changes (deploy), old uid/hash become invalid. On 403, clear session and auto-retry with a new visitor creation. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -34,6 +34,11 @@ async function decrypt(b64) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function clearSession() {
|
||||||
|
sessionStorage.removeItem(SK_UID)
|
||||||
|
sessionStorage.removeItem(SK_HASH)
|
||||||
|
}
|
||||||
|
|
||||||
async function send(data, expectResponse = false) {
|
async function send(data, expectResponse = false) {
|
||||||
const d = await encrypt(data)
|
const d = await encrypt(data)
|
||||||
if (!d) return null
|
if (!d) return null
|
||||||
@@ -48,6 +53,10 @@ async function send(data, expectResponse = false) {
|
|||||||
body: JSON.stringify({ d }),
|
body: JSON.stringify({ d }),
|
||||||
keepalive: true,
|
keepalive: true,
|
||||||
})
|
})
|
||||||
|
if (res.status === 403) {
|
||||||
|
clearSession()
|
||||||
|
return null
|
||||||
|
}
|
||||||
if (!res.ok || res.status === 204) return null
|
if (!res.ok || res.status === 204) return null
|
||||||
const json = await res.json()
|
const json = await res.json()
|
||||||
return json.d ? await decrypt(json.d) : null
|
return json.d ? await decrypt(json.d) : null
|
||||||
@@ -96,11 +105,18 @@ export async function initAnalytics() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const visitor = await getOrCreateVisitor()
|
let visitor = await getOrCreateVisitor()
|
||||||
if (!visitor) return
|
if (!visitor) return
|
||||||
|
|
||||||
await trackPageView(visitor)
|
await trackPageView(visitor)
|
||||||
|
|
||||||
|
// If trackPageView got 403 (stale session), retry with fresh visitor
|
||||||
|
if (!sessionStorage.getItem(SK_UID)) {
|
||||||
|
visitor = await getOrCreateVisitor()
|
||||||
|
if (!visitor) return
|
||||||
|
await trackPageView(visitor)
|
||||||
|
}
|
||||||
|
|
||||||
const authUserId = document.body.dataset.uid
|
const authUserId = document.body.dataset.uid
|
||||||
if (authUserId) {
|
if (authUserId) {
|
||||||
await setAuth(parseInt(authUserId, 10))
|
await setAuth(parseInt(authUserId, 10))
|
||||||
|
|||||||
Reference in New Issue
Block a user