forked from balahero03/eOrbitor_Pulse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseCurrentUser.ts
More file actions
43 lines (37 loc) · 974 Bytes
/
Copy pathuseCurrentUser.ts
File metadata and controls
43 lines (37 loc) · 974 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
'use client';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
export type CurrentUser = {
id: string;
email: string;
firstName: string;
lastName: string;
role: string;
department?: string;
};
export function useCurrentUser() {
const [user, setUser] = useState<CurrentUser | null>(null);
const [loading, setLoading] = useState(true);
const router = useRouter();
useEffect(() => {
const token = localStorage.getItem('token');
if (!token) {
router.push('/login');
return;
}
fetch('/api/auth/me', { headers: { Authorization: `Bearer ${token}` } })
.then((r) => {
if (!r.ok) throw new Error('Unauthorized');
return r.json();
})
.then((u) => {
setUser(u);
setLoading(false);
})
.catch(() => {
localStorage.removeItem('token');
router.push('/login');
});
}, [router]);
return { user, loading };
}