Skip to content

Instantly share code, notes, and snippets.

@acoyfellow
Last active April 23, 2021 07:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acoyfellow/e8888b4b5eb0dc52e65ea1e21ad5d525 to your computer and use it in GitHub Desktop.
Save acoyfellow/e8888b4b5eb0dc52e65ea1e21ad5d525 to your computer and use it in GitHub Desktop.
SvelteKit /src/hooks.js with cookie + firebase-admin
import * as cookie from 'cookie';
import { firebase } from "$services/server/firebase";
const firestore = firebase.firestore();
export async function getContext({ headers }) {
let user = null;
try {
const cookies = cookie.parse(headers.cookie || "");
const sessionId = cookies["__session"];
if (!sessionId) {
return {
context: { user }
}
};
const sessDoc = firebase.firestore().collection(`sessions`).doc(sessionId);
const session = (await sessDoc.get()).data();
if (!session) {
return {
context: { user }
}
};
user = JSON.parse(session.sess);
const { uid } = user;
const userSnap = await firestore
.collection('users')
.doc(uid)
.get();
const userData = userSnap.data();
return {
context: { user, userData }
}
} catch (e) {
console.error('hooks.js', e);
return {
context: { user }
}
};
};
export async function getSession({ context }) {
return context;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment