60 lines
1.4 KiB
TypeScript
60 lines
1.4 KiB
TypeScript
'use client'
|
|
|
|
import { useEffect, useState } from 'react'
|
|
import { authFetch, clearToken, getApiBase, getToken } from '../lib/auth'
|
|
|
|
export default function HeaderActions() {
|
|
const [signedIn, setSignedIn] = useState(false)
|
|
const [role, setRole] = useState<string | null>(null)
|
|
|
|
useEffect(() => {
|
|
const token = getToken()
|
|
setSignedIn(Boolean(token))
|
|
if (!token) {
|
|
return
|
|
}
|
|
const load = async () => {
|
|
try {
|
|
const baseUrl = getApiBase()
|
|
const response = await authFetch(`${baseUrl}/auth/me`)
|
|
if (!response.ok) {
|
|
clearToken()
|
|
setSignedIn(false)
|
|
setRole(null)
|
|
return
|
|
}
|
|
const data = await response.json()
|
|
setRole(data?.role ?? null)
|
|
} catch (err) {
|
|
console.error(err)
|
|
}
|
|
}
|
|
void load()
|
|
}, [])
|
|
|
|
const signOut = () => {
|
|
clearToken()
|
|
setSignedIn(false)
|
|
if (typeof window !== 'undefined') {
|
|
window.location.href = '/login'
|
|
}
|
|
}
|
|
|
|
if (!signedIn) {
|
|
return null
|
|
}
|
|
|
|
return (
|
|
<div className="header-actions">
|
|
<a href="/">Requests</a>
|
|
<a href="/how-it-works">How it works</a>
|
|
<a href="/profile">My profile</a>
|
|
<a className="header-cta" href="/feedback">Send feedback</a>
|
|
{role === 'admin' && <a href="/admin">Settings</a>}
|
|
<button type="button" className="header-link" onClick={signOut}>
|
|
Sign out
|
|
</button>
|
|
</div>
|
|
)
|
|
}
|