-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathAuthContext.tsx
More file actions
198 lines (171 loc) · 6.41 KB
/
AuthContext.tsx
File metadata and controls
198 lines (171 loc) · 6.41 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import {
createContext,
ReactNode,
useContext,
useEffect,
useState
} from 'react';
import { Action, Condition, Subject } from '@/permissions/constants';
import {
deleteAuthToken,
getAuthToken,
getDecodedAuthToken
} from '@/utils/authTokenHandler';
interface AuthState {
token: string;
firstName: string;
userObjectId: string;
userRole: string;
lastestLocationObjectId: string;
permissions: {
action: Action;
subject: Subject;
conditions: Condition[];
}[];
isLoggedIn: boolean;
isLoading: boolean;
}
interface AuthContextValue extends AuthState {
setToken: (token: string) => void;
setUserObjectId: (userObjectId: string) => void;
setFirstName: (firstName: string) => void;
setUserRole: (userRole: string) => void;
setLastestLocationObjectId: (lastestLocationObjectId: string) => void;
setPermissions: (
permissions: {
action: Action;
subject: Subject;
conditions: Condition[];
}[]
) => void;
clearSession: () => void;
fetchUserContext: (userObjectId: string) => Promise<void>;
}
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
function getDefaultAuthState(): AuthState {
return {
token: '',
firstName: '',
userObjectId: '',
userRole: '',
lastestLocationObjectId: '',
permissions: [],
isLoggedIn: false,
isLoading: false
};
}
export const AuthProvider = ({ children }: { children: ReactNode }) => {
const [state, setState] = useState<AuthState>(() => {
const token = getAuthToken(); // Reads from Zustand
if (!token) return getDefaultAuthState();
const decoded = getDecodedAuthToken();
if (!decoded) return getDefaultAuthState();
return {
token,
firstName: decoded.firstName,
userRole: decoded.role,
userObjectId: decoded.userObjectId,
permissions: [],
lastestLocationObjectId: '',
isLoggedIn: true,
// REVIEW: where are we using isLoading?
isLoading: true
};
});
/*
The `useEffect` hook runs once when the component mounts (indicated by the empty dependency array `[]`). This is the authentication context initialization logic that determines whether to load user data or immediately mark the auth state as ready.
**The conditional logic branch works as follows**: If both `state.token` and `state.userObjectId` exist (meaning the user has a valid JWT token and MongoDB user ID stored in localStorage via Zustand), the effect calls `fetchUserContext()` to retrieve the full user profile from the backend. This happens when a user refreshes the page or returns to the app with an existing session. The function will make an API call to `/api/v2/users/:id`, validate the token via the auth middleware, and populate the context with user details like name, role, and permissions.
**If either value is missing**, the effect takes a different path: it immediately sets `isLoading: false` without making any API calls. This signals to the rest of the application that there's no active session to restore, allowing login/registration screens to render immediately instead of showing a loading spinner while waiting for a user fetch that would fail anyway.
**A critical gotcha here**: The empty dependency array means this only runs on mount, so if `state.token` or `state.userObjectId` change later (e.g., after login), this effect won't re-run. The app must handle user data fetching separately in the login flow—typically in the login success handler that sets these values and then manually calls `fetchUserContext()` or triggers a re-render that causes the context to update through other means.
This pattern is common in auth contexts because you want to check for existing sessions exactly once at startup, not repeatedly as state changes during normal app usage. The actual authentication state updates happen through explicit actions (login, logout) rather than reactive effects.
*/
useEffect(() => {
if (state.token && state.userObjectId) {
fetchUserContext(state.userObjectId);
} else {
setState(prev => ({ ...prev, isLoading: false }));
}
}, []);
const fetchUserContext = async (userObjectId: string) => {
try {
const token = getAuthToken();
// fetch user
const userResponse = await fetch(`/api/v2/users/${userObjectId}`, {
headers: {
Authorization: `Bearer ${token}`
}
});
const user = await userResponse.json();
// fetch user's surveys to get latest location
const surveysResponse = await fetch(
`/api/v2/surveys?createdByUserObjectId=${userObjectId}`,
{
headers: {
Authorization: `Bearer ${token}`
}
}
);
const surveys = await surveysResponse.json();
const latestLocationObjectId =
surveys.data[0]?.locationObjectId ?? user.data.locationObjectId;
setState(prev => ({
...prev,
userObjectId: user.data._id,
firstName: user.data.firstName,
userRole: user.data.role,
lastestLocationObjectId: latestLocationObjectId,
permissions: user.data.permissions,
isLoggedIn: true,
isLoading: false
}));
} catch (error) {
console.error('Error fetching user context:', error);
setState(prev => ({ ...prev, isLoading: false }));
}
};
const setToken = (token: string) => {
setState(prev => ({ ...prev, token, isLoggedIn: !!token }));
};
const setUserObjectId = (userObjectId: string) => {
setState(prev => ({ ...prev, userObjectId }));
};
const setFirstName = (firstName: string) => {
setState(prev => ({ ...prev, firstName }));
};
const setUserRole = (userRole: string) => {
setState(prev => ({ ...prev, userRole }));
};
const setLastestLocationObjectId = (lastestLocationObjectId: string) => {
setState(prev => ({ ...prev, lastestLocationObjectId }));
};
const setPermissions = (permissions: AuthState['permissions']) => {
setState(prev => ({ ...prev, permissions }));
};
const clearSession = () => {
deleteAuthToken(); // Clears from Zustand
setState(getDefaultAuthState());
};
// The value that you want to pass to all the components reading this context inside this provider.
const value: AuthContextValue = {
...state,
setToken,
setUserObjectId,
setFirstName,
setUserRole,
setLastestLocationObjectId,
setPermissions,
clearSession,
fetchUserContext
};
return (
<AuthContext.Provider value={value}>{children}</AuthContext.Provider>
);
};
// REVIEW: Why is this here? Move to a separate file? What does useAuth do?
export const useAuthContext = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuthContext must be used within AuthProvider');
}
return context;
};