Last active
April 23, 2021 07:09
-
-
Save acoyfellow/e8888b4b5eb0dc52e65ea1e21ad5d525 to your computer and use it in GitHub Desktop.
SvelteKit /src/hooks.js with cookie + firebase-admin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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