MongoDB Show Current User - mongodb

How do I show the current user that I'm logged into the mongo shell as? This is useful to know because it is possible to change the user that you are logged in as—e.g. db.auth("newuser", "password")—while in the interactive shell. One can easily lose track.
Update
Using the accepted answer as a base, I changed the prompt to include user, connection, and db:
Edit .mongorc.js in your home directory.
function prompt() {
var username = "anon";
var user = db.runCommand({connectionStatus : 1}).authInfo.authenticatedUsers[0];
var host = db.getMongo().toString().split(" ")[2];
var current_db = db.getName();
if (!!user) {
username = user.user;
}
return username + "#" + host + ":" + current_db + "> ";
}
Result:
MongoDB shell version: 2.4.8
connecting to: test
anon#127.0.0.1:test> use admin
switched to db admin
anon#127.0.0.1:admin> db.auth("a_user", "a_password")
1
a_user#127.0.0.1:admin>

The connectionStatus command shows authenticated users (if any, among some other data):
db.runCommand({connectionStatus : 1})
Which results in something like bellow:
{
"authInfo" : {
"authenticatedUsers" : [
{
"user" : "aa",
"userSource" : "test"
}
]
},
"ok" : 1
}
So if you are connecting from the shell, this is basically the current user
You can also add the user name to prompt by overriding the prompt function in .mongorc.js file, under OS user home directory. Roughly:
prompt = function() {
user = db.runCommand({connectionStatus : 1}).authInfo.authenticatedUsers[0]
if (user) {
return "user: " + user.user + ">"
}
return ">"
}
An example:
$ mongo -u "cc" -p "dd"
MongoDB shell version: 2.4.8
connecting to: test
user: cc>db.auth("aa", "bb")
1
user: aa>

Related

Mongo DB authentication not working in grails but from console

