Search code examples
javamongodbuser-roles

What is a good way to define user roles in a mongo database


Coming from a relational db background I find it easy to break apart user and their roles into normalized tables. But what is the customary way to do this in a mongo database?

Scenario I have

({    "roles" :
    [
        {"role": "user"},
        {"role": "manager"},
        {"role": "admin"}
    ]

    "privileges" :
    [
        {"privilege": "READ"},
        {"privilege": "READ/WRITE"},
        {"privilege": "ALL"}
    ] 

    "users" :
    [
        {"user": "Sammy"},
        {"user": "Tom"},
        {"user": "Fred"},
        {"user": "Zack"}
    ]

    "userPermissions" :
    [
        {"admin": "Sammy"},
        {"manager": "Tom"},
        {"user": "Fred"},
        {"user": "Zack"}
    ]
})

Question : Is this an appropriate way to model user roles in Mongo?


Solution

  • If your roles are plain Strings or a primitive tuple, you can store them as array inside each User's document. If the role is a complex entity, you can store them as an array of doc-refs.

    UPDATE:

    this is a document from my userAccount collection, generated by Spring Security Core Grails plugin:

    {
      "_id" : "541fdfdebaacef69047415a8",
      "authorities" : [ 
         {
            "authority" : "ROLE_USER"
         },
         {
            "authority" : "ROLE_ADMIN"
         }
      ],
      "password" : "lakdjalksdj87a68sd76as87d6a87sd6",
      "username" : "someusername",
      "version" : NumberLong(1)
    }
    

    Spring Security and it's descendants are the standard security implementations in java, so...