paint-brush
Using Bitwise Operators To Handle Permissions in GOby@d8me
1,852 reads
1,852 reads

Using Bitwise Operators To Handle Permissions in GO

by AkshitMay 8th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Using Bitwise Operators To Handle Permissions in GO, I stumbled across a very interesting approach to give permissions (or roles) to users in the system. The idea is to have each bit in a binary sequence denote a permission, similar to how chmod number permission works. In this way we can store multiple permissions in a single byte. To verify the permissions, we can just do an AND operation and check the value with the permission. The output of the snippet above is: IsDevOps? true IsDev Ops? True IsDevops: true IsAdmin? True isDevOps.

Coin Mentioned

Mention Thumbnail
featured image - Using Bitwise Operators To Handle Permissions in GO
Akshit HackerNoon profile picture

Few days ago, I stumbled across a very interesting approach to give permissions (or roles) to users in the system.

Say, you have to give multiple permissions to user logged into your system. How do you plan on doing that? I remember, handling this problem in a very different way with user having many to many permissions field. There can be various approaches to this.

Let me share an interesting approach using the bitwise operator. So the idea is to have each bit in a binary sequence denote a permission, similar to how chmod number permission works. Let look at the code below in golang.

package main

import (
	"fmt"
)

const (
	isAdmin = 1 << iota
	isDev
	isDevOps
)

func main() {
	fmt.Printf("Admin: %b\n", isAdmin)
	fmt.Printf("Dev: %b\n", isDev)
	fmt.Printf("Devops: %b\n", isDevOps)
	
	var role byte = isDev | isAdmin	

	fmt.Printf("IsDev? %v\n", role & isDev == isDev)	
	fmt.Printf("IsAdmin? %v\n", role & isAdmin == isAdmin)
	fmt.Printf("IsDevOps? %v\n", role & isDevOps == isDevOps)
}

The output of the snippet above is:

Admin: 1
Dev: 10
Devops: 100
IsDev? true
IsAdmin? true
IsDevOps? false

Let see how this works. We initialise 3 constants

isAdmin
,
isDev
and
isDevOps
with binary values 001, 010 and 100 respectively. Then we define a variable role of type byte and initialise it to a bitwise OR operation on isDev and isAdmin. So after OR operation, role has the value of 011. In this way we can store multiple permissions in a single byte.

To verify the permissions, we can just do an AND operation and check the value with the permission. Example,

role: 011 ( Admin and Dev )
Checking for dev( 010 ) in role,
011 (role) & 010 (dev) -> 010 which is value for dev. 
Implying that, role contains dev permission.

The idea isn't limited to the permissions only. There could be many use cases. But I personally loved this approach.