Skip to main content

Write Access Control

In this tutorial, we will modify the schema in the first schema tutorial to add write access control rules.

Out of the box, Kwil supports a variety of access control capabilities. If you wish to implement more advances access control logic than what is natively available, you can do so by adding an Extension to your network.

Raising Errors

In a procedure, you can use SQL CASE statements to raise errors if certain conditions are not met. If an error is raised, the transaction will fail entirely, and data will not be written to the network.

social_media.kf
// private procedure to check if user exists
procedure check_user() private view {
// to check if a user exists, we will query for it
// and return if a row is found. If no row is found,
// we will raise an error.
for $row in SELECT 1 FROM users WHERE address=@caller {
return;
}

// if no user is found, we raise an error
ERROR('User does not exist');
}

Procedure Privacy

Procedure privacy enforces whether a procedure can be called by a user or not. Public procedures can be called by users. Private procedures can only be called by other procedures.

The distinction between public and private procedures are similar to the distinction between public and private methods in object-oriented programming, where public methods are accessible from outside the class, and private methods are only accessible from within the class.

social_media.kf
// private procedure to check if user exists
procedure check_user() private view {
// to check if a user exists, we will query for it
// and return if a row is found. If no row is found,
// we will raise an error.
for $row in SELECT 1 FROM users WHERE address=@caller {
return;
}

// if no user is found, we raise an error
ERROR('User does not exist');
}

// before creating a post, check if the user exists
procedure create_post ($id int, $title text, $content text, $date_string text) public {
check_user();
INSERT INTO posts (id, title, content, author_id, post_date)
VALUES (
$id,
$title,
$content,
(SELECT id FROM users WHERE address=@caller),
$date_string
);
}

Owner-only Procedures

Procedures can be given an owner privacy level, which means that only the owner of the database can call the procedure. This is useful for procedures that should only be called by the database owner, such as admin operations.

social_media.kf
// owner only procedure to delete a user
procedure delete_user($user_id int) public owner {
DELETE FROM users WHERE id = $user_id;
}