Skip to content
Merged
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
3 changes: 2 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ Firebase integration.
- `server.ts` - Firebase Admin SDK initialization (supports both `import.meta.env` and `process.env`)
- `client.ts` - Client-side Firebase SDK initialization
- `database.ts` - Firestore operations (save/export results)
- `session.ts` - Set and verify the `__session` cookie

### `/src/components/survey/`
Survey form components.
Expand All @@ -55,7 +56,7 @@ Astro pages (hybrid rendering).
- `home.astro` - Landing page
- `before-start.astro` - Pre-survey CAPTCHA and session initialization
- `survey.astro` - Survey form (protected by session check)
- `thanks.astro` - Post-survey thank you page with social sharing
- `thanks.astro` - Post-survey thank you page with social sharing (protected by session check)
- `{year}.astro` - Results pages for each survey year
- `playground.astro` - Interactive data exploration with filters

Expand Down
29 changes: 7 additions & 22 deletions src/actions/init-session.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
/* eslint-disable no-console */
import { ActionError, defineAction } from "astro:actions";
import { z } from "astro:schema";
import { getAuth } from "firebase-admin/auth";
import { passesCaptcha } from "@/lib/captcha";
import { initUserSubmission } from "@/lib/firebase/database";
import { getActiveApp } from "@/lib/firebase/server";
import { auth } from "@/lib/firebase/server";
import { setSessionCookie } from "@/lib/firebase/session";

