Skip to main content

Extract a Piece of Authorization Logic

Identify the logic to extract

First, select a piece of authorization logic to move to Oso Cloud. For your section of logic should be:
  • Well understood
  • Low-impact
  • Straightforward to extract
In this guide, the process of migration to local authorization is illustrated with code samples from a hypothetical version control application. You can follow along with those or you use examples from your code. One permission this version control application requires is the ability to read a repository. That permission affects two operations:
  1. read a single repository
  2. list all the repositories that the user can read
The logic resides in the corresponding get handlers:
This is typical of authorization code:
  • The same logic is implemented in multiple places
  • The implementation slightly differs in each place
  • It is not obvious it is critical authorization logic
This is a good candidate for early refactoring:
  • The logic is straightforward - a user can read a repository if:
    • They have any role on the repository
    • They have any role on the repository’s parent organization
  • It only grants read access.
  • The logic is already encapsulated.

Extract the logic into a dedicated function

With a piece of logic to refactor identified, extract it into a dedicated function. This decouples the authorization logic from the surrounding application logic. Create a function called canReadRepo() in a new file called authz.ts. That makes it obvious which permission it governs.
src/authz.ts
Now you call this function when you authorize a user’s request to read a repository.
src/routes/accounts.ts
src/routes/accounts.ts
Even this change provides meaningful benefits:
  • A dedicated file for authorization logic (src/authz.ts).
  • The logic for the “read repository” permission is easy to find, understand, and reason about.
  • The logic is defined only once.
  • The application code is cleaner.
Next, implement the logic in Oso Cloud.