Skip to content

Commit

Permalink
authenticate against 'admin' db unless a specific DB is provided
Browse files Browse the repository at this point in the history
fixes #82 and #54
  • Loading branch information
dcrosta committed May 22, 2017
1 parent 600bf49 commit ab0fee2
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
18 changes: 13 additions & 5 deletions flask_pymongo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,15 @@ def init_app(self, app, config_prefix='MONGO'):
def key(suffix):
return '%s_%s' % (config_prefix, suffix)

auth_database = 'admin'

if key('URI') in app.config:
# bootstrap configuration from the URL
parsed = uri_parser.parse_uri(app.config[key('URI')])
if not parsed.get('database'):
raise ValueError('MongoDB URI does not contain database name')
app.config[key('DBNAME')] = parsed['database']
if parsed.get('database') is not None:
auth_database = parsed['database']

app.config[key('DBNAME')] = parsed.get('database') or app.name
app.config[key('READ_PREFERENCE')] = parsed['options'].get('readpreference')
app.config[key('USERNAME')] = parsed['username']
app.config[key('PASSWORD')] = parsed['password']
Expand Down Expand Up @@ -159,6 +162,9 @@ def key(suffix):
host = app.config[key('URI')]

else:
if key('DBNAME') in app.config:
auth_database = app.config[key('DBNAME')]

app.config.setdefault(key('HOST'), 'localhost')
app.config.setdefault(key('PORT'), 27017)
app.config.setdefault(key('DBNAME'), app.name)
Expand Down Expand Up @@ -270,8 +276,10 @@ def key(suffix):
if any(auth):
auth_source = app.config[key('AUTH_SOURCE')]
auth_mechanism = app.config[key('AUTH_MECHANISM')]
db.authenticate(username, password, source=auth_source,
mechanism=auth_mechanism)
auth_db = cx[auth_database]
auth_db.logout()
auth_db.authenticate(username, password, source=auth_source,
mechanism=auth_mechanism)

app.extensions['pymongo'][config_prefix] = (cx, db)
app.url_map.converters['ObjectId'] = BSONObjectIdConverter
Expand Down
2 changes: 2 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from util import FlaskRequestTest, FlaskPyMongoTest

import time
import unittest

import pymongo
import flask
Expand Down Expand Up @@ -159,6 +160,7 @@ def test_uri_prioritised_over_host_and_port(self):
assert mongo.cx.port == 27017
assert mongo.db.name == 'database_name'

@unittest.skip("this should really be a test about auth'ing against admin")
def test_uri_without_database_errors_sensibly(self):
self.app.config['MONGO_URI'] = 'mongodb://localhost:27017/'
self.assertRaises(ValueError, flask_pymongo.PyMongo, self.app)
Expand Down

0 comments on commit ab0fee2

Please sign in to comment.