Initial commit
This commit is contained in:
58
frontend/app/ui/HeaderActions.tsx
Normal file
58
frontend/app/ui/HeaderActions.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
'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'
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="header-actions">
|
||||
<a href="/">Requests</a>
|
||||
<a href="/how-it-works">How it works</a>
|
||||
{signedIn && <a href="/profile">My profile</a>}
|
||||
{role === 'admin' && <a href="/admin">Settings</a>}
|
||||
{signedIn ? (
|
||||
<button type="button" className="header-link" onClick={signOut}>
|
||||
Sign out
|
||||
</button>
|
||||
) : (
|
||||
<a href="/login">Sign in</a>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user