Permission Flags with Bitmasks
Implement Unix-style permission systems using bitmask flags. Learn to define, combine, check, grant, and revoke permissions with bitwise operations.
Detailed Explanation
Permission Systems Using Bitmasks
Unix file permissions are the classic example of bitmask-based access control. Each permission type occupies a distinct bit position:
const NONE = 0b000; // 0
const EXECUTE = 0b001; // 1
const WRITE = 0b010; // 2
const READ = 0b100; // 4
Granting Permissions (OR)
Combine permissions using OR:
const readWrite = READ | WRITE; // 0b110 = 6
const all = READ | WRITE | EXECUTE; // 0b111 = 7
Checking Permissions (AND)
Test if a specific permission is granted:
function hasPermission(flags, permission) {
return (flags & permission) === permission;
}
hasPermission(readWrite, READ); // true
hasPermission(readWrite, EXECUTE); // false
Revoking Permissions (AND + NOT)
Remove a permission without affecting others:
function revoke(flags, permission) {
return flags & ~permission;
}
revoke(readWrite, WRITE); // 0b100 = READ only
Multi-Level Permissions
Unix extends this to owner/group/other with 3 bits each (9 bits total):
Owner Group Other
rwx rwx rwx
111 101 101 = 0o755 = 0b111101101
Role-Based Extension
Modern systems extend this pattern to dozens of permission types:
const PERM = {
VIEW: 1 << 0, // 1
EDIT: 1 << 1, // 2
DELETE: 1 << 2, // 4
SHARE: 1 << 3, // 8
ADMIN: 1 << 4, // 16
EXPORT: 1 << 5, // 32
};
const editorRole = PERM.VIEW | PERM.EDIT | PERM.SHARE; // 11
const adminRole = 0b111111; // all permissions = 63
A 32-bit integer can hold 32 distinct permission flags — enough for most applications.
Use Case
Web application frameworks use bitmask permissions for role-based access control (RBAC). Discord, for example, uses a 53-bit integer to store channel permission overrides. Each bit represents a permission like SEND_MESSAGES, MANAGE_CHANNELS, or BAN_MEMBERS. Permission checks are simple AND operations, and permission overrides are computed by ORing role permissions together and then applying channel-specific allow/deny masks.