Skip to main content
Our open-source integration for SQLAlchemy provides ORM-native support for Local Authorization.

Modeling

The SQLAlchemy integration automatically figures out your Local Authorization configuration from annotations on your models, so you can specify your facts entirely within the ORM. Use the sqlalchemy_oso_cloud.orm.Resource mixin to specify that a model corresponds to an authorization resource, and use the other functions in sqlalchemy_oso_cloud.orm to specify how properties correspond to facts. We use your model’s .id property as the resource ID, and use the model’s class name as the type. For example, the following SQLAlchemy models configure the facts:
  • has_relation(Folder:_, "organization", Organization:_)
  • is_public(Folder:_)
  • has_relation(Document:_, "folder", Folder:_)
  • has_status(Document:_, String:_)
Need a fact that isn’t covered by our functions? Open an issue and let us know.

Initialization

Use sqlalchemy_oso_cloud.init to initialize the integration. The function takes your SQLAlchemy model registry as its first argument, followed by any additional arguments you want to pass through when instantiating the Oso client.
You can access the underlying Oso API client by calling sqlalchemy_oso_cloud.get_oso(). This returns the same client instance that was created during initialization.

Usage

The simplest way to use the SQLAlchemy integration is via sqlalchemy_oso_cloud.select, our drop-in replacement for SQLAlchemy’s built-in select function. It adds a method .authorized(user, permission), which filters the results of the query to only include resources the user has permission for.

Using the Legacy Query API

For applications using SQLAlchemy’s legacy Query API we provide sqlalchemy_oso_cloud.Session, a drop-in replacement for SQLAlchemy’s Session class. Its .query(...) method provides queries extended with the .authorized(...) method.
sqlalchemy_oso_cloud.Session is simply a convenience wrapper that initializes a sqlalchemy.orm.Session with our custom sqlalchemy_oso_cloud.Query class. If you can’t use our Session class, you can extend your own sessions:

Maximum Vanilla

sqlalchemy_oso_cloud.authorized lets you add authorization to any SQLAlchemy Select or Query via the existing .options(...) method.

Using With Flask

sqlalchemy_oso_cloud.select is compatible with Flask-SQLAlchemy.
If you use Flask-SQLAlchemy with the legacy Query API, initialize SQLAlchemy with our custom Query class to get the .authorized(...) method:

Using With SQLModel

sqlalchemy_oso_cloud.select is compatible with SQLModel.
If you use SQLModel with the legacy Query API, you can either use our Session class (which is compatible with SQLModel), or initialize SQLModel’s Session with our custom Query class to get the .authorized(...) method:

Reference