Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 0 additions & 69 deletions firestore-debug.log

This file was deleted.

7 changes: 4 additions & 3 deletions functions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@
},
"main": "lib/index.js",
"dependencies": {
"firebase-admin": "^12.6.0",
"firebase-functions": "^6.0.1",
"resend": "^6.9.1"
"firebase-admin": "^13.7.0",
"firebase-functions": "^7.2.3",
"googleapis": "^171.4.0",
"resend": "^6.10.0"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.12.0",
Expand Down
129 changes: 129 additions & 0 deletions functions/src/index.ts

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

connectCalendar returns success even when no refresh_token is received, so it ends up marking the calendar as connected without actually storing credentials. Seems to be causing downstream errors with fetchCalendar

Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
} from "firebase-functions/v2/https";
import { defineSecret } from "firebase-functions/params";
import { Resend } from "resend";
import { google } from "googleapis";
import * as admin from "firebase-admin";

// Define the secret
const resendApiKey = defineSecret("RESEND_API_KEY");
Expand Down Expand Up @@ -63,3 +65,130 @@ export const sendEmail = onCall<EmailData>(
}
},
);

const googleClientSecret = defineSecret("GOOGLE_CLIENT_SECRET");
const googleClientId = "83459975838-fqj9tuogpa17urv03jsaos2nbjfde9ne.apps.googleusercontent.com";

if (!admin.apps.length) {
admin.initializeApp();
}

export const connectCalendar = onCall({
secrets: [googleClientSecret],
cors: ["http://localhost:3000", "https://studybuddy-392c7.web.app", "https://studybuddy-392c7.firebaseapp.com"],
}, async (request) => {
if (!request.auth) {
throw new HttpsError("unauthenticated", "User must be logged in.");
}

const { code } = request.data;
const uid = request.auth.uid;

const oauth2Client = new google.auth.OAuth2(
googleClientId,
googleClientSecret.value(),
"postmessage"
);

try {
const { tokens } = await oauth2Client.getToken(code);

if (tokens.refresh_token) {
await admin.firestore().collection("users").doc(uid).set({
calendarConnected: true,
googleRefreshToken: tokens.refresh_token,
updatedAt: new Date().toISOString(), // <-- added ()
}, { merge: true });
}

return { success: true };
} catch (error) {
console.error("Google Token Exchange Error:", error);
throw new HttpsError("internal", "Failed to connect Google Calendar");
}
});

export const fetchCalendar = onCall({
secrets: [googleClientSecret],
cors: ["http://localhost:3000", "https://studybuddy-392c7.web.app", "https://studybuddy-392c7.firebaseapp.com"],
}, async (request) => {
if (!request.auth) {
throw new HttpsError("unauthenticated", "User must be logged in.");
}

const uid = request.auth.uid;
const db = admin.firestore();

try {
const userDoc = await db.collection("users").doc(uid).get();
const refreshToken = userDoc.data()?.googleRefreshToken;

if (!refreshToken) {
throw new HttpsError("not-found", "No calendar token found. Please reconnect.");
}

const oauth2Client = new google.auth.OAuth2(
googleClientId,
googleClientSecret.value(),
"postmessage"
);

oauth2Client.setCredentials({ refresh_token: refreshToken });
const calendar = google.calendar({ version: "v3", auth: oauth2Client });
const response = await calendar.calendarList.list();

return { success: true, calendars: response.data.items || [] };
} catch (error: any) {
console.error("Error fetching calendar:", error);

if (error.message?.includes("invalid_grant")) {
await db.collection("users").doc(uid).update({
googleRefreshToken: admin.firestore.FieldValue.delete(),
calendarConnected: false,
});
throw new HttpsError("unauthenticated", "Calendar access revoked. Please reconnect.");
}

if (error instanceof HttpsError) throw error;
throw new HttpsError("internal", "Failed to fetch calendars");
}
});

export const fetchEvents = onCall({
secrets: [googleClientSecret],
}, async (request) => {
if (!request.auth) {
throw new HttpsError("unauthenticated", "User must be logged in.");
}

const uid = request.auth.uid;
const { calendarId, timeMin, timeMax, timezone } = request.data;
const db = admin.firestore();

const userDoc = await db.collection("users").doc(uid).get();
const refreshToken = userDoc.data()?.googleRefreshToken;

if (!refreshToken) {
throw new HttpsError("not-found", "No calendar token found.");
}

const oauth2Client = new google.auth.OAuth2(
googleClientId,
googleClientSecret.value(),
"postmessage"
);

oauth2Client.setCredentials({ refresh_token: refreshToken });
const calendar = google.calendar({ version: "v3", auth: oauth2Client });

const response = await calendar.events.list({
calendarId,
timeMin,
timeMax,
singleEvents: true,
orderBy: "startTime",
timeZone: timezone,
});

return { success: true, events: response.data.items || [] };
});
2 changes: 1 addition & 1 deletion src/backend/firebase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,5 @@ const db = getFirestore(app);
export const SCOPES = 'https://www.googleapis.com/auth/calendar.readonly';
const googleProvider = new GoogleAuthProvider();

export { auth, db, analytics, googleProvider };
export { auth, db, analytics, googleProvider, app };

10 changes: 10 additions & 0 deletions src/backend/functions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { getFunctions, connectFunctionsEmulator } from 'firebase/functions';
import { app } from './firebase';

const functions = getFunctions(app);

if (window.location.hostname === 'localhost') {
connectFunctionsEmulator(functions, 'localhost', 5001);
}

export { functions };
Loading