I want to use authentication in my mongodb. So I created a user. Which this user I can connect on command line and insert data without any problem.
But when I want to use this user in grails, I get this error:
{ "serverUsed" : "127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "auth failed" , "code" : 18 , "codeName" : "AuthenticationFailed"}
When I connect from commandline, everything works:
mongo --port 27017 -u "mongouser" -p "pwd" mydb
My code in Grails:
MongoCredential credential = MongoCredential.createMongoCRCredential("mongouser", "mydb", "pwd".toCharArray())
def mongoClient = new MongoClient( new ServerAddress(host, port), [credential ] )
gMongoCon = new GMongo(mongoClient)
What is wrong here?
Add your mongo credentials in Config.groovy or external config as follows,
grails
{
mongo
{
host = "YOUR_HOST_NAME_OR_IP_ADDRESS" // e.g localhost
port = 27017
username = "mongouser" //Username
password = "pwd" //password
databaseName = "mydb" //Database name
}
}
Note: change the bind_ip from /etc/mongod.conf if the application and
mongo are on different server.
This solution works:
MongoCredential.createCredential(username, datatable, password)

How to change mongoshell prompt?

I've recently re-installed Mongodb switching from the enterprise to the community version. Nevertheless, when I start mongo, this is the prompt format I get:
MongoDB Enterprise >
How can I change it to the standard prompt version? (i.e., > if I am not wrong)
You can change the prompt from within a shell session by setting the prompt variable. For example, issuing the following command within a Mongo shell ...
var prompt="this_prompt >"
... will result in the shell's prompt changing to:
this_prompt >
You can change the default prompt for all future sessions by updating your .mongorc.js (you'll find this in your $HOME directory and if it does not exist then just create it). The following addition to your .mongorc.js ...
var prompt=function() {
return ISODate().toLocaleTimeString() + " > ";
}
... will result in this prompt:
:~/dev/tools/mongodb/mongodb-osx-x86_64-3.4.7/bin$ ./mongo
MongoDB shell version v3.4.7
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.7
16:09:43 >
16:09:57 >
Or, to get this prompt: > just add the following to your .mongorc.js:
var prompt=">"
There remains the sub text to your question, namely; where is the existing MongoDB Enterprise > prompt coming from?. It's hard to say but ...
Perhaps you have a Global mongorc.js; have a look in /etc/mongorc.js if you are on a *nix system or %ProgramData%\MongoDB if you are on Windows
Mongo behavour when finding a rc file is also subject to environment variables, more details in the docs.
When you search the internet for this topic then often you find the function below. If you like to include the existing prompt then use function defaultPrompt(), e.g.
prompt = function() {
if (typeof db == 'undefined')
return '(nodb)> ';
// Check the last db operation
try {
db.runCommand( {getLastError:1} );
} catch (e) {
print(e);
}
var user = db.runCommand({connectionStatus : 1}).authInfo.authenticatedUsers[0]
if (user) {
return user.user + "#" + db + " " + defaultPrompt();
} else {
return "(anonymous)#" + db + " " + defaultPrompt();
//return db + " " + defaultPrompt(); // if you prefer
}
}
Prompts will be like this:
admin#mip mongos>
mip shard001:ARBITER>
admin#mip configRepSet:PRIMARY>

mongodb authorization exception in JMeter : code13

In MongoDB 3.2 I've setup a user with rights:
db.createUser(
{
user: "username",
pwd: "pass",
roles: [ { role: "readWrite", db: "dbname" }]
}
)
db.auth("username", "pass" )
When I use the JMeter(2.13) to connect to the database (using Jmeter's elements MongoDB Source Config , MongoDB Script) and run a query like this:
db.mycollectionname.find()
I get this error:
error: { "$err" : "not authorized on dbname to execute command { $eval: \"db.mycollectionname.find()\", args: [] }" , "code" : 13}
While I have provided all the necessary details Server Address List , Database , User , Password to Jmeter's MongoDB Source Config , MongoDB Script respectively.
Any ideas what can be happening?
I had the same issue. I had to set up a user with eval permissions even though this is not recommended (even the admin user does not have these permissions).
Try that and change you script to look at the new user and it should work.

Cannot access authenticated MongoDB collection from ReactiveMongo Play app

I have a MongoDB server where I have enabled authentication and created users with DB-specific permissions. The user for this app is defined as shown below i.e. geoAdmin has read, readWrite and dbOwner permissions for the relevant database:
MongoDB shell version: 3.0.0
connecting to: 192.168.2.89/test
> use geo_db
switched to db geo_db
> db.getUser("geoAdmin")
{
"_id" : "geo_db.geoAdmin",
"user" : "geoAdmin",
"db" : "geo_db",
"roles" : [
{
"role" : "read",
"db" : "geo_db"
},
{
"role" : "dbOwner",
"db" : "geo_db"
},
{
"role" : "readWrite",
"db" : "geo_db"
}
]
}
The following query works OK i.e. connecting to the remote server from my local mongo client:
mint:~ $ mongo 192.168.2.89:27017 -u geoAdmin -p secret --authenticationDatabase geo_db
MongoDB shell version: 3.0.0
connecting to: 192.168.2.89/test
> use geo_db
switched to db geo_db
> db.LAD_DEC_2013_GB_BFE.findOne({},{'properties.LAD13NM':1})
{
"_id" : ObjectId("54ffe2824f0787ec1293017f"),
"properties" : {
"LAD13NM" : "Hartlepool"
}
}
I then connect to the same remote host from a ReactiveMongo Play app on the same local client, with this URL in the app config file:
# ReactiveMongo
mongodb.uri = "mongodb://geoAdmin:secret#192.168.2.89:27017/geo_db"
But when my app tries to read from the same collection, I get a MongoDB "code = 13" error:
[DetailedDatabaseException: DatabaseException['not authorized for query on geo_db.LAD_DEC_2013_GB_BFE' (code = 13)]]
The app works fine if I connect to a local MongoDB which does not have authentication enabled.
Any ideas what might be going wrong here?
ReactiveMongo 0.11.7.play23 is supporting mongo 3.0 auth-protocols, but is still using the old as default.
With ReactiveMongo 0.11.7.play23 -plugin, you can make it authenticate with mongo 3.0, by adding "?authMode=scram-sha1" to the end of your mongodb.uri.
E.g.:
mongodb.uri = "mongodb://geoAdmin:secret#192.168.2.89:27017/geo_db?authMode=scram-sha1"
mongo 2.6 uses MONGODB-CR auth protocol and 3.0 uses MONGODB-SHA-1 by default
reactivemongo use MONGODB-CR auth protocol(not sure)
downgrade mongodb 3.0 auth mechanisms to MONGODB-CR
login mongo noauth
remove all user
update the version document for the authSchema.
ex.
db.getSiblingDB("admin").system.users.remove( {} )
db.getSiblingDB("admin").system.version.update(
{ _id: "authSchema" },
{ $set: { currentVersion: 3 } }
);
add authSource parameter to mongodb url
ex.
mongodb.uri = "mongodb://geoAdmin:secret#192.168.2.89:27017/geo_db?authSource=geo_db"

How to copy password protected database from remote server in mongodb?

I am running mongodb 2.4.8 and need to copy a database from remote server. Server has auth enabled in combination with a user having privileges the database. I have tried copydb but it didn't work. I guess it failed because of remote server using auth in combination with role based user(mentioned under authentication section of documentation).
host = "myhost.com"
mynonce = db.runCommand( { copydbgetnonce : 1, fromhost: host } ).nonce
username = "myuser"
password = "mypassword"
password_hash = hex_md5(mynonce + username + hex_md5(username + ":mongo:" + password))
db.runCommand({
copydb: 1,
fromdb: "test",
todb: "test",
fromhost: host,
username: username,
key: password_hash
})
# output: { "ok" : 0, "errmsg" : "" }
# but nothing really gets copied
What other options do I have? I would prefer a solution which can work from within the mongo shell as I do not have ssh access to server.
try db.copyDatabase(fromdb, todb, fromhost, username, password). as manual said: http://docs.mongodb.org/manual/reference/method/db.copyDatabase/