Reputation: 11309
Is it possible to get list of databases in Mongodb for which a particular user is having access?
Upvotes: 2
Views: 1534
Reputation: 11655
Since the 4.0.5 MongoDB there is an option in listDatabases that allows to filter only the authorized Databases:
authorizedDatabases [boolean] [Optional]: A flag that determines which databases are returned based on the user privileges when access control is enabled.
It may be something like:
return mongoClient.getDatabase("admin").runCommand(
new BasicDBObject("listDatabases",
new BasicDBObject("authorizedDatabases", 1)
)
);
Read the full documentation as there are some subtle differences between versions:
Upvotes: 0
Reputation: 103365
In the MongoDB shell, the following command will list the databases:
db.adminCommand('listDatabases')
or
db.getMongo().getDBNames()
For the current Java API, use the MongoClient's listDatabaseNames()
method which returns an iterable containing all the names of all the databases. As an example (untested):
import java.net.UnknownHostException;
import java.util.List;
import java.util.Set;
import com.mongodb.DB;
import com.mongodb.MongoClient;
public class JavaMongoDBConnection {
public static void main(String[] args) {
try {
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoIterable<String> allDatabases = mongoClient.listDatabaseNames();
for (String dbName : allDatabases) {
DB db = mongoClient.getDB(dbName);
char[] password = new char[] {'s', 'e', 'c', 'r', 'e', 't'};
boolean authenticated = db.authenticate("user", password);
if (authenticated) {
System.out.println("Successfully logged in to MongoDB!");
System.out.println("Database: " + dbName);
Set<String> collections = db.getCollectionNames();
for (String colName : collections) {
System.out.println("\t + Collection: " + colName);
}
} else {
System.out.println("Invalid username/password");
}
}
mongoClient.close();
} catch (UnknownHostException ex) {
ex.printStackTrace();
}
}
}
Upvotes: 1
Reputation:
You can check the access of specific user by finding that user in system.users collection. their you can add projection on db key which comes under roles key.
Here is the structure of doc in users collection.
{
_id: <system defined id>,
user: "<name>",
db: "<database>",
credentials: { <authentication credentials> },
roles: [
{ role: "<role name>", db: "<database>" },
...
],
customData: <custom information>
}
Upvotes: 0