You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为70家连锁餐厅内网创建Express JS路由实现门店专属MongoDB数据访问?

如何在Express.js中实现门店专属数据的路由访问控制

Nice question—this is a super common access control scenario for multi-location restaurant chains, and there are some straightforward, secure patterns to implement this in Express.js. Let’s break this down step by step:

1. 基础准备:给数据和门店绑定唯一标识

First off, you need a way to tie every piece of store-specific data to its respective location:

  • Assign a unique storeId to each of your 70 locations (e.g., store_001, store_005, store_070). Store this ID in a dedicated stores collection in MongoDB, along with other门店 details.
  • Add a storeId field to every document in your store-specific collections (like announcements, pendingOrders). For example, a store announcement document might look like:
{
  _id: ObjectId("60d21b4667d0d8992e610c85"),
  storeId: "store_005",
  title: "本周食材供应调整通知",
  content: "明日起生菜替换为有机生菜,请提前告知后厨",
  createdAt: ISODate("2024-05-20T12:00:00Z")
}

2. 门店身份认证:确保请求来自合法门店

Since your store screens are fixed devices, API key authentication is the simplest, most maintainable approach (no need for user-facing login flows):

  • Generate a unique apiKey for each store, and link it to the store’s storeId in your stores collection. Store these keys securely—never hardcode them in frontend code.
  • Configure your store screen’s frontend app to send this key in every API request via a custom header, e.g., X-Store-API-Key: YOUR_STORE_UNIQUE_KEY.

3. 编写认证中间件:统一处理身份验证

Create an Express middleware to validate the API key and inject the corresponding storeId into the request object. This keeps your route logic clean and ensures authentication runs before any data is accessed:

const Store = require('../models/Store'); // 你的门店信息Model

const authenticateStore = async (req, res, next) => {
  const apiKey = req.headers['x-store-api-key'];
  
  // 检查请求头是否携带API密钥
  if (!apiKey) {
    return res.status(401).json({ error: 'Missing store API key' });
  }

  try {
    // 从数据库查找匹配API密钥的门店
    const store = await Store.findOne({ apiKey });
    if (!store) {
      return res.status(403).json({ error: 'Invalid or expired API key' });
    }

    // 将门店ID注入请求对象,供后续路由使用
    req.storeId = store.storeId;
    next(); // 继续执行后续路由逻辑
  } catch (err) {
    res.status(500).json({ error: 'Server error during authentication' });
  }
};

module.exports = authenticateStore;

4. 设计门店专属路由:基于storeId过滤数据

Use the authentication middleware in your routes, then filter MongoDB queries using req.storeId to ensure only the store’s own data is returned:

示例1:获取门店专属公告

const express = require('express');
const router = express.Router();
const authenticateStore = require('../middleware/authenticateStore');
const Announcement = require('../models/Announcement');

// 应用认证中间件,确保只有合法门店能访问
router.get('/announcements', authenticateStore, async (req, res) => {
  try {
    // 仅查询当前门店的公告,按创建时间倒序排列
    const announcements = await Announcement.find({ storeId: req.storeId })
      .sort({ createdAt: -1 });
    
    res.json(announcements);
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch store announcements' });
  }
});

示例2:获取待处理订单

const Order = require('../models/Order');

router.get('/pending-orders', authenticateStore, async (req, res) => {
  try {
    // 过滤出当前门店且状态为"待处理"的订单
    const pendingOrders = await Order.find({ 
      storeId: req.storeId,
      status: 'pending'
    });
    
    res.json(pendingOrders);
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch pending orders' });
  }
});

5. 关键安全与维护建议

  • Never hardcode API keys: Store keys in a local .env file on each store’s screen device, and use a package like dotenv to load them securely.
  • Rotate API keys regularly: Set up a process to refresh keys every few months, or if a device is replaced, to mitigate leak risks.
  • Use HTTPS: Ensure all API requests are sent over HTTPS to prevent key interception during transmission.
  • Log access: Record requests with storeId and timestamp to monitor for unusual activity (e.g., repeated invalid key attempts).
  • Limit permissions: Make sure each API key only grants access to the routes relevant to store operations—no global admin access.

内容的提问来源于stack exchange,提问作者NRP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:05:34