I'm trying to have a Firebase cloud function that returns whether a user has permissions to content. I think it'll be clear how I want it to function based on the code.
Essentially, I'd like to check to make sure the user exists and the content exists before doing the compound query. This is because when I do the double query, it will return the 'this user does not have access to this content' even if the real issue is that the request has the incorrect contentId or userId.
function checkUser(userId) {
db.collection("users")
.where("userId", "==", userId)
.get()
.then(snapshot => {
if (snapshot.empty) {
return true;
} else {
return false;
}
})
.catch(err => console.error(err));
}
function checkContent(contentId) {
db.collection("content")
.doc(contentId)
.get()
.then(snapshot => {
if (!snapshot.exists) {
return true;
} else {
return false;
}
})
.catch(err => console.error(err));
}
app.get("/access", (req, res) => {
db.collection("access")
.where("userId", "==", req.body.userId)
.where("contentId", "==", req.body.contentId)
.get()
.then(snapshot => {
if (checkContent(req.body.contentId)) {
return res.status(404);
}
if (checkUser(req.body.userId)) {
return res.status(404);
}
if (snapshot.empty) {
return res.status(401).json({
message: "The requested user does not have access to this content"
});
} else {
return res.status(200).json({
message: "The requested user has access to this content"
});
}
})
.catch(err => {
console.error(err);
return res
.status(500)
.json({ message: "something went wrong on our end" });
});
});
I'm assuming this has something to do with the async code going on, but I'm not sure how to fix it.
Thanks for the help!
EDIT for @Chris G
const checkUser = async function(userId){
return db.collection("users")
.where("userId", "==", userId)
.get()
.then(snapshot => {
if (snapshot.empty) {
return true;
} else {
return false;
}
})
.catch(err => console.error(err));
}
const checkContent = async function(contentId){
return db.collection("access")
.where('contentId', '==', contentId)
.get()
.then(snapshot => {
if (snapshot.empty) {
return true;
} else {
return false;
}
})
.catch(err => console.error(err));
}
app.get("/access", (req, res) => {
db.collection("access")
.where("userId", "==", req.body.userId)
.where("contentId", "==", req.body.contentId)
.get()
.then(snapshot => {
const contentCheck = await checkContent(req.body.contentId);
const userCheck = await checkUser(req.body.userId);
.....