1

I have a Flask application that uses pymongo to access a mongo database and satisfy users' requests. I have enabled access control in Mongo and now there are several users associated with different roles. More specifically, each user has read-write privileges only in a specific subset of collections in the db.

I would like to have users logging into the application and having access only to their specific subset of collections. This means that each user request that needs to fetch some data from the db is binded to a (specific) db-authenticated connection.

The main extensions of flask like flask-login and flask-security do not seem to use MongoDB own authentication mechanism.

Have been looking for a while now but I was not able to solve this.

user9342787
  • 201
  • 2
  • 5

2 Answers2

1

As per MongoDB documentation for making connection string.

mongodb://[username:password@]host1[:port1][,...hostN[:portN]]][/[database][?options]]

or

mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017/admin

you can connect to MongoDB using PyMongo library.

from pymongo import MongoClient
from flask import Flask, request

app = Flask(__name__)

@app.route('/login')
def login():
    data = request.get_json()
    username = data['username']
    password = data['password']
    database = data['database']
    uri = 'mongodb://'+username+':'+password+'@localhost:27017/'+database
    print(uri) 
    app.config['uri'] = uri


@app.route('/some_endpoint')
def do_some_work():
    uri = app.config['uri']
    client = MongoClient(uri)
    # now use this as per your requirement.       

    client.close() 

if __name__ == '__main__':
    app.run()

this is just an example. you can store it in app.config and use it as you want.

Another reference that you might want to see.

0

You might want to reconsider that approach as opening a new db connection with each user that logs into your app might not scale very well, since Mongo creates a new thread for each new connection.

See: mongodb-max-connections

I would consider some RBAC for flask like flask-security.

grafuls
  • 311
  • 5
  • 8
  • Thanks for your comment. I do agree with you that the solution does not scale well. I also understand that typically you only create one MongoClient and use it throughout your application. My concern is that I do not see how these design principle can coexist with MongoDB's own RBAC. – user9342787 Jun 03 '19 at 07:33