pythonflaskflask-appbuilder

flask app builder user should see only own content


Hi i want that the user is only seeing it's own content which was created by themself. In flask i created a user table and every other table as a reference to the table. So when the view is called i filter for the current user and only show the entries for the user. I now checked out flask app builder and it has some nice user management but it seems that it has nothing like i need.

My solution would be: Create a reference from my table to the user table and do it like i did it with plain flask. I am just wondering if there is a better way to do this and maybe there is allready something in appbuilder what i have to activate but don't see yet.

my flask solution:

this is what i add to the model

user_id = db.Column(db.Integer, db.ForeignKey('user.id')) 

this is how i query it in the routes

articles_pos = ArticlePos.query.filter_by(user_id=current_user.id)

thanks in advance


Solution

  • A solution can be found in the examples of fab itself. see https://github.com/dpgaspar/Flask-AppBuilder/tree/master/examples/extendsecurity

    in my particular case i made the following changes

    in the model i adde the follwoing:

    class MyUser(User):
        __tablename__ = "ab_user"
    

    and in the class where i reference the user table

    user = relationship("MyUser")
    
    user_id = Column(Integer, ForeignKey('ab_user.id'), default=get_user_id, nullable=False)
    

    you still need the the function:

    @classmethod
        def get_user_id(cls):
            try:
                return g.user.id
            except Exception:
                return None