Skip to content

Instantly share code, notes, and snippets.

@acoyfellow

acoyfellow/hooks.js

Last active Apr 23, 2021
Embed
What would you like to do?
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