import { auth, db, admin } from "../config/firebase.js"; import { isValidDepartment, isValidRole, ROLES, DEPARTMENT_CODES } from "../config/constants.js"; const USERS_COLLECTION = "users"; const DEFAULT_ROLE = "student"; const parseAge = (value) => { const age = Number(value); if (!Number.isInteger(age) || age < 1 || age > 120) { throw new Error("Age must be a valid number between 1 and 120"); } return age; }; const normalizeText = (value) => String(value || "").trim(); const requireValue = (value, label) => { const normalized = normalizeText(value); if (!normalized) { throw new Error(`${label} is required`); } return normalized; }; const sanitizeProfile = (profile) => ({ uid: profile.uid, fullName: profile.fullName, sex: profile.sex, age: profile.age, collegeDepartment: profile.collegeDepartment, // Accounts created before roles existed have no role field. Treat them as students // rather than failing, so existing logins keep working. role: profile.role || DEFAULT_ROLE, email: profile.email, createdAt: profile.createdAt, updatedAt: profile.updatedAt, }); const parseRole = (value) => { const role = String(value || DEFAULT_ROLE).trim().toLowerCase(); if (!isValidRole(role)) { throw new Error(`Role must be one of: ${ROLES.join(", ")}`); } return role; }; const parseDepartment = (value) => { const code = String(value || "").trim().toUpperCase(); if (!isValidDepartment(code)) { throw new Error(`College/Department must be one of: ${DEPARTMENT_CODES.join(", ")}`); } return code; }; const getFirebaseApiKey = () => { const apiKey = process.env.FIREBASE_WEB_API_KEY; if (!apiKey) { throw new Error("FIREBASE_WEB_API_KEY is not configured"); } return apiKey; }; const updatePasswordWithIdToken = async (idToken, newPassword) => { const apiKey = getFirebaseApiKey(); const response = await fetch( `https://identitytoolkit.googleapis.com/v1/accounts:update?key=${apiKey}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ idToken, password: newPassword, returnSecureToken: false, }), } ); const payload = await response.json(); if (!response.ok) { const code = payload?.error?.message || "PASSWORD_UPDATE_FAILED"; throw new Error(`Failed to change password: ${code}`); } }; /** * Exchange a refresh token for a fresh ID token. Firebase ID tokens last one hour; without * this, a session that looks logged in starts failing every request after that hour. * Firebase refuses the exchange for deleted or disabled accounts, which is what signs * such users out. */ export const refreshSession = async ({ refreshToken }) => { const token = String(refreshToken || "").trim(); if (!token) throw new Error("Missing refresh token"); const response = await fetch( `https://securetoken.googleapis.com/v1/token?key=${getFirebaseApiKey()}`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: token }), } ); const payload = await response.json().catch(() => ({})); if (!response.ok) { const code = payload?.error?.message || "REFRESH_FAILED"; if (code === "USER_DISABLED") throw new Error("This account has been disabled"); if (code === "USER_NOT_FOUND") throw new Error("This account no longer exists"); throw new Error("Your session has expired. Please log in again."); } return { idToken: payload.id_token, refreshToken: payload.refresh_token, expiresIn: Number(payload.expires_in || 3600), }; }; const signInWithEmailPassword = async (email, password) => { const apiKey = getFirebaseApiKey(); const response = await fetch( `https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${apiKey}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, password, returnSecureToken: true, }), } ); const payload = await response.json(); if (!response.ok) { const code = payload?.error?.message || "LOGIN_FAILED"; if (code === "INVALID_LOGIN_CREDENTIALS" || code === "EMAIL_NOT_FOUND" || code === "INVALID_PASSWORD") { throw new Error("Invalid email or password"); } throw new Error(`Firebase login failed: ${code}`); } return payload; }; export const createAccount = async ({ fullName, sex, age, collegeDepartment, email, password, role }) => { const cleanFullName = requireValue(fullName, "Full name"); const cleanSex = requireValue(sex, "Sex"); const cleanCollegeDepartment = parseDepartment(collegeDepartment); const cleanRole = parseRole(role); const cleanEmail = requireValue(email, "Email").toLowerCase(); const cleanPassword = String(password || ""); if (cleanPassword.length < 6) { throw new Error("Password must be at least 6 characters"); } const cleanAge = parseAge(age); let userRecord; try { userRecord = await auth.createUser({ email: cleanEmail, password: cleanPassword, displayName: cleanFullName, }); const now = admin.firestore.FieldValue.serverTimestamp(); const userProfile = { uid: userRecord.uid, fullName: cleanFullName, sex: cleanSex, age: cleanAge, collegeDepartment: cleanCollegeDepartment, role: cleanRole, email: cleanEmail, createdAt: now, updatedAt: now, }; await db.collection(USERS_COLLECTION).doc(userRecord.uid).set(userProfile); // The role also goes into the Firebase ID token as a custom claim, so requireRole // can authorise a request without a Firestore read on every call. await auth.setCustomUserClaims(userRecord.uid, { role: cleanRole }); const login = await signInWithEmailPassword(cleanEmail, cleanPassword); const saved = await db.collection(USERS_COLLECTION).doc(userRecord.uid).get(); return { user: sanitizeProfile(saved.data()), token: { idToken: login.idToken, refreshToken: login.refreshToken, expiresIn: Number(login.expiresIn || 3600), }, }; } catch (error) { if (userRecord?.uid) { await auth.deleteUser(userRecord.uid).catch(() => null); await db.collection(USERS_COLLECTION).doc(userRecord.uid).delete().catch(() => null); } if (error?.code === "auth/email-already-exists") { throw new Error("Email is already registered"); } throw error; } }; export const loginAccount = async ({ email, password, role }) => { const cleanEmail = requireValue(email, "Email").toLowerCase(); const cleanPassword = String(password || ""); if (!cleanPassword) { throw new Error("Password is required"); } const login = await signInWithEmailPassword(cleanEmail, cleanPassword); const uid = login.localId; const doc = await db.collection(USERS_COLLECTION).doc(uid).get(); if (!doc.exists) { throw new Error("User profile not found"); } const profile = sanitizeProfile(doc.data()); // The login form asks which role you are signing in as. Enforce it here rather than in // the browser: a student picking "Teacher" must be refused with no token issued, not // merely shown a different dashboard. The check is skipped when the client sends no // role, so older clients keep working. const wanted = String(role || "").trim().toLowerCase(); if (wanted && wanted !== profile.role) { const actual = profile.role === "teacher" ? "Teacher" : "Student"; const chosen = wanted === "teacher" ? "Teacher" : "Student"; throw new Error( `This account is registered as a ${actual}. You selected ${chosen} - switch to ${actual} and try again.` ); } return { user: profile, token: { idToken: login.idToken, refreshToken: login.refreshToken, expiresIn: Number(login.expiresIn || 3600), }, }; }; export const getAuthStats = async () => { const aggregate = await db.collection(USERS_COLLECTION).count().get(); const totalUsers = aggregate.data().count || 0; return { totalUsers }; }; export const getMyProfile = async ({ userUid }) => { const doc = await db.collection(USERS_COLLECTION).doc(userUid).get(); if (!doc.exists) { throw new Error("User profile not found"); } return sanitizeProfile(doc.data()); }; export const updateMyProfile = async ({ userUid, fullName }) => { const cleanFullName = requireValue(fullName, "Full name"); await db.collection(USERS_COLLECTION).doc(userUid).set( { fullName: cleanFullName, updatedAt: admin.firestore.FieldValue.serverTimestamp(), }, { merge: true } ); await auth.updateUser(userUid, { displayName: cleanFullName }).catch(() => null); return getMyProfile({ userUid }); }; export const changeMyPassword = async ({ userUid, currentPassword, newPassword }) => { const cleanCurrentPassword = String(currentPassword || ""); const cleanNewPassword = String(newPassword || ""); if (!cleanCurrentPassword) { throw new Error("Current password is required"); } if (cleanNewPassword.length < 6) { throw new Error("New password must be at least 6 characters"); } if (cleanCurrentPassword === cleanNewPassword) { throw new Error("New password must be different from current password"); } const profile = await getMyProfile({ userUid }); const login = await signInWithEmailPassword(profile.email, cleanCurrentPassword); await updatePasswordWithIdToken(login.idToken, cleanNewPassword); return { message: "Password changed successfully" }; };