Reputation: 907
is it possible to grant a user in mongodb to access multiple databases using some sort of regex? for example in MySql i can use
grant all on `example\_%`.* to `example`@`localhost`;
Upvotes: 8
Views: 1427
Reputation: 2573
I'm not sure if there is a way to do that in MongoDB as the db value when setting user roles has to be a string, source. However, you can write a script to help you achieve the same result. I came up with this(the script itself is small, however, comments and logging make it seem long):
// script.js
// Change the value of this variable to the name of the database expected to store the user details
const userDatabase = 'test';
// Change the value of this variable to the name of the user to grant the roles
const userName = 'user';
// Get a list of all database matching the regExp /^example.*$/
const dbs = db.adminCommand({ listDatabases: 1, nameOnly: true, filter: { name: /^example.*$/ } });
print('Found ' + dbs.databases.length + ' matching databases');
// Compose the user roles
// You can remove or add more roles here
const roles = dbs.databases.map(({ name }) => ({ role: 'readWrite', db: name }));
// Change to the database expected to store the user details
const userDb = db.getSiblingDB(userDatabase);
if (userDb.getUser(userName)) {
// If the user already exists, update the user roles
print('User already exist, granting roles...');
userDb.grantRolesToUser(userName, roles);
} else {
// If the user does not exist, create the user and add roles
print('User does not exist, creating a user...');
userDb.createUser({
user: userName,
pwd: passwordPrompt(), // This would prompt a password for the new user. The password can also be written in clear text here
roles,
});
}
You would run the script like this:
// Replace <host> and <port> with the host and port values of your mongoDB server.
// Replace <adminUserName> with the userName of the admin user
mongo <host>:<port>/admin script.js -u <adminUserName> --authenticationDatabase "admin" -p
A password prompt would appear after running the command above, you should enter the password of the admin user.
Upvotes: 1