Skip to content

Access Control

Thomas Pollet edited this page Jul 21, 2020 · 20 revisions

Application-Wide Access Control

You can implement application-wide access control using the flask before_request decorator.

Class-Level Access Control

Access control can be enforced on the API endpoints by means of function decorators that will be applied to the API endpoints of the class where the decorators are declared. This is demonstrated in this example. In this example we add the flask-httpauth login_required decorator to the decorators list of the User class:

class User(SAFRSBase, db.Model):
    """
        description: Protected user resource
    """

    __tablename__ = "users"
    id = db.Column(db.String(32), primary_key=True)
    username = db.Column(db.String(32))
    # The custom_decorators will be applied to all API endpoints
    decorators = [auth.login_required]

We create a simplistic verify_password function to verify the username and password sent in the Authorization header

@auth.verify_password
def verify_password(username_or_token, password):
    # Implement your authentication here
    if username_or_token == "user" and password == "pass":
        return True

    return False

The decorators can be customized, this example shows a custom decorator where authentication is only required for specific HTTP methods. These decorators are also applied to the relationships exposed by the class objects.

Access Control for Attributes and Relationships

More granular access control for attributes can be implemented

  • by overriding the _s_check_perms method
  • by overriding the _s_post and _s_patch methods (HTTP methods)
  • in the class __init__ constructror for post requests
  • in the orm.reconstructor for patch requests
  • in the to_dict json serialization method
  • using a custom SQLAlchemy column type

Access control for relationships can be implemented

  • in the relationship target classes.
  • by overriding _s_relationships
  • by overriding _s_get_related