Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create user roles and permission in mongodb / nosql

Ive been searching for a while trying to find tutorials on how to make a typical website MVC permission system using user roles.

Ive done such things using SQL and relations, but in nosql databases, its done differently ( i assume).

what i have in mind is something like this

//Role objects
{Roles : [
{
    '_id' : 'uniqueId',
    'role_name' : 'admin',
    'permissions_granted' : [array of permission strings]
},
{
    '_id' : 'uniqueId',
    'role_name' : 'user',
    'permissions_granted' : [array of permission strings]
},
{
    '_id' : 'uniqueId',
    'role_name' : 'guest',
    'permissions_granted' : [array of permission strings]
}
]}

//User objects
{Users: [
{
    '_id' : 'uniqueId',
    'username' : 'mike',
    'password' : 'mypass',
    'permissions' : [an instance of role group, or its id ? ]
},
{
    '_id' : 'uniqueId',
    'username' : 'jonny',
    'password' : '123',
    'permissions' : [???]
}
]}

how could i make a single query which fetches user data + its permissions ? is there a downside of using 2 querys, one to get user's role id, and then get permissions from roles document. ? how are user permissions handled in nosql databases like mongodb

like image 767
Rainer Plumer Avatar asked Nov 12 '22 22:11

Rainer Plumer


1 Answers

You should use the IDs and not the objects as such. This way you can update everything easily. If you have a scenario, when you read permissions often and write very seldom (which I assume) you can store additionally to the role ID's also the actual permissions of the user (based on its roles)

However you need to update those permissions, every time a role is updated. But when querying a user you get the roles immediately with it, which is much faster than with 2 separate queries.

like image 137
peter Avatar answered Nov 14 '22 22:11

peter