Commit b16b929a authored by Jens Segers's avatar Jens Segers

Pass credentials as MongoClient option, check issue #22 for more information.

parent d27f0691
...@@ -27,14 +27,16 @@ class Connection extends \Illuminate\Database\Connection { ...@@ -27,14 +27,16 @@ class Connection extends \Illuminate\Database\Connection {
*/ */
public function __construct(array $config) public function __construct(array $config)
{ {
// Store configuration
$this->config = $config; $this->config = $config;
// Check for connection options // Build the connection string
$dsn = $this->getDsn($config);
// You can pass options directly to the MogoClient constructor
$options = array_get($config, 'options', array()); $options = array_get($config, 'options', array());
// Create connection // Create the connection
$this->connection = new MongoClient($this->getDsn($config), $options); $this->connection = $this->createConnection($dsn, $config, $options);
// Select database // Select database
$this->db = $this->connection->{$config['database']}; $this->db = $this->connection->{$config['database']};
...@@ -95,6 +97,31 @@ class Connection extends \Illuminate\Database\Connection { ...@@ -95,6 +97,31 @@ class Connection extends \Illuminate\Database\Connection {
return $this->connection; return $this->connection;
} }
/**
* Create a new MongoClient connection.
*
* @param string $dsn
* @param array $config
* @param array $options
* @return MongoClient
*/
protected function createConnection($dsn, array $config, array $options)
{
// Add credentials as options, this make sure the connection will not fail if
// the username or password contains strange characters.
if (isset($config['username']) && $config['username'])
{
$options['username'] = $config['username'];
}
if (isset($config['password']) && $config['password'])
{
$options['password'] = $config['password'];
}
return new MongoClient($dsn, $options);
}
/** /**
* Create a DSN string from a configuration. * Create a DSN string from a configuration.
* *
...@@ -120,17 +147,9 @@ class Connection extends \Illuminate\Database\Connection { ...@@ -120,17 +147,9 @@ class Connection extends \Illuminate\Database\Connection {
} }
} }
// Credentials // The database name needs to be in the connection string, otherwise it will
if (isset($config['username']) and isset($config['password'])) // authenticate to the admin database, which may result in permission errors.
{ return "mongodb://" . implode(',', $hosts) . "/{$database}";
$credentials = "{$username}:{$password}@";
}
else
{
$credentials = '';
}
return "mongodb://{$credentials}" . implode(',', $hosts) . "/{$database}";
} }
/** /**
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment