feat(ui): show user and logout
This commit is contained in:
55
apps/visualizer/src/layout/AuthStatus.tsx
Normal file
55
apps/visualizer/src/layout/AuthStatus.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import Button from '../ui/Button';
|
||||
|
||||
type WhoamiResponse = {
|
||||
ok?: boolean;
|
||||
user?: string | null;
|
||||
};
|
||||
|
||||
export default function AuthStatus() {
|
||||
const [user, setUser] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
fetch('/whoami', { cache: 'no-store' })
|
||||
.then(async (res) => {
|
||||
const json = (await res.json().catch(() => null)) as WhoamiResponse | null;
|
||||
const u = typeof json?.user === 'string' ? json.user.trim() : '';
|
||||
return u || null;
|
||||
})
|
||||
.then((u) => {
|
||||
if (cancelled) return;
|
||||
setUser(u);
|
||||
})
|
||||
.catch(() => {
|
||||
if (cancelled) return;
|
||||
setUser(null);
|
||||
})
|
||||
.finally(() => {
|
||||
if (cancelled) return;
|
||||
setLoading(false);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const logout = () => {
|
||||
window.location.href = '/logout';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="authStatus">
|
||||
<Button size="sm" variant="ghost" type="button" onClick={logout}>
|
||||
Wyloguj
|
||||
</Button>
|
||||
<div className="topNav__account">
|
||||
<div className="topNav__accountName">{loading ? '…' : user || 'unknown'}</div>
|
||||
<div className="topNav__accountSub">zalogowany</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user