DEV Community

Cover image for Build a Bitwise Permission System
Jannis
Jannis

Posted on • Updated on

 

Build a Bitwise Permission System

Permissions are everywhere and very important to secure your application from unauthorized actions and potential data loss.
A system to handle and combine permissions can be overwhelming and maybe too complex, but there's a better way called 🔐 Bitwise Permission System!

🛠 How to build your own

I will be doing this in JavaScript but the system is pretty much in every language possible.

Operators

Let's quickly discuss the bitwise operators. I'll give you a small overview here.

Bits is the unit 0 or 1. It's the smallest unit of data a computer can process and store.
For example you can convert the number 3 into bits which would be 110. I'm not going any deeper on bits, there's a lot of resources in the internet.

Example  Operator Name Description
1100 & 0100 = 0100 & AND Sets bit to 1 if both are 1
 1100 | 1000 = 1100 | OR Sets bit to 1 if one is 1
 0100 1010 = 1110 ^ XOR Sets bit to 1 if only one is 1
~0110 = 1001 ~ NOT Invert each bit

We are going to build a small project to check if a person is allowed to enter different areas in our headquarter.

First create our permissions for each area.

const DEFAULT = 1 // 0001
const LABORATORY = 2 // 0010
const CAFE = 4 // 0100
const PARK = 8 // 1000
Enter fullscreen mode Exit fullscreen mode

Next let's create three different users and give them some unique permissions. Do not use addition only OR operator! (Thanks to @naveennamani for correcting me)

const Elen = DEFAULT | CAFE // 0101
const Carl = DEFAULT | LABORATORY // 0011
const Jenny = DEFAULT | CAFE | PARK // 1101
Enter fullscreen mode Exit fullscreen mode

Here quickly some operations to change a person's permissions.

let Naveen = DEFAULT;
Naveen |= PARK; // add permission
Naveen ^= LABORATORY; // toggle permission
Naveen &= (~PARK); // remove permission
console.log(Naveen);  // 0011 (DEFAULT and LABORATORY)
Enter fullscreen mode Exit fullscreen mode

To check where each person has permission to access too we'll create a function that should return us an object with true or false for each area.

function checkPermissions(person) {
  // Default if you have no permissions
  var permissions = {
    default: false,
    laboratory: false,
    cafe: false,
    park: false,
  }

  // Person can enter the building
  if(person & DEFAULT) {
    permissions.default = true
  }

  // Person can enter the laboratory
  if(person & LABORATORY) {
    permissions.laboratory = true
  }

  // Person can enter the cafe
  if(person & CAFE) {
    permissions.cafe = true
  }

  // Person can enter the park
  if(person & PARK) {
    permissions.park = true
  }

  // Return permissions of this person
  return permissions
}
Enter fullscreen mode Exit fullscreen mode

To check if this worked let's print out the permissions of each persons.

const permsOfElen = checkPermissions(Elen)
console.log("Permissions of Elen: ", JSON.parse(permsOfElen))

const permsOfCarl = checkPermissions(Carl)
console.log("Permissions of Carl: ", JSON.parse(permsOfCarl))

const permsOfJenny = checkPermissions(Jenny)
console.log("Permissions of Jenny: ", JSON.parse(permsOfJenny))
Enter fullscreen mode Exit fullscreen mode

And here we have the correct output:

"Permissions of Elen: ", {
  default: true, // <--
  laboratory: false,
  cafe: true, // <--
  park: false
}
"Permissions of Carl: ", {
  default: true, // <--
  laboratory: true, // <--
  cafe: false,
  park: false
}
"Permissions of Jenny: ", {
  default: true, // <--
  laboratory: false,
  cafe: true, // <--
  park: true // <--
}
Enter fullscreen mode Exit fullscreen mode

Here's the Code!

 📍 Where can you use them

You can use bitwise permission systems in every application. It's fast because of binary and very easy to implement. Also the scalability of this system is to so easy and almost to infinite or let's say until you reached the limit of your datatype 😉.

You can use bitwise also for a role-based permission system where you give a role multiple permissions and then maybe only check for the role and not each permission 🤷‍♂️.

