Authenticating while connecting to multiple database using mongoose - mongodb

I have set up auth in my MongoDB as mentioned here. Initially, in my project I was accessing a single database say, firstdb from mongoose using
let url = "mongodb://localhost:27017/firstdb";
let options = {
server:{
socketOptions:{
keepAlive:120
}
},
user:"username1",
pass:"mypassword1"
};
mongoose.connect(url,options,callback);
The user with username and mypassword was created in the firstdb itself giving it readWrite perms. I did this while logged in with my admin user.
Things were working smoothly. Then I had a requirement of connecting to a second database. So I changed my code as such
let url1 = "mongodb://localhost:27017/firstdb";
let options1 = {
server:{
socketOptions:{
keepAlive:120
}
},
user:"username1",
pass:"mypassword1",
auth:{
authdb:"firstdb"
}
};
let connection1 = mongoose.createConnection(url1,options1);
let url2 = "mongodb://localhost:27017/seconddb";
let options2 = {
server:{
socketOptions:{
keepAlive:120
}
},
user:"username2",
pass:"mypassword2",
auth:{
authdb:"seconddb"
}
};
let connection2 = mongoose.createConnection(url2,options2);
This time I created user username2 the same way in the seconddb database. But now mongoose is unable to perform any operation and is failing with Not authorized to execute command. I can access the db through mongo shell though. I also spun up the code in my local system which doesn't have mongodb auth enabled and it works fine there. Please help

So, after shooting around in the blind, found something that works.
Use the username and password in the url itself like
let connection1 = mongoose.createConnection("mongodb://username1:password1#localhost:27017/firstdb");
Still, I would like to know why passing the parameters as options doesn't work.

Related

Heroku Express + Postgres addon requires elevated privileges

