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 thesqlalchemy_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.
sqlalchemy_oso_cloud.orm function | corresponding sqlalchemy.orm function | fact configured |
---|---|---|
relation | relationship | has_relation |
remote_relation | mapped_column | has_relation |
attribute | mapped_column | has_<name> (is_<name> if boolean) |
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
Usesqlalchemy_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.
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 viasqlalchemy_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 legacyQuery
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.
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.
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: