forked from worlddriven/webapp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseAuth.js
More file actions
78 lines (71 loc) · 2.07 KB
/
useAuth.js
File metadata and controls
78 lines (71 loc) · 2.07 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { useState, useEffect, useCallback } from 'react';
export function useAuth() {
const [user, setUser] = useState(null);
const [authenticated, setAuthenticated] = useState(false);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function performAuthCheck() {
try {
const response = await fetch('/api/v1/user/');
if (response.ok) {
const data = await response.json();
setAuthenticated(true);
setUser(data);
} else {
setAuthenticated(false);
setUser(null);
}
} catch (error) {
console.error('Auth check failed:', error);
setAuthenticated(false);
setUser(null);
}
setLoading(false);
}
performAuthCheck();
}, []);
const checkAuth = useCallback(async () => {
try {
const response = await fetch('/api/v1/user/');
if (response.ok) {
const data = await response.json();
setAuthenticated(true);
setUser(data);
} else {
setAuthenticated(false);
setUser(null);
}
} catch (error) {
console.error('Auth check failed:', error);
setAuthenticated(false);
setUser(null);
}
}, []);
const logout = useCallback(async () => {
try {
await fetch('/api/user/logout', { method: 'GET' });
setAuthenticated(false);
setUser(null);
window.location.href = '/';
} catch (error) {
console.error('Logout failed:', error);
}
}, []);
const login = useCallback(async () => {
try {
const callbackUrl = `${window.location.origin}/auth/callback`;
const response = await fetch(
`/api/auth/url?redirect_uri=${encodeURIComponent(callbackUrl)}`
);
if (response.ok) {
const data = await response.json();
window.location.href = data.url;
} else {
console.error('Failed to get OAuth URL:', response.status);
}
} catch (error) {
console.error('Login failed:', error);
}
}, []);
return { user, authenticated, loading, login, logout, checkAuth };
}