Repository navigation
Expand file tree
/
Copy pathauthStore.js
More file actions
58 lines (50 loc) · 1.4 KB
/
Copy pathauthStore.js
File metadata and controls
58 lines (50 loc) · 1.4 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
import { create } from "zustand";
import { AuthAPI } from "../api/auth.api.js";
import { AdminAuthAPI } from "../api/admin-auth.api.js";
export const useAuthStore = create((set) => ({
user: null,
role: null,
loading: true,
isAuthenticated: false,
login: (user, role = "student") =>
set({
user,
role,
isAuthenticated: true,
loading: false,
}),
logout: () =>
set({
user: null,
role: null,
isAuthenticated: false,
loading: false,
}),
// Revokes the session server-side (clears the refresh-token hash + cookie),
// then clears local state. Prefer this over calling `logout()` directly.
logoutAndClear: async (isAdmin = false) => {
try {
await (isAdmin ? AdminAuthAPI.logout() : AuthAPI.logout());
} catch {
// best-effort — still clear local state even if the network call fails
}
localStorage.removeItem(isAdmin ? "adminToken" : "token");
// Without this, Google's auto sign-in would put the person straight back
// in the next time they open the login page after logging out.
try {
window.google?.accounts?.id?.disableAutoSelect();
} catch {
// Google script not loaded on this page; nothing to disable.
}
set({
user: null,
role: null,
isAuthenticated: false,
loading: false,
});
},
finishLoading: () =>
set({
loading: false,
}),
}));