-
Notifications
You must be signed in to change notification settings - Fork 241
Expand file tree
/
Copy pathauth.js
More file actions
408 lines (353 loc) · 14 KB
/
auth.js
File metadata and controls
408 lines (353 loc) · 14 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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// auth.js — AgriTech Authentication System
// Migrated from localStorage to Firebase Auth + Firestore
// Maintains full backward-compatible API so register.js / login.js need minimal changes
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.11.0/firebase-app.js";
import {
getAuth,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut,
onAuthStateChanged,
} from "https://www.gstatic.com/firebasejs/10.11.0/firebase-auth.js";
import {
getFirestore,
doc,
setDoc,
getDoc,
updateDoc,
collection,
getDocs,
serverTimestamp,
} from "https://www.gstatic.com/firebasejs/10.11.0/firebase-firestore.js";
// ─────────────────────────────────────────────
// Role constants — single source of truth
// ─────────────────────────────────────────────
export const ROLES = {
FARMER: "farmer",
BUYER: "buyer",
EQUIPMENT: "equipment",
GROCERY: "grocery",
EXPERT: "expert",
ADMIN: "admin",
};
// Pages each role is allowed to access (filename without path)
const ROLE_HOME = {
farmer: "farmer.html",
buyer: "buyer.html",
equipment: "equipment.html",
grocery: "grocery.html",
expert: "expert.html",
admin: "admin.html",
};
// ─────────────────────────────────────────────
// Firebase initialisation (config fetched from Flask)
// ─────────────────────────────────────────────
let _app, _auth, _db;
async function getFirebaseInstances() {
if (_auth && _db) return { auth: _auth, db: _db };
const res = await fetch('http://localhost:5000/api/firebase-config');
if (!res.ok) throw new Error('Failed to fetch Firebase config');
const config = await res.json();
_app = initializeApp(config);
_auth = getAuth(_app);
_db = getFirestore(_app);
window._agriDb = _db;
return { auth: _auth, db: _db };
}
class AuthManager {
constructor() {
// currentUser is populated after observeAuth resolves
this.currentUser = null;
this._ready = false;
getFirebaseInstances().catch(console.error);
}
// ── Register ──────────────────────────────
async register({ role, fullname, email, password }) {
// Client-side validation (same as before)
if (!role || !fullname || !email || !password)
return { success: false, message: "All fields are required" };
if (!this._validateEmail(email))
return { success: false, message: "Please use a @gmail.com address" };
if (!/^[a-zA-Z\s]+$/.test(fullname))
return { success: false, message: "Full Name should only contain letters and spaces" };
const pwCheck = this._validatePassword(password);
if (!pwCheck.valid) return { success: false, message: pwCheck.message };
try {
const { auth, db } = await getFirebaseInstances();
const cred = await createUserWithEmailAndPassword(auth, email, password);
// Store profile + role in Firestore
await setDoc(doc(db, "users", cred.user.uid), {
fullname: fullname.trim(),
email: email.toLowerCase().trim(),
role,
createdAt: serverTimestamp(),
isActive: true,
isBanned: false,
});
const userData = { id: cred.user.uid, fullname, email, role };
this._setSession(userData);
return {
success: true,
message: "Account created successfully!",
user: userData,
};
} catch (err) {
return { success: false, message: this._friendlyError(err.code) };
}
}
// ── Login ─────────────────────────────────
async login(email, password) {
if (!email || !password)
return { success: false, message: "Email and password are required" };
if (!this._validateEmail(email))
return { success: false, message: "Please enter a valid email address" };
try {
const { auth, db } = await getFirebaseInstances();
const cred = await signInWithEmailAndPassword(auth, email, password);
// Fetch role and profile from Firestore
const snap = await getDoc(doc(db, "users", cred.user.uid));
if (!snap.exists())
return {
success: false,
message: "User profile not found. Please re-register.",
};
const data = snap.data();
if (data.isBanned)
return {
success: false,
message: "Your account has been suspended. Contact support.",
};
if (!data.isActive)
return {
success: false,
message: "Account is deactivated. Contact support.",
};
// Update lastLogin in Firestore
await updateDoc(doc(db, "users", cred.user.uid), {
lastLogin: serverTimestamp(),
});
const userData = {
id: cred.user.uid,
fullname: data.fullname,
email: data.email,
role: data.role,
};
this._setSession(userData);
return { success: true, message: "Login successful!", user: userData };
} catch (err) {
return { success: false, message: this._friendlyError(err.code) };
}
}
// ── Logout ────────────────────────────────
async logout() {
try {
const { auth } = await getFirebaseInstances();
await signOut(auth);
sessionStorage.removeItem("agritech_session");
this.currentUser = null;
window.location.href = "login.html";
return { success: true };
} catch (err) {
return { success: false, message: err.message };
}
}
// ── Check login state ─────────────────────
isLoggedIn() {
return this.currentUser !== null;
}
// ── Get current user ──────────────────────
getCurrentUser() {
if (this.currentUser) return this.currentUser;
try {
const s = sessionStorage.getItem("agritech_session");
if (s) {
this.currentUser = JSON.parse(s);
return this.currentUser;
}
} catch (_) {}
return null;
}
// ── Role helpers ──────────────────────────
getHomePageForRole(role) {
return ROLE_HOME[role] || "main.html";
}
// ── Admin: get all users ──────────────────
async getAllUsers() {
const { db } = await getFirebaseInstances();
const snap = await getDocs(collection(db, "users"));
return snap.docs.map((d) => ({ id: d.id, ...d.data() }));
}
// ── Admin: ban / unban ────────────────────
async setBanned(uid, isBanned) {
const { db } = await getFirebaseInstances();
await updateDoc(doc(db, "users", uid), { isBanned });
return { success: true };
}
// ── Admin: change role ────────────────────
async setRole(uid, newRole) {
const { db } = await getFirebaseInstances();
await updateDoc(doc(db, "users", uid), { role: newRole });
return { success: true };
}
// ─────────────────────────────────────────
// Private helpers
// ─────────────────────────────────────────
_setSession(user) {
this.currentUser = user;
sessionStorage.setItem("agritech_session", JSON.stringify(user));
}
_validateEmail(email) {
return /^[^\s@]+@gmail\.com$/.test(email);
}
_validatePassword(password) {
if (password.length < 8)
return {
valid: false,
message: "Password must be at least 8 characters long",
};
if (!/[a-z]/.test(password))
return {
valid: false,
message: "Password must contain at least one lowercase letter",
};
if (!/[A-Z]/.test(password))
return {
valid: false,
message: "Password must contain at least one uppercase letter",
};
if (!/\d/.test(password))
return {
valid: false,
message: "Password must contain at least one number",
};
return { valid: true };
}
_friendlyError(code) {
const map = {
"auth/email-already-in-use": "An account with this email already exists.",
"auth/invalid-email": "Please enter a valid email address.",
"auth/weak-password": "Password must be at least 6 characters.",
"auth/user-not-found": "Invalid email or password.",
"auth/wrong-password": "Invalid email or password.",
"auth/too-many-requests": "Too many attempts. Please try again later.",
"auth/network-request-failed": "Network error. Check your connection.",
"auth/invalid-credential": "Invalid email or password.",
};
return map[code] || "Something went wrong. Please try again.";
}
// ── UI helper (kept from old auth.js) ─────
updateAuthUI() {
const user = this.getCurrentUser();
const isLoggedIn = !!user;
const loginBtn = document.querySelector(".login-btn-desktop");
const registerBtn = document.querySelector(".register-btn-desktop");
const logoutBtn = document.querySelector(".logout-button");
const mobileLogin = document.querySelector(
'a[href="login.html"].mobile-link',
);
const mobileReg = document.querySelector(
'a[href="register.html"].mobile-link',
);
if (isLoggedIn) {
if (loginBtn) loginBtn.style.display = "none";
if (registerBtn) registerBtn.style.display = "none";
if (logoutBtn) {
logoutBtn.style.display = "inline-flex";
logoutBtn.onclick = (e) => {
e.preventDefault();
this.logout();
};
}
if (mobileLogin) mobileLogin.style.display = "none";
if (mobileReg) mobileReg.style.display = "none";
} else {
if (loginBtn) loginBtn.style.display = "inline-flex";
if (registerBtn) registerBtn.style.display = "inline-flex";
if (logoutBtn) logoutBtn.style.display = "none";
if (mobileLogin) mobileLogin.style.display = "flex";
if (mobileReg) mobileReg.style.display = "flex";
}
}
}
// ─────────────────────────────────────────────
// Singleton
// ─────────────────────────────────────────────
window.authManager = new AuthManager();
// ─────────────────────────────────────────────
// Page guards — same function names as before
// ─────────────────────────────────────────────
/**
* requireAuth([allowedRoles])
* Call on any protected page.
* Optionally pass roles that are allowed, e.g. requireAuth(["admin"])
*/
window.requireAuth = function (allowedRoles = []) {
const user = window.authManager.getCurrentUser();
if (!user) {
showAuthMessage("Please log in to access this page.", "error");
setTimeout(() => {
window.location.href = "login.html";
}, 1500);
return false;
}
if (allowedRoles.length > 0 && !allowedRoles.includes(user.role)) {
showAuthMessage("You don't have permission to view this page.", "error");
setTimeout(() => {
window.location.href = "unauthorized.html";
}, 1500);
return false;
}
return true;
};
/** Redirect already-logged-in users away from login/register pages */
window.redirectIfLoggedIn = function () {
const user = window.authManager.getCurrentUser();
if (user) {
window.location.href = window.authManager.getHomePageForRole(user.role);
}
};
// ─────────────────────────────────────────────
// showAuthMessage — kept exactly from old auth.js
// ─────────────────────────────────────────────
window.showAuthMessage = function (message, type = "info") {
const existing = document.querySelector(".auth-message");
if (existing) existing.remove();
const div = document.createElement("div");
div.className = `auth-message auth-message-${type}`;
div.innerHTML = `
<div class="auth-message-content">
<i class="fas fa-${type === "success" ? "check-circle" : type === "error" ? "exclamation-circle" : "info-circle"}"></i>
<span>${message}</span>
</div>`;
div.style.cssText = `
position:fixed; top:20px; right:20px; z-index:10000;
padding:15px 20px; border-radius:8px; color:white;
font-weight:500; box-shadow:0 4px 12px rgba(0,0,0,.15);
animation:slideInRight .3s ease-out; max-width:400px;`;
const colors = {
success: "linear-gradient(135deg,#4caf50,#45a049)",
error: "linear-gradient(135deg,#f44336,#e53935)",
info: "linear-gradient(135deg,#2196f3,#1976d2)",
};
div.style.background = colors[type] || colors.info;
document.body.appendChild(div);
setTimeout(() => {
if (div.parentNode) {
div.style.animation = "slideOutRight .3s ease-out";
setTimeout(() => div.remove(), 300);
}
}, 5000);
};
// CSS animations (same as before)
const s = document.createElement("style");
s.textContent = `
@keyframes slideInRight { from{opacity:0;transform:translateX(100%)} to{opacity:1;transform:translateX(0)} }
@keyframes slideOutRight { from{opacity:1;transform:translateX(0)} to{opacity:0;transform:translateX(100%)} }
.auth-message-content { display:flex; align-items:center; gap:10px; }
.auth-message-content i { font-size:1.2rem; }
`;
document.head.appendChild(s);
// Run UI update on every page load
document.addEventListener("DOMContentLoaded", () => {
window.authManager.updateAuthUI();
});