0

I have a model called Account. Registered users in the ab_user table can be associated with M accounts. The model looks like this:

class Account(Model, AuditMixin):
    __tablename__ = "accounts"
    id = Column(Integer)
    user_id = Column(Integer, ForeignKey("ab_user.id"))
    user = relationship("User" , primaryjoin="Account.user_id == User.id")
    name = Column(String(140))

    def __str__(self):
        return self.name

As a default, a user who logs into the application can list all accounts regardless of who's user_id is associated with the account.

I created a simple filter to find the associated records and return them. The filter looks like this:

class OwnerFilter(BaseFilter):
    """
    Lists results with the following criteria:

    1. The account.user_id matches the current user
    """
    
    def apply(self, query: Query, value: Any) -> Query:
        return query.filter(self.model.user == g.user)

And the AccountModelView:

class AccountModelView(ModelView):
    datamodel = SQLAInterface(Account)
    list_columns = ["identifier", "alias", "brokerage.name"]
    add_columns = ["identifier", "alias", "brokerage"]
    edit_columns = ["identifier", "alias", "brokerage"]

    base_filters = [["user_id", OwnerFilter, ""]]

Given I need to add this filter to every view (or a base class), it seems risky given such an important security consideration and the robust security mechanisms in AppBuilder. I feel like I'm missing something.

Is this the correct way to only view records of the logged in user?

Jason Strimpel
  • 14,670
  • 21
  • 76
  • 106

1 Answers1

0

You can create your own custom security class. Refer to the documentation here https://flask-appbuilder.readthedocs.io/en/latest/security.html#your-custom-security

Lenin
  • 303
  • 2
  • 3