Me at AquaHubStudio will use this system in every application to authorize certain actions. Follow me on my journey of AquaHub!

🔥 Last words

Thanks for reading!
Don't hesitate to comment on tips or problems. I will respond to every comment with joy.

Support me

Top comments (20)

Collapse
 
naveennamani profile image
naveennamani

const naveen = DEFAULT + DEFAULT

Now I can enter LABORATORY

Collapse
 
jannisdev profile image
Jannis

That's not quite how it works and how you should do it in your application but technically yes 😂🔥

Collapse
 
naveennamani profile image
naveennamani

That's why you should use only bitwise OR when combining permissions instead of addition as you used in your example.

Thread Thread
 
jannisdev profile image
Jannis

Now i get what you exactly mean. I was also thinking about this but now I realized.
I will edit this! Thanks

Thread Thread
 
naveennamani profile image
naveennamani

Yes, that's what I mean. You only said about adding permissions. For removing and toggling them you can use following operations

let naveen = DEFAULT;
naveen |= PARK; // add permission
naveen ^= LABORATORY; // toggle permission
naveen &= (~PARK); // remove permission
console.log(naveen);  // should be 3 (0011)
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
jannisdev profile image
Jannis

Awesome I'll paste that in the post 👍

Collapse
 
zyabxwcd profile image
Akash

Woah, nice. Never thought permissions would be managed using such low level concepts when high level plug n play abstractions are the way to go these days. I would like to see implementations like these in other areas as well.

Collapse
 
jannisdev profile image
Jannis

Thank you a lot! In what areas would you prefer?

Collapse
 
zyabxwcd profile image
Akash

Not sure but I can give you a rough idea. When I was talking about low level concepts, I was talking about concepts included in OS design (drivers, interfaces, paging, separation of concerns by layering), computer architecture and programming language basics. Bitwise operators is one such topic that I think we only hear or learn about while studying computer science basics. But here its directly used to manage permissions in a very practical way and further on, you said that its ever more efficient due to its operating on a binary level.
By other areas, I can think of maybe plugging in security loopholes in applications (prevention of various injection attacks maybe) and optimization techniques for both space and time. I got a gut feeling that preventing injection attacks requires us to validate user input or user supplied data on the server and so maybe that is where we might be able to plug in bitwise operators to do things more efficiently.

Thread Thread
 
jannisdev profile image
Jannis

Now I get what you meant. I can only agree with that! 🔥

Collapse
 
galileo profile image
José Gilson

Nice job and excellent idea! Thanks a lot.

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

The idea is actually a very old one. For example, this is exactly how NTFS permissions work.

Collapse
 
jannisdev profile image
Jannis

That's correct. But even if it's old it's still very useful. It's also very fast. If you get deeper into it you begin to love the simplicity and scalability.

Collapse
 
jannisdev profile image
Jannis

Thank you very much! 🙏

Collapse
 
userr profile image
Dominic Ruggiero

Interesting! I've heard of bitfields, are those similar?

Collapse
 
jannisdev profile image
Jannis

I've looked into bit fields and it says A bit field is a data structure that consists of one or more adjacent bits. So it seems like yes those are familiar and in my understand a bit field is in this example either DEFAULT or LABORATORY but also
them combined e.g. Jenny is a bit field. 🔥

If someone knows more specific about this feel free to correct me 😉.

Collapse
 
boxtonie profile image
tonie box

Du bist Meine Rettung! DAS war das was ich unbedingt gebraucht habe!!!!!!
Vielen Dank für das tolle Tutorial

Collapse
 
jannisdev profile image
Jannis

It's a pleasure! I wish you much succes! And happy coding 😉

Collapse
 
brentdalling profile image
Brent Dalling

I built something similar. However, it was for storing days of weeks. It aims to reduce data size on large datasets. Say, a booking system with millions of records.

npmjs.com/package/daystobits

Great job explaining how it works! Kudos!

Collapse
 
jannisdev profile image
Jannis

Very nice! 🔥

Why You Need to Study Javascript Fundamentals

The harsh reality for JS Developers: If you don't study the fundamentals, you'll be just another “Coder”. Top learnings on how to get to the mid/senior level faster as a JavaScript developer by Dragos Nedelcu.