-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Expand file tree
/
Copy pathAuthContext.jsx
More file actions
80 lines (69 loc) · 2.07 KB
/
Copy pathAuthContext.jsx
File metadata and controls
80 lines (69 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
79
80
import { createContext, useContext, useState, useEffect } from 'react'
import { apiUrl } from '../utils/basePath'
const AuthContext = createContext(null)
export function AuthProvider({ children }) {
const [state, setState] = useState({
loading: true,
authEnabled: false,
staticApiKeyRequired: false,
user: null,
permissions: {},
})
const fetchStatus = () => {
return fetch(apiUrl('/api/auth/status'))
.then(r => r.json())
.then(data => {
const user = data.user || null
const permissions = user?.permissions || {}
setState({
loading: false,
authEnabled: data.authEnabled || false,
staticApiKeyRequired: data.staticApiKeyRequired || false,
user,
permissions,
})
})
.catch(() => {
setState({ loading: false, authEnabled: false, staticApiKeyRequired: false, user: null, permissions: {} })
})
}
useEffect(() => {
fetchStatus()
}, [])
const logout = async () => {
try {
await fetch(apiUrl('/api/auth/logout'), { method: 'POST' })
} catch (_) { /* ignore */ }
// Clear cookies
document.cookie = 'session=; path=/; max-age=-1'
document.cookie = 'token=; path=/; max-age=-1'
window.location.href = '/login'
}
const refresh = () => fetchStatus()
const noAuthRequired = !state.authEnabled && !state.staticApiKeyRequired
const hasFeature = (name) => {
if (state.user?.role === 'admin' || noAuthRequired) return true
return !!state.permissions[name]
}
const value = {
loading: state.loading,
authEnabled: state.authEnabled,
staticApiKeyRequired: state.staticApiKeyRequired,
user: state.user,
permissions: state.permissions,
isAdmin: state.user?.role === 'admin' || noAuthRequired,
hasFeature,
logout,
refresh,
}
return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
)
}
export function useAuth() {
const ctx = useContext(AuthContext)
if (!ctx) throw new Error('useAuth must be used within AuthProvider')
return ctx
}