forked from ZyntariHQ/Invoisio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-auth-store.ts
More file actions
167 lines (151 loc) · 4.54 KB
/
Copy pathuse-auth-store.ts
File metadata and controls
167 lines (151 loc) · 4.54 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
import { create } from "zustand";
import * as SecureStore from "expo-secure-store";
import { authService } from "../lib/auth-service";
const AUTH_STORAGE_KEY = "@invoisio:auth";
interface AuthState {
accessToken: string | null;
publicKey: string | null;
expiresAt: number | null;
isAuthenticated: boolean;
isLoading: boolean;
// Actions
setAuth: (accessToken: string, publicKey: string) => Promise<void>;
clearAuth: () => Promise<void>;
loadAuth: () => Promise<boolean>;
}
export const useAuthStore = create<AuthState>((set) => ({
accessToken: null,
publicKey: null,
expiresAt: null,
isAuthenticated: false,
isLoading: true,
setAuth: async (accessToken: string, publicKey: string) => {
try {
const expiresAt = authService.decodeTokenExpiry(accessToken);
if (
expiresAt == null ||
!publicKey.startsWith("G") ||
publicKey.length !== 56
) {
throw new Error("Cannot persist invalid authentication data");
}
const authData = { accessToken, publicKey, expiresAt };
await SecureStore.setItemAsync(
AUTH_STORAGE_KEY,
JSON.stringify(authData),
);
set({
accessToken,
publicKey,
expiresAt,
isAuthenticated: true,
isLoading: false,
});
} catch (error) {
console.error("Error storing auth data:", error);
throw error;
}
},
clearAuth: async () => {
try {
await SecureStore.deleteItemAsync(AUTH_STORAGE_KEY);
set({
accessToken: null,
publicKey: null,
expiresAt: null,
isAuthenticated: false,
isLoading: false,
});
} catch (error) {
console.error("Error clearing auth data:", error);
throw error;
}
},
loadAuth: async () => {
try {
const authDataString = await SecureStore.getItemAsync(AUTH_STORAGE_KEY);
if (!authDataString) {
set({ isLoading: false });
return false;
}
const authData = JSON.parse(authDataString) as {
accessToken?: string;
publicKey?: string;
expiresAt?: number | null;
};
const storedAccessToken = authData.accessToken;
const storedPublicKey = authData.publicKey;
const hasValidIdentity =
typeof storedAccessToken === "string" &&
storedAccessToken.length > 0 &&
typeof storedPublicKey === "string" &&
storedPublicKey.startsWith("G") &&
storedPublicKey.length === 56;
if (hasValidIdentity) {
const expiresAt =
typeof authData.expiresAt === "number"
? authData.expiresAt
: authService.decodeTokenExpiry(storedAccessToken);
// Local expiry check first — works offline and avoids a wasted request.
if (expiresAt == null || Date.now() >= expiresAt) {
await SecureStore.deleteItemAsync(AUTH_STORAGE_KEY);
set({
accessToken: null,
publicKey: null,
expiresAt: null,
isAuthenticated: false,
isLoading: false,
});
return false;
}
// Confirm with the backend. A network failure ("unknown") keeps the
// restored session so transient connectivity issues do not log the
// merchant out; only an explicit rejection clears credentials.
const status = await authService.verifyToken(storedAccessToken);
if (status === "invalid") {
await SecureStore.deleteItemAsync(AUTH_STORAGE_KEY);
set({
accessToken: null,
publicKey: null,
expiresAt: null,
isAuthenticated: false,
isLoading: false,
});
return false;
}
set({
accessToken: storedAccessToken,
publicKey: storedPublicKey,
expiresAt,
isAuthenticated: true,
isLoading: false,
});
return true;
}
await SecureStore.deleteItemAsync(AUTH_STORAGE_KEY);
set({
accessToken: null,
publicKey: null,
expiresAt: null,
isAuthenticated: false,
isLoading: false,
});
return false;
} catch (error) {
console.error("Error loading auth data:", error);
try {
await SecureStore.deleteItemAsync(AUTH_STORAGE_KEY);
} catch {
// Preserve the original load failure while resetting memory safely.
}
set({
accessToken: null,
publicKey: null,
expiresAt: null,
isAuthenticated: false,
isLoading: false,
});
return false;
}
},
}));