Skip to content

Instantly share code, notes, and snippets.

@rootasjey
Created October 15, 2022 05:04
Show Gist options
  • Save rootasjey/6b8594cd4da10822c5029a6997f1b8c6 to your computer and use it in GitHub Desktop.
Save rootasjey/6b8594cd4da10822c5029a6997f1b8c6 to your computer and use it in GitHub Desktop.
An helper function to check user access control when fetching or saving a new file (markdown post) to Firebase Storage using Cloud Function.
/**
* Tells if an user can have access to a project.
* @param {object} params - An object containing a project's id and jwt;
*/
async function checkAccessControl(params: CheckProjectAccessControlParams) {
const {projectId, jwt} = params;
try {
const projectSnapshot = await firestore
.collection("projects")
.doc(projectId)
.get();
if (!projectSnapshot.exists) {
throw new functions.https.HttpsError(
"not-found",
"The project asked does not exist anymore." +
" You may be asking a deleted project.",
);
}
const projectData = projectSnapshot.data();
if (!projectData) {
throw new functions.https.HttpsError(
"data-loss",
"The project data is null, which is weird. Please contact us.",
);
}
if (!projectData.published) {
if (!jwt) {
throw new functions.https.HttpsError(
"unauthenticated",
"The project asked is a draft and " +
"you do not have the right to get its content.",
);
}
const decodedToken = await auth.verifyIdToken(jwt, true);
let hasAuthorAccess = false;
if (projectData.author.id === decodedToken.uid) {
hasAuthorAccess = true;
} else if (projectData.coauthors.indexOf(decodedToken.uid) > -1) {
hasAuthorAccess = true;
}
if (!hasAuthorAccess) {
throw new functions.https.HttpsError(
"permission-denied",
"You do not have the right to view this project's content.",
);
}
} else if (projectData.restrictedTo.premium) {
// TODO: Handle premium users.
}
} catch (error) {
throw new functions.https.HttpsError(
"internal",
`There was an internal error while retrieving the project content.
Your JWT may be outdated.`,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment