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:
#typescript #javascript #angular #web-development