简体   繁体   中英

create authentication sub-user in flask-pymongo

I've a flask web app in which I authenticate to the "core" DB as admin.

MONGO_URI = "mongodb://myUserAdmin:abc123@localhost:27017/test?authSource=admin"
mongo = PyMongo(app)
# ... and I am able to interact with the DB
    flash(mongo.db.user.find_one())

now, I want to create sub-DBs for each user of the app and let him modify only its specific DB (or table). How can I configure flask to manage that? I tried to look in web but found no solutions.

Thanks in advance for any help!

You can do something like this

Create Authentication middleware

class UserAuthenticationMiddleware:

    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        '''
            Authenticate the user here
        '''
        self.app.user = {'_id': ObjectId('ddddddddssssssssssss')} #  authenticate the user and get it from db
        return self.app(environ, start_response)

Then create a Database middleware to get a db for the user

class DbMiddleware(object):
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        if hasattr(self.app, 'user'):

            # create a database by user id or you can use any unique field here
            self.app.db = self.app.db_client[str(self.app.user._id)]
        else:
            self.app.db = self.app.db_client['default_db']
        return self.app(environ, start_response)

Then in create app instance

from flask import Flask


if __name__ == '__main__':
    app = Flask(__name__)
    app.db_client = MongoClient() 
    app = DbMiddleware(UserAuthenticationMiddleware(app))
    app.run()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM