forked from Renu-code123/ExpenseFlow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth-integration.js
More file actions
301 lines (267 loc) · 8.24 KB
/
auth-integration.js
File metadata and controls
301 lines (267 loc) · 8.24 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// Authentication API Functions
const API_BASE_URL = 'http://localhost:3000/api';
let authToken = localStorage.getItem('authToken');
let currentUser = JSON.parse(localStorage.getItem('currentUser') || 'null');
// Auth API calls
async function register(userData) {
try {
const response = await fetch(`${API_BASE_URL}/auth/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(userData)
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error);
}
const data = await response.json();
authToken = data.token;
currentUser = data.user;
localStorage.setItem('authToken', authToken);
localStorage.setItem('currentUser', JSON.stringify(currentUser));
return data;
} catch (error) {
throw error;
}
}
async function login(credentials) {
try {
const response = await fetch(`${API_BASE_URL}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(credentials)
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error);
}
const data = await response.json();
authToken = data.token;
currentUser = data.user;
localStorage.setItem('authToken', authToken);
localStorage.setItem('currentUser', JSON.stringify(currentUser));
return data;
} catch (error) {
throw error;
}
}
function logout() {
authToken = null;
currentUser = null;
localStorage.removeItem('authToken');
localStorage.removeItem('currentUser');
localStorage.removeItem('transactions');
showAuthForm();
}
// Updated API functions with authentication
async function fetchExpenses() {
if (!authToken) throw new Error('Not authenticated');
try {
const response = await fetch(`${API_BASE_URL}/expenses`, {
headers: { 'Authorization': `Bearer ${authToken}` }
});
if (!response.ok) throw new Error('Failed to fetch expenses');
return await response.json();
} catch (error) {
if (error.message.includes('401')) {
logout();
throw new Error('Session expired');
}
throw error;
}
}
async function saveExpense(expense) {
if (!authToken) throw new Error('Not authenticated');
try {
const response = await fetch(`${API_BASE_URL}/expenses`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify(expense)
});
if (!response.ok) throw new Error('Failed to save expense');
return await response.json();
} catch (error) {
if (error.message.includes('401')) {
logout();
throw new Error('Session expired');
}
throw error;
}
}
async function deleteExpense(id) {
if (!authToken) throw new Error('Not authenticated');
try {
const response = await fetch(`${API_BASE_URL}/expenses/${id}`, {
method: 'DELETE',
headers: { 'Authorization': `Bearer ${authToken}` }
});
if (!response.ok) throw new Error('Failed to delete expense');
return await response.json();
} catch (error) {
if (error.message.includes('401')) {
logout();
throw new Error('Session expired');
}
throw error;
}
}
// UI Functions
function showAuthForm() {
document.body.innerHTML = `
<div class="auth-container">
<div class="auth-form">
<h2 id="auth-title">Login to ExpenseFlow</h2>
<form id="auth-form">
<div id="name-field" style="display: none;">
<input type="text" id="name" placeholder="Full Name" required>
</div>
<input type="email" id="email" placeholder="Email" required>
<input type="password" id="password" placeholder="Password" required>
<button type="submit" id="auth-submit">Login</button>
</form>
<p>
<span id="auth-switch-text">Don't have an account?</span>
<a href="#" id="auth-switch">Register</a>
</p>
</div>
</div>
<style>
.auth-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.auth-form {
background: white;
padding: 2rem;
border-radius: 10px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
width: 100%;
max-width: 400px;
}
.auth-form h2 {
text-align: center;
margin-bottom: 1.5rem;
color: #333;
}
.auth-form input {
width: 100%;
padding: 12px;
margin-bottom: 1rem;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 16px;
}
.auth-form button {
width: 100%;
padding: 12px;
background: #667eea;
color: white;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
.auth-form button:hover {
background: #5a6fd8;
}
.auth-form p {
text-align: center;
margin-top: 1rem;
}
.auth-form a {
color: #667eea;
text-decoration: none;
}
</style>
`;
let isLogin = true;
document.getElementById('auth-switch').addEventListener('click', (e) => {
e.preventDefault();
isLogin = !isLogin;
const title = document.getElementById('auth-title');
const nameField = document.getElementById('name-field');
const submitBtn = document.getElementById('auth-submit');
const switchText = document.getElementById('auth-switch-text');
const switchLink = document.getElementById('auth-switch');
if (isLogin) {
title.textContent = 'Login to ExpenseFlow';
nameField.style.display = 'none';
submitBtn.textContent = 'Login';
switchText.textContent = "Don't have an account?";
switchLink.textContent = 'Register';
} else {
title.textContent = 'Register for ExpenseFlow';
nameField.style.display = 'block';
submitBtn.textContent = 'Register';
switchText.textContent = 'Already have an account?';
switchLink.textContent = 'Login';
}
});
document.getElementById('auth-form').addEventListener('submit', async (e) => {
e.preventDefault();
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
const name = document.getElementById('name').value;
try {
if (isLogin) {
await login({ email, password });
} else {
await register({ name, email, password });
}
showMainApp();
showNotification(`Welcome ${currentUser.name}!`, 'success');
} catch (error) {
showNotification(error.message, 'error');
}
});
}
function showMainApp() {
// Restore original HTML structure
location.reload();
}
function showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.className = `notification notification-${type}`;
notification.textContent = message;
Object.assign(notification.style, {
position: 'fixed',
top: '20px',
right: '20px',
padding: '1rem',
borderRadius: '5px',
color: 'white',
background: type === 'success' ? '#4CAF50' : type === 'error' ? '#f44336' : '#2196F3',
zIndex: '10000'
});
document.body.appendChild(notification);
setTimeout(() => notification.remove(), 3000);
}
// Initialize authentication
function initAuth() {
if (!authToken || !currentUser) {
showAuthForm();
return false;
}
// Add logout button to existing UI
const header = document.querySelector('header') || document.querySelector('.header');
if (header) {
const logoutBtn = document.createElement('button');
logoutBtn.textContent = `Logout (${currentUser.name})`;
logoutBtn.onclick = logout;
logoutBtn.style.cssText = 'position: absolute; top: 10px; right: 10px; padding: 8px 16px; background: #f44336; color: white; border: none; border-radius: 5px; cursor: pointer;';
header.appendChild(logoutBtn);
}
return true;
}
// Check authentication on page load
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initAuth);
} else {
initAuth();
}