Skip to content

Commit 602331d

Browse files
committed
Pass credentials as MongoClient option, check issue mongodb#22 for more information.
1 parent b01a972 commit 602331d

File tree

1 file changed

+35
-16
lines changed

1 file changed

+35
-16
lines changed

Diff for: src/Jenssegers/Mongodb/Connection.php

+35-16
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,16 @@ class Connection extends \Illuminate\Database\Connection {
2727
*/
2828
public function __construct(array $config)
2929
{
30-
// Store configuration
3130
$this->config = $config;
3231

33-
// Check for connection options
32+
// Build the connection string
33+
$dsn = $this->getDsn($config);
34+
35+
// You can pass options directly to the MogoClient constructor
3436
$options = array_get($config, 'options', array());
3537

36-
// Create connection
37-
$this->connection = new MongoClient($this->getDsn($config), $options);
38+
// Create the connection
39+
$this->connection = $this->createConnection($dsn, $config, $options);
3840

3941
// Select database
4042
$this->db = $this->connection->{$config['database']};
@@ -95,6 +97,31 @@ public function getMongoClient()
9597
return $this->connection;
9698
}
9799

100+
/**
101+
* Create a new MongoClient connection.
102+
*
103+
* @param string $dsn
104+
* @param array $config
105+
* @param array $options
106+
* @return MongoClient
107+
*/
108+
protected function createConnection($dsn, array $config, array $options)
109+
{
110+
// Add credentials as options, this make sure the connection will not fail if
111+
// the username or password contains strange characters.
112+
if (isset($config['username']) && $config['username'])
113+
{
114+
$options['username'] = $config['username'];
115+
}
116+
117+
if (isset($config['password']) && $config['password'])
118+
{
119+
$options['password'] = $config['password'];
120+
}
121+
122+
return new MongoClient($dsn, $options);
123+
}
124+
98125
/**
99126
* Create a DSN string from a configuration.
100127
*
@@ -120,17 +147,9 @@ protected function getDsn(array $config)
120147
}
121148
}
122149

123-
// Credentials
124-
if (isset($config['username']) and isset($config['password']))
125-
{
126-
$credentials = "{$username}:{$password}@";
127-
}
128-
else
129-
{
130-
$credentials = '';
131-
}
132-
133-
return "mongodb://{$credentials}" . implode(',', $hosts) . "/{$database}";
150+
// The database name needs to be in the connection string, otherwise it will
151+
// authenticate to the admin database, which may result in permission errors.
152+
return "mongodb://" . implode(',', $hosts) . "/{$database}";
134153
}
135154

136155
/**
@@ -145,4 +164,4 @@ public function __call($method, $parameters)
145164
return call_user_func_array(array($this->db, $method), $parameters);
146165
}
147166

148-
}
167+
}

0 commit comments

Comments
 (0)