mongo authorization zend shanty - php

I trying to add authorization to mongoDB.
I use mongodb 2.2.4, php-mongo 1.4.1 stable, apache2, php 5.4, ZendFramework 1.12 + ShantyMongo
Also I use replicaset with 3 instances.
When I set auth = true mongo create admin database, and when I add user to this database I got this error:
Fatal error: Uncaught exception 'MongoCursorException' with message 'test.server.com:27017: unauthorized db:database_test ns:database_test.options lock type:0 client:127.0.0.1' in /apps/test_app/libs/Shanty/Mongo/Collection.php:3501
If I add user to my database_test all work fine.
<?php
/* Configure logging */
MongoLog::setModule( MongoLog::ALL );
MongoLog::setLevel( MongoLog::ALL );
$m = new MongoClient(); // connect
$db = $m->selectDB("database_test");
$db->authenticate('admin','12345');
this code work fine even if I add user to both admin and database_test.
Maybe someone has similar problem and know what I need to do.

First of all, you should use the following syntax for specifying authentication:
<?php
$m = new MongoClient("mongodb://admin:12345#localhost/database_test");
$db = $m->database_test;
It's a bit difficult to answer your question though, as "when I add user to this database" is not really descriptive. In order to get a proper answer, you need to learn to list the exact steps or code that you used to do this.
I am thinking that you were trying to auth against a normal database (database_test), where you would only have a user/pass set for the admin database. In that case, you need to auth to the admin database, and then select your database_test:
<?php
$m = new MongoClient("mongodb://admin:12345#localhost/admin");
$db = $m->database_test;

Thank you for your answer I figured out this.
Maybe it's will be heplful for some one on future, Shanty-Mongo require username, password and port in array of servers.
It's should looks like:
; Shanty Mongo Config
hosts.0.host = '127.0.0.1'
hosts.0.port = '27017'
hosts.0.username = 'root'
hosts.0.password = 'pass'
hosts.1.host = '127.0.0.1'
hosts.1.port = '27018'
hosts.1.username = 'root'
hosts.1.password = 'pass'
hosts.2.host = '127.0.0.1'
hosts.2.port = '27019'
hosts.2.username = 'root'
hosts.2.password = 'pass'
database = 'database_test'
replicaSet = true
Also what I do:
in mongo:
1. edit config file, enable auth (auth = true)
2. create user in admin database
3. connect as new user
4. create user in target database
in ZF config
update config file, as I describe above.
Also some times I get error: Fatal error: php_network_getaddresses, I think it's because I have some trouble with DNS or php trying resolve address: mongo://root:pass#127.0.0.1:27017,root:pass#127.0.0.1:27018,root:pass#127.0.0.1:27019/database_test

Related

Working with the latest PHP / MongoDB version

After much of a struggle I managed to install MongoDB as a service and WAMP. Then on start I got a fatal error saying these would not work:
$m = new Mongo(...);
$m = new MongoClient(...);
In some previous questions on SO people mentioned using a new class called MongoDB/Driver/Manager. I also came across something called MongoDB/Client.
As a beginner to MongoDB I now stand rather confused about how to use/connect to a DB and collection.
I guess I will use:
$m = new MongoDB/Driver/Manager(...);
However,
$db = $m->$dbname; // Seems to cause -> Notice: Undefined Property
$collection = $db->shows; // dito
So all in all what are the difference between MongoDB/Driver/Manager and MongoDB/Client ? And with these new classes how would I correctly connect to a DB or Collection as shown in the previous snippet ? I can't seem to find many examples explaining how to use these new classes, or an up to date correct way of using the new classes for basic functionality.
Thanks,
I think I understand what I am confusing.
Using the MongoDB/Driver/Manager class and others, are part of the basic tools available with the PHP MongoDB Driver. I am guessing it is not recommended using them unless you know what you are doing, or you want something relatively customized.
A more recommendable alternative is to install "mongodb/mongodb-^1.x.x" with a PHP installer such as Composer, which will give you a MongoDB Library. This will give you classes such as the MongoDB/Client class.
Once the library has been installed you can connect like so:
<?php
require 'vendor/autoload.php';
$client = new MongoDB/Client('mongodb://localhost:27017');
// Add URI of MongoDB here
$mydb = $client->mydb; // Add the new DB name or existing DB name here
$collection = $mydb->createCollection('userCollection');
...
?>

Mongo bug - How to protect or authenticate my database?

How can I protect or authenticate my database in MongoDB?
I created a user using the command line,
use mydb
db.createUser(
{
user: "root",
pwd: "password",
roles: [ { role: "userAdmin", db: "mydb" } ]
}
)
my php,
// connect to mongodb
$m = new MongoClient();
var_dump($m);
// select a database
$db = $m->selectDB("mydb");
var_dump($db);
But why I still can access the database without authentication? What have I missed?
I'm on MongoDB 3.
This is totally expected, not a bug at all.
I am just adding text to Blakes Seven's above link and comment:
This is the guest user concept and does not impact security (see Blakes link: mongodb allows guest connection even when auth is enabled).
This means: your data is safe, guest users can only access meta data. This concept is well known from other services (see Jenkins, see some CMS system etc).
I must run the mongo again
C:\mongodb\bin\mongod.exe --auth
Then the auth works as expected.

MongoDB PHP connection not working

<?php
$m = new MongoClient('mongodb://localhost', array(
'username' => 'wa',
'password' => 'password',
'db' => 'wa'
));
I'm using that code snippet to connect and am trying to run commands in PHP to insert / find data in a MongoDB collection or database.
I installed MongoDB and added the mongo.so extension to my php.ini.
What am I doing wrong?
Can you run just the connection code from the command line. Also you should be passing in your connection options in this format:
mongodb://[username:password#]host1[:port1][,host2[:port2:],...]/db
Use this:
<?php
$m = new MongoClient('mongodb://wa:password#localhost/wa');
?>
That will throw any errors you are having on the command line and be easy to diagnose. The responses should be self explainatory. Likely causes:
You are connecting to localhost and do not have a running mongod or mongos on this machine. [ So change tha host and possibly port].
Your user credentials are incorrect
It seems likely that case 1 applies by the very fact you are supplying user credentials, as you would be unlikely to need them if developing on your own machine. It would also be very uncommon to be running MongoDB on the same server as your application in production.
For anyone that stumbles upon this, the MongoClient is depricated and does not work with the current (as of Aug 2018) MongoDB PHP Driver. (which would be installed with the mongodb.dll file, not the *.so file)
A current example of a working connection would be:
<?php
$user = "XXXX";
$pwd = 'XXXX';
$filter = [];
if (isset($_POST['needleID'])) {
$needleID = $_POST['needleID'];
$filter = ['id'=> $needleID];
}
//Manager Class
$connection = new MongoDB\Driver\Manager("mongodb://${user}:${pwd}#localhost:27017");
// Query Class
$query = new MongoDB\Driver\Query($filter);
// Output of the executeQuery will be object of MongoDB\Driver\Cursor class
$rows = $connection->executeQuery('sedwe.defaultConfig', $query);
// Convert rows to Array and sedn result back to client
$rowsArr = $rows->toArray();
echo json_encode($rowsArr);
?>

Zend Pdo_Mysql LOAD DATA forbidden

I have been looking for a solution that allows load data queries with zend framework like:
LOAD XML LOCAL INFILE '$dbFile' INTO TABLE mytable ROWS IDENTIFIED BY '<object>';
When I try to execute this query, i get the following error:
Warning: PDO::exec() [pdo.exec]: LOAD DATA LOCAL INFILE forbidden
However if I output the query and copy/paste it into an editor like HeidiSQL the query works.
I searched for an answer and found that I should set the driver option PDO::MYSQL_ATTR_LOCAL_INFILE but it does not seem to work.
I would like to use application.ini to set the driver option:
resources.multidb.mydb.adapter = "Pdo_Mysql"
resources.multidb.mydb.dbname = "mydb"
resources.multidb.mydb.username = "myuser"
resources.multidb.mydb.password = "mypass"
resources.multidb.mydb.driver_options.PDO::MYSQL_ATTR_LOCAL_INFILE = true
resources.multidb.mydb.driver_options.1001 = true
I tried it the following way too but got the same error:
$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', 'testing');
$dbParams = $config->resources->multidb->mydb->toArray();
$dbParams['driver_options'] = array(PDO::MYSQL_ATTR_LOCAL_INFILE => '1');
$db = Zend_Db::factory($config->resources->multidb->mydb->adapter, $dbParams);
Am I overlooking something? Or maybe setting the options wrong? I also read that mysql must be compiled with --enable-load-data or something but the query works with an sql editor so it should work through php.
I found an interesting implementation of local infiles in the Rend (Rapid Zend) Framework.
Basically, the file has a class for the PDO object and has a method like this:
/**
* Set the local infile flag
*
* #param boolean $allowLocalInfile
* #return Rend_Factory_Database_Pdo_Mysql
*/
public function setAllowLocalInfile($allowLocalInfile)
{
$this->_options["driver_options"][PDO::MYSQL_ATTR_LOCAL_INFILE] = $allowLocalInfile;
return $this;
}
I'm sure some more browsing in that open source repository would reveal some tricks to solve your problem.

Possible for PHP app built on top of codeigniter to connect to a MySQL AND a mongoDB database at the same time?

I have a web application built in codeigniter and hosted with cloudcontrol. I use a normal MySQL database for all of my data persistance, and now I want to use a mongodb database in addition to the MySQL database.
I want to use mongodb as a job queue to persist messages between my workers and my application servers. I've gotten the inspiration to do this from this tutorial: http://www.captaincodeman.com/2011/05/28/simple-service-bus-message-queue-mongodb/
Is this possible (using two different types of databases simultaniously -- with/without hacking codeigniter, I would assume it is)
Any tips for accomplishing this?
---- EDIT ----
I've included this library in my CI project:
https://github.com/alexbilbie/codeigniter-mongodb-library
And when I attempt to load it via: $this->load->library('mongo_db');
I run into this:
I'm not sure how I can get mysql and mongodb working together...
---- EDIT ----
Nevermind my above question, I improperly set up the config file and confused the error...
Yes this is possible, out of the box.
You need to define two groups in your config, one for mysql and one for mongodb. In your application you can then load in these databases by group name.
In your confugration.php:
$db['mysql']['hostname'] = "localhost";
$db['mysql']['username'] = "root";
$db['mysql']['password'] = "";
$db['mysql']['dbdriver'] = "mysql";
//... (full config omitted for brevity)
$db['mongodb']['hostname'] = "localhost";
$db['mongodb']['username'] = "root";
$db['mongodb']['password'] = "";
$db['mongodb']['dbdriver'] = "mongodb";
//... (full config omitted for brevity)
And then you would load in your databases as follows:
$mysqlDB = $this->load->database('mysql', TRUE);
$mongoDB = $this->load->database('mongodb', TRUE);
Take a look at the user guide on how to connect to multiple databases and on how to specify configuration groups.

Categories