[英]create authentication sub-user in flask-pymongo
I've a flask web app in which I authenticate to the "core" DB as admin. 我有一个Flask Web应用程序,在该应用程序中,我以管理员身份验证了“核心”数据库。
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? 如何配置flask来管理它? 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.