使用pymongo插入嵌套字段时清理用户输入

时间:2013-01-04 01:57:42

标签: python mongodb pymongo

我有一个充满结构的集合,如下所示:

{
  "_id": {
      "$oid": "xxxxxxxxxxxxxxxxxx"
   },
  "sections": {
      "Some Cool Section" : {
        "sources" : ["source1", "source2", "source3"]
      }
      "An Awesome Section" : {
        "sources" : ["source1", "source2", "source3"]
      }
   },
  "username": "boatzart"
}

我需要允许用户随意添加新的“部分”,所以使用pymongo我可以像这样添加部分:

userid = bson.ObjectId('xxxxxxxxxxxxxxxxxx')
sectionname = getUnsafeUserInput()
mongo.db.userprofiles.update({'_id' : userid},
  { '$set' : { 'sections.'+sectionname: { 'sources': []} } }
    )

由于sectionname来自不安全的用户输入,因此某些恶意用户可能会通过在其section name中添加句点等内容来搞砸数据库。我可以很容易地擦掉非字母数字字符,但我觉得应该有更好的方法来做到这一点。

有没有更好的方法将嵌套字段插入现有文档中,而不需要我擦除内容?

如果没有,那么我认为哪些角色不安全?所有非alpha数字?只有时期?期间和美元符号?

1 个答案:

答案 0 :(得分:1)

如果您可以重新设计架构,那么将这些用户定义的节名称视为值而不是键,应该更清晰:

{
  "_id": {
      "$oid": "xxxxxxxxxxxxxxxxxx"
  },
  "sections": [{
        "name": "Some Cool Section",
        "sources" : ["source1", "source2", "source3"]
      }, {
        "name": "An Awesome Section",
        "sources" : ["source1", "source2", "source3"]
      }
  ],
  "username": "boatzart"
}

使用动态密钥名称很少是一个好主意,因为它会使查询和更新变得混乱。