Access control patterns help decide who can do what in a blockchain system. They keep things safe by letting only the right people make changes.
0
0
Access control patterns in Blockchain / Solidity
Introduction
When you want only certain users to add or change data on the blockchain.
When you need to protect sensitive information from everyone except trusted parties.
When you want to track who did what and prevent unauthorized actions.
When building a blockchain app that requires roles like admin, user, or guest.
When you want to limit access to smart contract functions based on user identity.
Syntax
Blockchain / Solidity
contract AccessControl {
mapping(address => bool) private admins;
modifier onlyAdmin() {
require(admins[msg.sender], "Not an admin");
_;
}
function addAdmin(address user) public onlyAdmin {
admins[user] = true;
}
function removeAdmin(address user) public onlyAdmin {
admins[user] = false;
}
function restrictedAction() public onlyAdmin {
// action only admins can do
}
}modifier is a way to check permissions before running a function.
mapping(address => bool) stores which addresses have access.
Examples
This example uses a whitelist to allow only certain addresses access.
Blockchain / Solidity
mapping(address => bool) private whitelist; function addToWhitelist(address user) public { whitelist[user] = true; } function checkAccess() public view returns (bool) { return whitelist[msg.sender]; }
This example uses roles to control access, allowing more than one type of permission.
Blockchain / Solidity
enum Role { None, User, Admin }
mapping(address => Role) roles;
function setRole(address user, Role role) public {
roles[user] = role;
}
modifier onlyAdmin() {
require(roles[msg.sender] == Role.Admin, "Not admin");
_;
}Sample Program
This smart contract lets the creator be the first admin. Admins can add or remove other admins. Only admins can call these functions.
Blockchain / Solidity
pragma solidity ^0.8.0; contract SimpleAccessControl { mapping(address => bool) private admins; constructor() { admins[msg.sender] = true; // creator is admin } modifier onlyAdmin() { require(admins[msg.sender], "Not an admin"); _; } function addAdmin(address user) public onlyAdmin { admins[user] = true; } function removeAdmin(address user) public onlyAdmin { admins[user] = false; } function isAdmin(address user) public view returns (bool) { return admins[user]; } }
OutputSuccess
Important Notes
Always test access control carefully to avoid security holes.
Use modifiers to keep your code clean and avoid repeating permission checks.
Remember that blockchain data is public, so access control protects actions, not data visibility.
Summary
Access control patterns decide who can use blockchain functions.
Use mappings or enums to track permissions.
Modifiers help check permissions before running code.