[2018-05-16 08:27:12.979] [ERROR] server - Pipe
postgres://xnmcmqfirrdzkg:638d94fcd7aa5178e1054f0ff604613826033d5e8845fb42614c17a3d386823a#ec2-107-21-126-193.compute-1.amazonaws.com:5432/d5l5g60nk6l27a
requires elevated privileges
I'm trying to deploy server Express + Sequelize + Postgres on Heroku.
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable]);
}
else {
config.logging = function (str) {
log4js.getLogger("sequelize").info(str);
}
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
The data's credential is set at default. I tried searching on the internet but there is no one having the same problem with me.
I am. But I have not been able to figure it out yet. And the docs I have been provided are more than two years old.

"Not authorized on ___ to execute command" with mLab + MongoDB ^3.0

Connects without a hitch, but on insert() throws me this error.
var MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
var url = 'mongodb://____:____#ds125565.mlab.com:25565/heroku_w268n9pj';
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
db = client.db('temp');
console.log("connected!");
const collection = db.collection('temp');
collection.insert([{
something: please
}
});
I saw some other answers regarding mLab accounts and credentials, but I just created a new admin account for this. Frustrating because it was working previously with v2.3.
When attempting to connect to an mlab database, you have to correctly specify the client. It's located at the end of your connection string, just after the final forward slash.
mlab_url = "mongodb://db_user_name:db_password#ds139725.mlab.com:39725/heroku_sd1fp182?retryWrites=false"
client = MongoClient(url)
db = client["heroku_sd1fp182"]
collection = db["coinHack"]
You may also get the error:
This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.
Just add "?retryWrites=false" to your connection string, as shown above.

Making public realms on Realm Object Server in Swift

I am trying to make a public realm that all users will have read permissions to. The realm team mentioned this capability in this webinar, but I am having trouble finding any documentation on how to do it.
Here is a nice image from the webinar that illustrates the types of realms that can be made in the object server. I am having trouble finding out how to make a public realm.
Here are directions for doing what you want. Be aware that this feature has changed slightly since that webinar was presented. (We also need to improve our documentation, so thank you for asking this question!)
Create an admin user. You can do this by creating a regular user, going to the web dashboard, and editing the user so that it is an administrator. If the user is an admin, upon logging in its isAdmin property should be true.
Using your admin user, open a global Realm. A global Realm is one whose path doesn't contain ~, for example /myGlobalRealm versus /~/eachUserHasTheirOwnCopy. Note that this Realm is completely inaccessible to other users by default. If the Realm doesn't yet exist, the Realm Object Server will automatically create it. This will be your public Realm.
Create an RLMSyncPermissionValue to grant read permissions to all users. This means specifying the path to your public Realm (/myGlobalRealm), as well as a user ID of *.
Then call -[RLMSyncUser applyPermission:callback:] on your admin user with your new permission value, and ensure that the server properly set the permission.
Try opening your public Realm using a different user, and make sure it works.
I hope this helps.
Swift Solution
You can run this once in your simulator to create a global realm with default read/write permissions.
SyncUser.logIn(with: .usernamePassword(username: "ADMIN USERNAME", password: "ADMIN PASSWORD!"), server: URL(string: "Your Server URL")! { (user, error) in
guard user != nil else{
print(error)
return
}
do{
let globalRealm = try Realm(configuration: Realm.Configuration(syncConfiguration: SyncConfiguration(user: user!, realmURL: URL(string: "realm://<YOUR SERVER>:9080/GlobalRealm")!), readOnly: false))
}catch{
print(error)
}
let permission = SyncPermissionValue(realmPath: "/GlobalRealm", userID: "*", accessLevel: SyncAccessLevel.write)
user!.applyPermission(permission) { error in
if let error = error{
print(error)
}else{
user!.retrievePermissions { permissions, error in
if let error = error {
print("error getting permissions")
}else{
print("SUCCESS!")
}
}
}
}
}
Here is a server function to write a public realm:
const Realm = require('realm');
const server_url = 'realm://<Your Server URL>:9080'
const realmName = 'PublicRealm'
const REALM_ADMIN_TOKEN = "YOUR REALM ADMIN TOKEN"
const adminUser = Realm.Sync.User.adminUser(REALM_ADMIN_TOKEN);
var newRealm = new Realm({
sync: {
user: adminUser,
url: server_url + '/' + realmName
},
});
Paste the code into the function editor in the realm dashboard and run the function to create a public realm. You can modify the public realm by changing the properties in the realm constructor.

How do I remove a user in mongoDB from the terminal by username?

My question is this: How can I remove a user from the users db by username, or at all even?
I have a meteor application with a custom registration, and when an account is created you can login and manage your account and what have you.. My problem is that, on the local host for testing, I created a few extra user accounts that I want to delete individually (not a complete reset). I am on OS X so I went to terminal, typed in 'show dbs' but users came up empty and when I typed 'show users' nothing came up. If I type 'db.users.findOne()' information appears and I can get a username and _id. I know there is users and this command shows that there is at least one but the rest of the commands indicate that I can't manage them.
Below is some code for the registration page, specifically the Accounts.createUser I'm not sure it will mater for the response but I wanted to be thorough.
Template.SignUp.events({
'submit form': function(event, template){
event.preventDefault();
var UsernameVar = template.find('#username').value;
var emailVar = template.find('#Email').value;
var passwordVar = template.find('#password').value;
var ConfirmPasswordVar = template.find('#Cpassword').value;
if(ConfirmPasswordVar == passwordVar)
{
document.getElementById("NotValid").style.display = 'none';
Accounts.createUser({
username: UsernameVar,
email: emailVar,
password: passwordVar
}, function(err, result){
if(err)
{
document.getElementById("Unavailable").style.display = 'block';
}
else{
document.getElementById("Unavailable").style.display = 'none';
}
});
}
else{
document.getElementById("NotValid").style.display = 'block';
}
}
});
I've done a lot of searching on this issue and all I've found is how to grant users the right to remove profiles but I want to do it from terminal, even when the application launches I will be the only one to be using this feature so I don't want to start giving those rights to users.
If there is anything else I should provide please let me know.
meteor mongo
db.users.find({username: "someusername"}) // ensure that your query returns the correct user that you want to remove
db.users.remove({username: "someusername"})

'Execute failed:unauthorized' when using RockMongo with MongoLab

I can't use RockMongo(v1.1.2) to connect MongoLab, what did i do wrong?
In my MDb.php file
$MONGO["servers"][$i]["mongo_name"] = "MongoLab";
$MONGO["servers"][$i]["mongo_host"] = "ds053xx.mongolab.com";
$MONGO["servers"][$i]["mongo_port"] = "53818";
$MONGO["servers"][$i]["mongo_timeout"] = 0;
$MONGO["servers"][$i]["mongo_auth"] = true;
and when I log in with my username, password, db_name
It can log in but I can't do anything with it
on the left side of the screen it show
Execute failed:unauthorized
function (){ return db.getCollectionNames(); }
I have no problem when connect to local database.
And also can use the same url,port,username,etc. with MongoVUE
This doesn't appear to be anything you're doing wrong. It looks like RockMongo requires admin access because it's trying to list collections for databases other than your own (such as the admin and local databases), which is not possible w/ MongoLab's Sandbox databases.
https://github.com/iwind/rockmongo/issues/35
If you want to access only your own database, you can change the following line 31 inside rockmongo/apps/models/MDb.php listCollections(MongoDB $db) function:
from
$names = self::exec($db, 'function () {
return db.getCollectionNames();
}');
to
$names = $db->getCollectionNames();