Techniques for Modeling Permissions as Types in Typescript

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

What is GEEK

Buddha Community

Techniques for Modeling Permissions as Types in Typescript

Techniques for Modeling Permissions as Types in Typescript

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

Arvel  Parker

Arvel Parker

1593156510

Basic Data Types in Python | Python Web Development For Beginners

At the end of 2019, Python is one of the fastest-growing programming languages. More than 10% of developers have opted for Python development.

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Table of Contents  hide

I Mutable objects

II Immutable objects

III Built-in data types in Python

Mutable objects

The Size and declared value and its sequence of the object can able to be modified called mutable objects.

Mutable Data Types are list, dict, set, byte array

Immutable objects

The Size and declared value and its sequence of the object can able to be modified.

Immutable data types are int, float, complex, String, tuples, bytes, and frozen sets.

id() and type() is used to know the Identity and data type of the object

a**=25+**85j

type**(a)**

output**:<class’complex’>**

b**={1:10,2:“Pinky”****}**

id**(b)**

output**:**238989244168

Built-in data types in Python

a**=str(“Hello python world”)****#str**

b**=int(18)****#int**

c**=float(20482.5)****#float**

d**=complex(5+85j)****#complex**

e**=list((“python”,“fast”,“growing”,“in”,2018))****#list**

f**=tuple((“python”,“easy”,“learning”))****#tuple**

g**=range(10)****#range**

h**=dict(name=“Vidu”,age=36)****#dict**

i**=set((“python”,“fast”,“growing”,“in”,2018))****#set**

j**=frozenset((“python”,“fast”,“growing”,“in”,2018))****#frozenset**

k**=bool(18)****#bool**

l**=bytes(8)****#bytes**

m**=bytearray(8)****#bytearray**

n**=memoryview(bytes(18))****#memoryview**

Numbers (int,Float,Complex)

Numbers are stored in numeric Types. when a number is assigned to a variable, Python creates Number objects.

#signed interger

age**=**18

print**(age)**

Output**:**18

Python supports 3 types of numeric data.

int (signed integers like 20, 2, 225, etc.)

float (float is used to store floating-point numbers like 9.8, 3.1444, 89.52, etc.)

complex (complex numbers like 8.94j, 4.0 + 7.3j, etc.)

A complex number contains an ordered pair, i.e., a + ib where a and b denote the real and imaginary parts respectively).

String

The string can be represented as the sequence of characters in the quotation marks. In python, to define strings we can use single, double, or triple quotes.

# String Handling

‘Hello Python’

#single (') Quoted String

“Hello Python”

# Double (") Quoted String

“”“Hello Python”“”

‘’‘Hello Python’‘’

# triple (‘’') (“”") Quoted String

In python, string handling is a straightforward task, and python provides various built-in functions and operators for representing strings.

The operator “+” is used to concatenate strings and “*” is used to repeat the string.

“Hello”+“python”

output**:****‘Hello python’**

"python "*****2

'Output : Python python ’

#python web development #data types in python #list of all python data types #python data types #python datatypes #python types #python variable type

Christa  Stehr

Christa Stehr

1599315360

Nominal typing in Typescript

Nominal & structural typing

Type systems are typically categorized as either structural or nominal. Languages like Java and Scala have primarily nominal type systems, whereas a language like Typescript has a structural type system. Let’s take a brief look at both systems.

Nominal Typing

In a nominal typing system, type compatibility is checked using the name of the types. If they do not have the same name, then they are not compatible; end of story. **If **Typescript had a nominal typing system the type check for the last line would fail:

Image for post

Structural typing

Typescript uses structural typing to decide whether two types are compatible with one another or not. What do we mean by structural typing? Well, let’s consider the following code snippet:

Image for post

To determine whether the type of the constant color(RGBA) is compatible with the type of serializeColor’s parameter x(RGB) the type system must verify that each member of RGB has a corresponding compatible member in RGBA. In this case, RGB has a single member color for which RGBA has a corresponding member with the same type — [number, number, number] — and so it passes the type check. Notice how the type system ignores the additional members that exist on RGBA (alpha).

#typescript #type-safe #type-systems

Carmen  Grimes

Carmen Grimes

1599326160

Reflecting business logic rules into the domain models using typescript — Part 3

In the previous article, we declare types and create a function to make and validate the type.

But it will take too much time if we want to create these functions and validators for each model we want to use.

In this article, we are going to use io-ts library to automate these boring tasks.

The final project is available here:

mohsensaremi/reflecting-business-logic-rules-into-the-domain-models

Contribute to mohsensaremi/reflecting-business-logic-rules-into-the-domain-models development by creating an account on…

github.com

Installation

yarn add io-ts fp-ts

So what is fp-ts ?

fp-ts is a functional programming utility for typescript and is a peer dependency for io-ts .

We are not going to talk about functional programming in this article.

We only discuss a little about Either monad.

Codec

io-ts represent our type with something called Codec.

A codec has decode and encode functions.

We create and validate our input data with decode function and put back the data in normal shape using encode function.

#domain-modeling #typescript #business-logic #domain-driven-design #domain-model

Carmen  Grimes

Carmen Grimes

1599329880

Reflecting business logic rules into the domain models using typescript — Part 2

In the previous article, we learned how to create self-documented types and models. but they were just types and didn’t have any functionality.

In this article, we are going to write some code that creates and validates those types.

At the end of this article, our types can be used in real-life projects.

The project source code is available here:

mohsensaremi/reflecting-business-logic-rules-into-the-domain-models

Contribute to mohsensaremi/reflecting-business-logic-rules-into-the-domain-models development by creating an account on…

github.com

Bootstrap

First, we need a typescript project. so let’s create it.

yarn init -y
yarn add --dev typescript ts-node
./node_modules/.bin/tsc --init

Then we create our types.

String50

import {CustomTypeError} from "../exception/CustomTypeError";

	export type String50 = {
	    kind: "String50",
	    value: string,
	}

	export const makeString50 = (arg: any): String50 => {
	    if (typeof arg === "string" && arg.length <= 50) {
	        return {
	            kind: "String50",
	            value: arg,
	        };
	    }
	    throw new CustomTypeError("String50", arg);
	}

At the top, there is the type declaration. after that, there is the makeString50function. this function accepts any argument and tries to create String50 .

It checks if the argument type is a string and its length is less than 50.

If the argument doesn’t satisfy the rules and constraint it will throw a CustomTypeError exception.

And here is CustomTypeError

export class CustomTypeError extends Error {
	    constructor(type: string, value: any) {
	        super(`invalid value ${JSON.stringify(value)} provided for type ${type}`);
	    }
	}

It is just a simple class for showing errors.

We use it in try catch blocks to handle our custom type errors.

Let’s continue to define other types.

#domain-driven-design #business-logic #typescript #domain-modeling #domain-model