Skip to content

Instantly share code, notes, and snippets.

// this function will be used to compose further middlewares
const restaurantEmployeeOnly = (restaurantIdSupplier, groupName) => async (req, res, next) => {
// using such a supplier can be useful if the restaurant id can occur on different places within the request
// for example within the payload of a POST request (req.body) or as a query param (req.query)
// maybe you want to use a default value for the param.
const restaurantId = restaurantIdSupplier(req);
const {user} = req;
if (!restaurantId || !user) {
res.status(403).send("Unauthorized");
const restaurantOwnerOnlyMiddleware = async (req, res, next) => {
const {restaurantId} = req.params;
const user = req.user;
const restaurantDoc = await db.collection("restaurants").doc(restaurantId).get(); // db-read
const restaurant = restaurantDoc.data();
if (restaurant.owner !== req.user.uid) {
res.status(403).send("Unauthorized");
return;
const restaurantOwnerOnlyMiddleware = async (req, res, next) => {
const {restaurantId} = req.params;
const user = req.user;
const restaurantDoc = await db.collection("restaurants").doc(restaurantId).get(); // db-read
const {owner} = restaurantDoc.data();
if (owner !== req.user.uid) {
res.status(403).send("Unauthorized");
return;
app.delete("/:restaurantId", [onlyLoggedInUsers, restaurantOwnerOnlyMiddleware], (req, res) => {
// an user which doesn't fulfill the preconditions from the middlewares above, will not reach the code below
// do your delete operation here
res.send();
});
// you can simple re-use the implementation above
app.put("/:restaurantId", [onlyLoggedInUsers, restaurantOwnerOnlyMiddleware], (req, res) => {
// do your put operation here
res.send();
const restaurantOwnerOnlyMiddleware = (req, res, next) => {
const {restaurantId} = req.params; // in this case, the id is part of the path
const user = req.user; // available if you're using Google Firebase Authentication Middleware
const hasPermission = (id, user) => true; // do your checks here instead
if (!hasPermission(restaurantId, user)) {
res.status(403).send("Unauthorized");
return;
}