30 lines
1.0 KiB
TypeScript
30 lines
1.0 KiB
TypeScript
const TOKEN_KEY = 'commander-auth-token'
|
|
export const AUTH_CHANGED = 'commander-auth-change'
|
|
|
|
// Stored in a cookie (not localStorage) so the server can redirect before rendering.
|
|
export function authToken(): string | undefined {
|
|
if (typeof document === 'undefined') return undefined
|
|
const value = document.cookie
|
|
.split('; ')
|
|
.find(cookie => cookie.startsWith(`${TOKEN_KEY}=`))
|
|
?.slice(TOKEN_KEY.length + 1)
|
|
return value ? decodeURIComponent(value) : undefined
|
|
}
|
|
|
|
export function setAuthToken(token: string | undefined): void {
|
|
if (typeof document === 'undefined') return
|
|
document.cookie = token
|
|
? `${TOKEN_KEY}=${encodeURIComponent(token)}; path=/; max-age=31536000; SameSite=Lax`
|
|
: `${TOKEN_KEY}=; path=/; max-age=0; SameSite=Lax`
|
|
window.dispatchEvent(new Event(AUTH_CHANGED))
|
|
}
|
|
|
|
export function hasAuth(): boolean {
|
|
return Boolean(authToken())
|
|
}
|
|
|
|
export function authHeaders(): Record<string, string> {
|
|
const token = authToken()
|
|
return token ? { Authorization: `Bearer ${token}` } : {}
|
|
}
|