Resource Permissions Based on Admin Flags

I am creating a Flask-Admin application that requires checking permissions to view, edit, and delete specific rows in a table.

ie, I would like to:

  • A list of only rows where the user id matches the row owner id
  • Let the user create a string if it has a specific role
  • Allow the user to edit the line if it has a specific role.

I can think of overriding the query (), on_model_change (), etc. methods to check for edit permission, but:

  • The user can still view the string by changing the URL to display the edit screen
  • I don’t know how to limit the WTForms one-to-many editing list to only allowed items

How can i achieve this?

+4
source share
1 answer

A quick and dirty solution to my problem:

1. Create a generic function to verify ownership in the ModelView class

def is_owned(self, id):
    model = db.session.query(self.model).filter(self.model.id == id).all()
    if len(model) == 0:
        return False
    else:
        model = model[0]
    if model.user_id == current_user.id:
        return True
    return False

2. Override the ModelView methods on_model_change, on_form_prefill, on_model_delete, get_query and get_count_query to verify ownership (user_id = current_user.id):

def on_model_change(self, form, model, is_created):
    if not self.is_owned(model.id):
        abort(403)

def on_form_prefill(self, form, id):
    if not self.is_owned(id):
        abort(403)

def on_model_delete(self, model):
    if not self.is_owned(model.id):
        abort(403)

def get_query(self):
    return super(Tables, self).get_query().filter(self.model.user_id == current_user.id)

def get_count_query(self):
    return super(Tables,self).get_count_query().filter(self.model.user_id == current_user.id)
+3
source

All Articles