How to Add Users and How to Manage User Roles in MongoDB Using PHP

Introduction

  • This tutorial will show you how to create and change permissions when adding users and how to manage user roles in MongoDB using PHP. To accomplish these functions, you must have MongoDB and the MongoDB PHP driver properly installed on your machine.

Prerequisites

  • Confirm that you have MongoDB and the MongoDB PHP driver’s properly installed and configured on your machine before you begin.

  • You can use the below command to find out if you have the MongoDB driver installed:

pecl search mongo
  • The result should resemble this:
Package Stable/(Latest) Local
mongo 1.6.16 (stable) MongoDB database driver
mongodb 1.6.0alpha1 (alpha) 1.5.3 MongoDB driver for PHP
  • Use the following command to see which PHP version is installed on your system:
php --version
  • The results should look something like this:
PHP 7.2.15-0ubuntu0.18.04.2 (cli) (built: Mar 22 2019 17:05:14) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.2.15-0ubuntu0.18.04.2, Copyright (c) 1999-2018, by Zend Technologies
  • You should refer to the below Mongodb driver chart for any compatibility issues:

table mongodb php driver

Starting the MongoDB Daemon

  • First, open your terminal by pressing the Ctrl + Alt + T keys.

  • Next, start the MongoDB service and check the status using the below command.

NOTE: You can use sudo command to avoid permission-related issue while starting the MongoDB service, as shown here:

sudo systemctl start mongod
sudo systemctl status mongod
  • You should now see something like this:

starting mongod service

The MongoDB Database Built-In Roles

  • Next, you should familiarize yourself with the following table of the database built-in roles:

Database User Roles

RoleDescription
readThis grants the ability to read the data on non-system collections, with the following system collections that include system.namespaces, system.js and the system.indexes.
readWriteSame as the privileges of the read role, but with additional ability to modify data on all no-system collections and the system.js collection

How to Create MongoDB User and User Roles using PHP

  • The following script will create a user with corresponding roles in MongoDB using PHP:
// Using MongoDB\Driver\Manager

$dbName = 'abi_db'; //
$dbUser = 'rommel'; // (1)
$dbPass = 'abcd123'; //


$dbCon = new MongoDB\Driver\Manager("mongodb://localhost:27017"); // (2)

$command = array // (3)
(
"createUser" => $dbUser,
"pwd" => $dbPass,
"roles" => array
(
array("role" => "readWrite", "db" => $dbName)
)
);
$result = $dbCon->executeCommand( // (4)
'abi_db', new MongoDB\Driver\Command($command)
);
  • Be sure you follow these steps in the proper sequence:
  1. Info to be supplied for the user name, password and database name.
  2. Instantiate MongoDBDriverManager.
  3. The command to create a new user
  4. Execute the command to create a user in the abi_db ($dbName) database.
  • The equivalent script for the PHP Library for creating user roles is as follows:
// Using PHP Library

$dbName = 'abi_db';
$dbUser = 'rommel';
$dbPass = 'abcd123';
$dbCon = new MongoDB\Client("mongodb://localhost:27017");
$dbCon = new MongoDB\Client("mongodb://localhost:27017");
$db = $mongo->selectDatabase( $db_name );

$command = array
(
"createUser" => $dbUser,
"pwd" => $dbPass,
"roles" => array
(
array("role" => "readWrite", "db" => $dbName)
)
);

$db->command( $command );
  • Use the following command to verify that the user and it’s corresponding role was created:
db.getUser("rommel")
  • The result should resemble the following:

GeSHi Error: GeSHi could not find the language json (using path /nas/content/live/orkbprod/wp-content/plugins/codecolorer/lib/geshi/) (code 2)

How to Manage MongoDB User Roles

  • Managing MongoDB user roles is very straight forward. You just need to replace the method to be executed for a given database user, as in the below example.

NOTE: In this section the example will be based in the MongoDBDriverManager format.

Updating User Roles

  • The following script will update the user role from readWrite to read via updateUser() method.
$dbName = 'abi_db';
$dbUser = 'rommel';

$mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$command = array
(
"updateUser" => $dbUser,
"roles" => array
(
array("role" => "readWrite", "db" => $dbName)
)
);
$result = $db->executeCommand('abi_db', new MongoDB\Driver\Command($command));

Revoking User Roles

  • How to revoke a role using the revokeRolesFromUser() method:
$dbName = 'abi_db';
$dbUser = 'rommel';

$mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$command = array
(
"revokeRolesFromUser" => $dbUser,
"roles" => array
(
array("role" => "read", "db" => $dbName)
)
);
$result = $db->executeCommand('abi_db', new MongoDB\Driver\Command($command));
  • You can verify the user role was actually revoked by using the following command in the Mongo terminal:
db.getUser("rommel")
  • The result should look something like this:

GeSHi Error: GeSHi could not find the language json (using path /nas/content/live/orkbprod/wp-content/plugins/codecolorer/lib/geshi/) (code 2)
  • Notice that roles returns empty “[ ]”.

Granting User Roles

  • The following command will allow you to grant user roles to a specified user:
$dbName = 'abi_db';
$dbUser = 'rommel';

$mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$command = array
(
"grantRolesToUser" => $dbUser,
"roles" => array
(
array("role" => "read", "db" => $dbName)
)
);
$result = $db->executeCommand('abi_db', new MongoDB\Driver\Command($command));
  • You can determine if the role was successfully updated with the following command:
> db.getUser("rommel")
{
"_id" : "abi_db.rommel",
"userId" : UUID("e4d98a44-9d09-4973-9bd1-dac0f9c55351"),
"user" : "rommel",
"db" : "abi_db",
"roles" : [
{
"role" : "read",
"db" : "abi_db"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}

Conclusion

  • This tutorial showed you how to create and change permissions when adding users and how to manage user roles in MongoDB using PHPx000D. Remember, you must have MongoDB and the compatible MongoDB PHP driver properly installed on your machine to execute these functions. Before beginning, remember to confirm you have the proper PHP driver installed. You can consult the Mongodb driver chart for any compatibility issues. It is crucial you confirm that the new user roles were properly established or revoked after you have set or changed the permissions. You should also take the time to familiarize yourself with the database’s built-in roles.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.