-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp-config.js
More file actions
183 lines (159 loc) · 3.96 KB
/
Copy pathapp-config.js
File metadata and controls
183 lines (159 loc) · 3.96 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
/**
* Server Configuration Manager
* To switch between servers, change the line below:
* "localhost" = Development (http://localhost:8080/api/todos)
* "render" = Production (https://to-do-list-eki9.onrender.com/api/todos)
*/
const ACTIVE_SERVER = "localhost"; // Change this to "localhost" or "render"
const AUTH_TOKEN_KEY = "todoAuthToken";
const SERVERS = {
localhost: "http://localhost:8080/api/todos",
render: "https://to-do-list-eki9.onrender.com/api/todos",
};
/**
* Get the API base URL for the current server
*/
function getApiBase() {
return SERVERS[ACTIVE_SERVER];
}
/**
* Get the current server mode ("localhost" or "render")
*/
function getServerMode() {
return ACTIVE_SERVER;
}
/**
* Build API URL for a given endpoint path
*/
function apiUrl(path) {
const base = getApiBase();
// Ensure path starts with /
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
return `${base}${normalizedPath}`;
}
/**
* Build Authorization headers with JWT token
*/
function buildAuthHeaders(extraHeaders = {}) {
const headers = { ...extraHeaders };
const token = getAuthToken();
if (token) {
headers.Authorization = `Bearer ${token}`;
}
return headers;
}
/**
* Check whether the JWT has expired based on its exp claim
*/
function isTokenExpired(token) {
const payload = decodeJwtPayload(token);
if (!payload || !payload.exp) {
return true;
}
const expiresAtMs = payload.exp * 1000;
return Date.now() >= expiresAtMs;
}
/**
* Check if user has a valid auth token
*/
function hasAuthToken() {
const token = localStorage.getItem(AUTH_TOKEN_KEY);
if (!token) {
return false;
}
if (isTokenExpired(token)) {
clearAuthToken();
return false;
}
return true;
}
/**
* Store auth token (called after successful login/register)
*/
function storeAuthToken(token) {
localStorage.setItem(AUTH_TOKEN_KEY, token);
}
/**
* Get auth token
*/
function getAuthToken() {
const token = localStorage.getItem(AUTH_TOKEN_KEY);
if (!token) {
return null;
}
if (isTokenExpired(token)) {
clearAuthToken();
return null;
}
return token;
}
/**
* Clear auth token (called on logout)
*/
function clearAuthToken() {
localStorage.removeItem(AUTH_TOKEN_KEY);
}
/**
* Extract token from URL parameter (used after login redirect)
* Removes the token from URL after storing it
*/
function bootstrapAuthTokenFromUrl() {
const url = new URL(window.location.href);
const token = url.searchParams.get("token");
if (!token) {
console.log("[Auth] No token param in URL");
return;
}
if (isTokenExpired(token)) {
console.warn("[Auth] Ignoring expired token from URL");
url.searchParams.delete("token");
window.history.replaceState(
{},
"",
`${url.pathname}${url.search}${url.hash}`,
);
return;
}
console.log("[Auth] Found token in URL, storing in localStorage");
localStorage.setItem(AUTH_TOKEN_KEY, token);
// Verify it was actually stored
if (!localStorage.getItem(AUTH_TOKEN_KEY)) {
console.error("[Auth] ERROR: Failed to store token in localStorage!");
return;
}
console.log("[Auth] Token stored successfully");
// Clean up URL
url.searchParams.delete("token");
window.history.replaceState(
{},
"",
`${url.pathname}${url.search}${url.hash}`,
);
}
/**
* Decode JWT payload (without verification - client-side only)
*/
function decodeJwtPayload(token) {
try {
const base64Url = token.split(".")[1];
const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
const jsonPayload = decodeURIComponent(
atob(base64)
.split("")
.map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2))
.join(""),
);
return JSON.parse(jsonPayload);
} catch (err) {
console.error("Failed to decode JWT:", err);
return null;
}
}
/**
* Get user info from token
*/
function getUserFromToken() {
const token = getAuthToken();
if (!token) return null;
return decodeJwtPayload(token);
}