TypeScript makes it easy to eliminate potential sources of error. We’ve been using some simple techniques to do this with permissions checking.

One of the advantages of TypeScript is how its rich type system enables you to leverage the language to eliminate potential sources of error. On a few recent projects with nontrivial authorization needs, we’ve been using some simple techniques to do this with permissions checking and enforcement.

Scott Wlaschin documented the heart of the technique in his great blog, F## for Fun and Profit. Scott shows how you can create types that represent access tokens for particular permissions. Then the services that perform potentially unauthorized operations require a value of that type to perform the operation.

For example, let’s say our application has general system settings that only administrators can change. We might have a function in our service layer that looks something like this:

// Service layer / business logic layer
function updateSystemSettings(
  permission: PermissionToChangeSystemSettings,
  newSettings: SystemSettings
) {
  //....
}

By having a type represent permission to perform the operation and requiring a value of that type to perform the operation, we’ve got an API that’s impossible to accidentally call in a context where you haven’t proved you have that permission.

We’ve got a simple pattern and some lightweight support code for implementing this model in typescript — code and examples on GitHub. At a high level, we do the following:

  1. Define specific permissions as types using the Single-Valued Type pattern.
  2. Have routines in our service layer take values of the corresponding permission type as an argument.
  3. Define an “authorizer” that provides permission-checker functions that attempt to produce a value of the requested permission type and fail if the request isn’t authorized.
  4. API endpoints such as GraphQL resolvers or HTTP handlers request permissions from the authorizer and use them to invoke service layer business logic.

#typescript #javascript #angular #web-development

Techniques for Modeling Permissions as Types in Typescript
2.65 GEEK