I am interested in establishing different access privileges for each user.
- A Super admin has full access to the entire database.
- An Admin can only access data related to their specific field.
- A User is limited to accessing data pertinent to their own profile.
In order to achieve this, a document-level access control mechanism is required where access to a document
is determined by the value in a particular field. However, up to version 3.0, MongoDB does not offer built-in support for document/field level access-control; ACLs are limited to the Collection-level.
How can I implement different schemas for distinct user types and prevent unauthorized access to resources?
Given the current limitations at the database level, achieving this solely through the database alone, especially in terms of restricting access to 'documents', is not feasible. Nevertheless, similar functionality can be implemented at the application level (such as with sailJS).
At the database level, one workaround is to move user documents to separate collections and employ the createRole() method to establish roles and specify associated privileges.
For SuperAdmins:
db.createRole({ role: "SuperAdmin",
privileges: [
{ resource: { db: "myCustomDB", collection: "" }, actions: [ "find", "update", "insert", "remove" ]}
],
roles: []
})
SuperAdmins are granted full access to all collections within the myCustomDB database and can execute find
, update
, insert
, and remove
actions.
For Admins:
db.createRole({ role: "Admin",
privileges: [
{ resource: { db: "myCustomDB", collection: "AdminCollection" }, actions: [ "find", "update", "insert", "remove" ]},
{ resource: { db: "myCustomDB", collection: "" }, actions: [ "find"]}
],
roles: []
})
Admins have CRUD permissions on documents within their designated collection but only read-only access to other database collections.
For Users:
db.createRole({ role: "User",
privileges: [
{ resource: { db: "myCustomDB", collection: "UserCollection" }, actions: [ "find", "update", "insert", "remove" ]}
],
roles: []
})
Note: For users still on version 2.4 (or earlier), it may be necessary to relocate user collections to a separate database due to MongoDB's ACL limitations being restricted to Database-Level access in versions 2.4 and below.