@@ -193,5 +193,57 @@ def test_uri_options(self):
193193 self .assertTrue (client .pymongo_test .command ('dbstats' ))
194194
195195
196+ class TestDelegatedAuth (unittest .TestCase ):
197+
198+ def setUp (self ):
199+ self .client = MongoClient (host , port )
200+ if not version .at_least (self .client , (2 , 4 , 0 )):
201+ raise SkipTest ('Delegated authentication requires MongoDB >= 2.4.0' )
202+ if not server_started_with_auth (self .client ):
203+ raise SkipTest ('Authentication is not enabled on server' )
204+ # Give admin all priviledges.
205+ self .client .admin .add_user ('admin' , 'pass' ,
206+ roles = ['readAnyDatabase' ,
207+ 'readWriteAnyDatabase' ,
208+ 'userAdminAnyDatabase' ,
209+ 'dbAdminAnyDatabase' ,
210+ 'clusterAdmin' ])
211+
212+ def tearDown (self ):
213+ self .client .admin .authenticate ('admin' , 'pass' )
214+ self .client .pymongo_test .system .users .remove ()
215+ self .client .pymongo_test2 .system .users .remove ()
216+ self .client .pymongo_test2 .foo .remove ()
217+ self .client .admin .system .users .remove ()
218+ self .client .admin .logout ()
219+
220+ def test_delegated_auth (self ):
221+ self .client .admin .authenticate ('admin' , 'pass' )
222+ self .client .pymongo_test2 .foo .remove ()
223+ self .client .pymongo_test2 .foo .insert ({})
224+ # User definition with no roles in pymongo_test.
225+ self .client .pymongo_test .add_user ('user' , 'pass' , roles = [])
226+ # Delegate auth to pymongo_test.
227+ self .client .pymongo_test2 .add_user ('user' ,
228+ userSource = 'pymongo_test' ,
229+ roles = ['read' ])
230+ self .client .admin .logout ()
231+ self .assertRaises (OperationFailure , self .client .pymongo_test2 .foo .find_one )
232+ # Auth must occur on the db where the user is defined.
233+ self .assertFalse (self .client .pymongo_test2 .authenticate ('user' , 'pass' ))
234+ # Auth directly
235+ self .assertTrue (self .client .pymongo_test .authenticate ('user' , 'pass' ))
236+ self .assertTrue (self .client .pymongo_test2 .foo .find_one ())
237+ self .client .pymongo_test .logout ()
238+ self .assertRaises (OperationFailure , self .client .pymongo_test2 .foo .find_one )
239+ # Auth using source
240+ self .assertTrue (self .client .pymongo_test2 .authenticate (
241+ 'user' , 'pass' , source = 'pymongo_test' ))
242+ self .assertTrue (self .client .pymongo_test2 .foo .find_one ())
243+ # Must logout from the db authenticate was called on.
244+ self .client .pymongo_test2 .logout ()
245+ self .assertRaises (OperationFailure , self .client .pymongo_test2 .foo .find_one )
246+
247+
196248if __name__ == "__main__" :
197249 unittest .main ()
0 commit comments