Using Bitwise Operators To Handle Permissions in GO

Written by d8me | Published 2020/05/08
Tech Story Tags: golang | permissions | coding | golang-permissions-handling | handling-permissions-in-golang | bitwise-operator-for-golang | latest-tech-stories | hackernoon-top-story

TLDR 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.via the TL;DR App

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.

Published by HackerNoon on 2020/05/08