export const initSession = defineAction({
accept: "json",
Expand All @@ -13,7 +13,6 @@ export const initSession = defineAction({
captchaToken: z.string().optional()
}),
handler: async ({ idToken, captchaToken }, { cookies }) => {
const auth = getAuth(getActiveApp());
if (!idToken) {
throw new ActionError({
code: "UNAUTHORIZED",
Expand All @@ -28,15 +27,10 @@ export const initSession = defineAction({
});
}

/* Verify id token and save user to database */
try {
const decodedToken = await auth.verifyIdToken(idToken);
const user = await auth.getUser(decodedToken.uid);
if (!user) {
throw new ActionError({
code: "UNAUTHORIZED",
message: "User not found"
});
}
await initUserSubmission(user);
console.log("user session created");
}
Expand All @@ -49,25 +43,16 @@ export const initSession = defineAction({
}

try {
// Create and set session cookie
const fiveDays = 60 * 60 * 24 * 5 * 1000;
const sessionCookie = await auth.createSessionCookie(idToken, {
expiresIn: fiveDays
});

// set session cookie
cookies.set("__session", sessionCookie, {
path: "/"
});
await setSessionCookie(cookies, idToken);
return {
success: true
};
}
catch (error) {
console.error("Error signing in:", error);
console.error("Error creating session cookie:", error);
throw new ActionError({
code: "UNAUTHORIZED",
message: "Error signing in"
code: "INTERNAL_SERVER_ERROR",
message: "Error creating session"
});
}
}
Expand Down
28 changes: 7 additions & 21 deletions src/actions/submit-answers.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
/* eslint-disable no-console */
import { ActionError, defineAction } from "astro:actions";
import { z } from "astro:schema";
import { getAuth } from "firebase-admin/auth";
import { saveAnswers } from "@/lib/firebase/database";
import { getActiveApp } from "@/lib/firebase/server";
import { getSessionUid } from "@/lib/firebase/session";
import { findInvalidAnswer } from "@/lib/validators/answers";

export const submitAnswers = defineAction({
Expand All @@ -21,35 +20,22 @@ export const submitAnswers = defineAction({
})
}),
handler: async ({ answers }, { cookies }) => {
const auth = getAuth(getActiveApp());
/* Verify Session */
const sessionCookie = cookies.get("__session")?.value;
if (!sessionCookie) {
const uid = await getSessionUid(cookies);
if (!uid) {
throw new ActionError({
code: "UNAUTHORIZED",
message: "No session is active, please initialize a session first"
message: "No valid session, please initialize a session first"
});
}
/* Get User */
try {
const decodedCookie = await auth.verifySessionCookie(sessionCookie);
const user = await auth.getUser(decodedCookie.uid);
if (!user) {
throw new ActionError({
code: "UNAUTHORIZED",
message:
"Can't find user from session, please initialize a session first"
});
}
/* Save answers to database */
await saveAnswers(user.uid, answers);
await saveAnswers(uid, answers);
console.log("answers saved");
}
catch (error) {
console.error("Error token or saving answers:", error);
console.error("Error saving answers:", error);
throw new ActionError({
code: "INTERNAL_SERVER_ERROR",
message: "Error token or saving answers"
message: "Error saving answers"
});
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/lib/firebase/server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { ServiceAccount } from "firebase-admin";
import { cert, getApps, initializeApp } from "firebase-admin/app";
import { getAuth } from "firebase-admin/auth";

const activeApps = getApps();
let serviceAccount = {};
Expand Down Expand Up @@ -48,3 +49,4 @@ function initApp() {

export const app = activeApps.length === 0 ? initApp() : activeApps[0];
export const getActiveApp = () => app;
export const auth = getAuth(app);
33 changes: 33 additions & 0 deletions src/lib/firebase/session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { AstroCookies } from "astro";
import { auth } from "./server";

const SESSION_COOKIE = "__session";
const SESSION_MAX_AGE_MS = 60 * 60 * 24 * 5 * 1000;

export async function setSessionCookie(cookies: AstroCookies, idToken: string) {
const sessionCookie = await auth.createSessionCookie(idToken, {
expiresIn: SESSION_MAX_AGE_MS
});
cookies.set(SESSION_COOKIE, sessionCookie, {
path: "/",
maxAge: SESSION_MAX_AGE_MS / 1000,
httpOnly: true,
secure: import.meta.env.PROD,
sameSite: "lax"
});
}

// firebase-admin throws on expired/tampered/revoked cookies and deleted/disabled users; treat all as "no session"
export async function getSessionUid(cookies: AstroCookies) {
const sessionCookie = cookies.get(SESSION_COOKIE)?.value;
if (!sessionCookie)
return null;
try {
const { uid } = await auth.verifySessionCookie(sessionCookie, true);
return uid;
}
catch (error) {
console.warn("Invalid session:", error);
return null;
}
}
18 changes: 2 additions & 16 deletions src/pages/survey.astro
Original file line number Diff line number Diff line change
@@ -1,25 +1,11 @@
---
import { getAuth } from "firebase-admin/auth";
import BaseLayout from "@/components/layout.astro";
import SurveyForm from "@/components/survey/index.astro";
import { getActiveApp } from "@/lib/firebase/server";
import { getSessionUid } from "@/lib/firebase/session";

export const prerender = false;

const auth = getAuth(getActiveApp());

/* Check current session */
if (!Astro.cookies.has("__session")) {
return Astro.redirect("/before-start");
}
const sessionCookie = Astro.cookies.get("__session")?.value;
if (!sessionCookie) {
return Astro.redirect("/before-start");
}
const decodedCookie = await auth.verifySessionCookie(sessionCookie);
const user = await auth.getUser(decodedCookie.uid);

if (!user) {
if (!(await getSessionUid(Astro.cookies))) {
return Astro.redirect("/before-start");
}
---
Expand Down
18 changes: 2 additions & 16 deletions src/pages/thanks.astro
Original file line number Diff line number Diff line change
@@ -1,28 +1,14 @@
---
import { Image } from "astro:assets";
import { getAuth } from "firebase-admin/auth";
import tarbouch from "@/assets/tarbouch.png"; // Image is 1600x900

import BaseLayout from "@/components/layout.astro";
import SocialMediaCard from "@/components/social-media-card.astro";
import { getActiveApp } from "@/lib/firebase/server";
import { getSessionUid } from "@/lib/firebase/session";

export const prerender = false;

const auth = getAuth(getActiveApp());

/* Check current session */
if (!Astro.cookies.has("__session")) {
return Astro.redirect("/before-start");
}
const sessionCookie = Astro.cookies.get("__session")?.value;
if (!sessionCookie) {
return Astro.redirect("/before-start");
}
const decodedCookie = await auth.verifySessionCookie(sessionCookie);
const user = await auth.getUser(decodedCookie.uid);

if (!user) {
if (!(await getSessionUid(Astro.cookies))) {
return Astro.redirect("/before-start");
}

Expand Down
Loading