How to assign distinct privileges to users and administrators in MongoDB?

I am currently working on developing an application using Sails and MongoDB that requires three levels of users.

  • Super admin
  • Admin
  • User

My goal is to assign different privileges to each type of user

  • The Super admin should have access to the entire database.
  • An Admin can only access data related to their field
  • A User can only access data specific to that user.

How can I implement different schemas for each type of user and restrict access so one user cannot view resources belonging to another?

Answer №1

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.

Answer №2

Imagine you're in the process of setting up a database called "records"

When using mongo shell >>

//SuperADMIN
use admin
db.createUser(
 {
   user: "superuser",
   pwd: "12345678",
   roles: [ "root" ]
 }
 )


 //ADMIN
 use records
 db.createUser
 (
   {
     user: "recordsUserAdmin",
     pwd: "password",
     roles: [ { role: "userAdmin", db: "records" } ]
   }
 )





//Any User
use records
db.createUser(
 {
    user: "recordUser",
    pwd: "12345678",
    roles: [
       { role: "read", db: "records" },
       { role: "read", db: "user" },
       { role: "read", db: "sales" },
       { role: "readWrite", db: "accounts" }
    ]
  }
 )

To learn more, visit:

Mongo tutorial create admin

Add user to mongo

Answer №3

What you're trying to achieve cannot be done solely at the database level.

One workaround could involve creating a separate user account with different permissions for accessing and modifying the database. However, restricting a user to only view data related to themselves is not supported by traditional database setups. To accomplish this, authentication checks would need to be implemented within the application itself. This process typically involves verifying if a user has authorization to access certain data, based on criteria such as ownership. For instance, the application might determine whether "User ABC" owns "Data XYZ" before granting them access to view it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Including item from ajax not within $.when function finished

function fetchData(){ return $.ajax({ url : 'URL1', data : { id : id }, type : 'GET', }); } function fetchItemData(item_id) { return $.ajax({ url: 'URL2', data: { item_id: it ...

The value of an AngularJS service is not being reflected in the view

I have implemented the stateProvider in my code, and I am facing an issue with updating the breadcrumbs in the header when the state changes. Instead of creating embedded views for each state, I have a service that shares an array of breadcrumbs containing ...

Error message in Node.js: Unable to establish connection to 127.0.0.1 on port 21 due to E

I am currently developing a simple application using node js, and I have encountered the following issue: Error: connect ECONNREFUSED 127.0.0.1:21 at Object exports._errnoException (util.js:1034:11) at exports _exceptionWithHostPort (util.js:1057: ...

angularjs | clear input field by clicking on icon inside input

I am struggling to understand why I can't remove the value by clicking on the remove-icon in the input field. <i ng-hide="search" class="glyphicon glyphicon-filter"></i> <i ng-show="search" ng-click="search=null" cl ...

I am having trouble establishing a connection between my Node.js server and the Google Cloud Platform server

I've been working on a global ESP32 Cam project, aiming for worldwide connectivity. I came across a tutorial that has been my guide: https://www.youtube.com/watch?v=CpIkG9N5-JM. I followed all the steps in the tutorial diligently, but unfortunately, I ...

MongoError: The close method cannot be called on MongoClient

I am currently working on an application that automatically closes its database connection after a period of inactivity. However, I am encountering issues with using the MongoClient.close() function as it keeps throwing an error stating "TypeError: Mongo ...

What is the best way to create 7 or 8 column grids with Vuetify's v-row and v-col components?

I understand that vuetify's grid system is based on a 12-column flex-box layout, but I would like to customize it to have 7 or 8 columns by default instead of the usual 12. In the code snippet below, you can see my attempt: <v-row> <v-col ...

Verifying if checkboxes are selected in PHP using JavaScript

echo '<div class="col-lg-10 col-lg-offset-1 panel">' . "<table id='data' class='table'> <tr> <th></th> <th>Document No</th> <th>AWB NO</th> ...

Having trouble accessing the properties of an undefined variable (reading 'VSCODE_TEXTMATE_DEBUG')

Encountering an error while attempting to use Shiki in Nuxt3. The cause is unknown, even after trying to add the environment variable with no success. Here's a recreation of the error: https://stackblitz.com/edit/github-whzftm?file=pages%2F%5B...slug ...

Error: Unable to locate module: 'fs' in Next.js

import nookies from 'nookies'; import { firebaseAdmin } from "../firebaseAdmin"; import { TChildren } from "../types/app/app.types"; interface Props { children: TChildren; } export default function ProtectedRoute(props ...

The average calculation malfunctioning after adjusting the input data

I am a beginner with AngularJS and facing an issue. I have a list of cities for which I need to calculate the average temperature. However, after editing the temperature values in the city list, the function that computes the average temperature is giving ...

Utilizing a combination of a `for` loop and `setInterval

I've been encountering an issue for the past 3-4 hours and have sought solutions in various places like here, here, here, etc... However, I am unable to get it to work in my specific case: var timer_slideshow = {}; var that, that_boss, has_auto, el ...

Can one open a unique custom pop-up before the window is about to close?

Seeking a way to create a pop-up confirmation dialog for users when they try to log out or stay on the page while logged in. I attempted using the code below, but haven't been able to find the correct solution: window.onbeforeunload = function (e) { ...

Trapped in the dilemma of encountering the error message "Anticipated an assignment or function: no-unused expressions"

Currently facing a perplexing issue and seeking assistance from the community to resolve it. The problem arises from the code snippet within my model: this.text = json.text ? json.text : '' This triggers a warning in my inspector stating: Ex ...

The configuration settings for MongoDB database names are not properly recognized by Spring Webflux

I am currently tackling the challenge of creating a reactive application using Spring Webflux and MongoDB. Here is the configuration I have set in the application.properties file: spring.data.mongodb.database=my-db spring.data.mongodb.uri=mongodb://user:p ...

Is my Socket.io application consuming excessive bandwidth? What might be causing this issue?

Upon reviewing my AWS billing report, I noticed an excessive data transfer of 495.385 GB on my socket.io application running on the EC2 instance. This amount seems too high for a small experimental website like mine. Could this be due to inefficient code i ...

Transforming NIF to OBJ within the Blender 249.2 software results in an object that is not visible

I am currently utilizing Three.js for rendering Fallout 3 assets in WebGL. Check out the JavaScript code for a similar object rendering here. Most objects are loading fine along with their normals, except for the brahmin... While the texture and normals a ...

Body not being populated in POST request

I'm encountering an issue with transferring data from the client side to the server side. Within my application, I have a form that needs to be submitted to the server. Since I am utilizing a library to automatically generate my form from a JSON sche ...

Creating a series of adjacent dropdown menus with JavaScript, HTML, and CSS

I am encountering an issue while attempting to place multiple dropdown menus next to each other. I have included two categories as dropdown options in the header, but I am facing difficulty with one of them not functioning correctly. When I click on the no ...

What could be causing my dangerouslySetInnerHTML to show altered content?

I am working on a project using React and have encountered an issue with the code: const externalMarkup = ` <a data-refpt='DN_0OKF_177480_ID0EMPAC' /> <ol> <li value='1'> <p> <strong&g ...