Created
October 15, 2022 05:04
-
-
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.
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
/** | |
* 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