forked from Kuldeeep18/LeadOrbit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
152 lines (131 loc) · 4.7 KB
/
Copy pathapi.js
File metadata and controls
152 lines (131 loc) · 4.7 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
const storedApiBase = localStorage.getItem('api_base_url');
const isLocalhost = ['localhost', '127.0.0.1'].includes(window.location.hostname);
const defaultApiBase = isLocalhost
? 'http://127.0.0.1:8000/api/v1'
: 'https://leadorbit.onrender.com/api/v1';
const API_BASE = (storedApiBase || defaultApiBase).replace(/\/$/, '');
export const setTokens = (access, refresh) => {
localStorage.setItem('access_token', access);
localStorage.setItem('refresh_token', refresh);
};
export const getAccessToken = () => localStorage.getItem('access_token');
export const getRefreshToken = () => localStorage.getItem('refresh_token');
export const clearTokens = () => {
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
};
let refreshPromise = null;
const redirectToLogin = () => {
clearTokens();
window.location.href = '/login.html';
};
export const refreshAccessToken = async () => {
const refresh = getRefreshToken();
if (!refresh) {
throw new Error('Missing refresh token');
}
if (!refreshPromise) {
refreshPromise = fetch(`${API_BASE}/token/refresh/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh }),
})
.then(async (res) => {
if (!res.ok) {
throw new Error('Refresh failed');
}
const data = await res.json();
if (!data.access) {
throw new Error('Refresh response missing access token');
}
localStorage.setItem('access_token', data.access);
if (data.refresh) {
localStorage.setItem('refresh_token', data.refresh);
}
return data.access;
})
.finally(() => {
refreshPromise = null;
});
}
return refreshPromise;
};
const buildRequestHeaders = (options, token = getAccessToken()) => {
const headers = {
'Content-Type': 'application/json',
...options.headers,
};
if (token) {
headers['Authorization'] = `Bearer ${token}`;
} else {
delete headers['Authorization'];
}
// Don't set content-type for FormData (like CSV uploads)
if (options.body instanceof FormData) {
delete headers['Content-Type'];
}
return headers;
};
const sendApiRequest = async (endpoint, options = {}, token = getAccessToken()) => {
const headers = buildRequestHeaders(options, token);
const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : 20000;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
try {
return await fetch(`${API_BASE}${endpoint}`, {
...options,
headers,
signal: options.signal || controller.signal,
});
} catch (error) {
if (error.name === 'AbortError') {
throw new Error('Request timed out. Check if the backend is running on port 8000.');
}
if (error instanceof TypeError) {
throw new Error(`Cannot reach backend API at ${API_BASE}. Check that the backend server is running.`);
}
throw error;
} finally {
clearTimeout(timeoutId);
}
};
export const fetchWithAuth = async (endpoint, options = {}) => {
const token = getAccessToken();
let response = await sendApiRequest(endpoint, options, token);
if (response.status === 401) {
try {
const refreshedToken = await refreshAccessToken();
response = await sendApiRequest(endpoint, options, refreshedToken);
} catch {
redirectToLogin();
throw new Error("Unauthorized");
}
if (response.status === 401) {
redirectToLogin();
throw new Error("Unauthorized");
}
}
return response;
};
export const login = async (email, password) => {
const res = await fetch(`${API_BASE}/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
if (!res.ok) throw new Error("Login failed");
const data = await res.json();
setTokens(data.access, data.refresh);
return data;
};
export const register = async (userData) => {
const res = await fetch(`${API_BASE}/auth/register/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(userData)
});
if (!res.ok) throw new Error("Registration failed");
const data = await res.json();
setTokens(data.access, data.refresh);
return data;
};