How to check permissions

From Online Manual

Jump to: navigation, search

If you are writing custom code for SMF, such as a mod or a website integration with SSI.php, you can easily check for standard or custom permissions. The membergroup and board permissions are available through a few simple functions, and it works for guests too.

There are two ways to check for permissions. You can either check only whether someone has a permission, or you can run this check and then have an error displayed if the user does not have the permission.

Examples:

<?php
	// Conditional: returns true or false depending on whether they have been given that permission or not
	if (allowedTo('my_permission'))
		take_over_the_world();
?>
<?php
	// Deterministic: checks the permission and stops the program with an error if the user does not have it
	isAllowedTo('my_permission');
	// At this point of the code, only those with my_permission are left.
	// I can now safely assume you're authorized to...	take_over_the_world();
?>

Here is a practical example: suppose you are writing a custom page with SSI integration that allows a user to manage your forum news. You can use:

<?php
	if (allowedTo('edit_news'))
		custom_function_to_edit_the_news();
?>

If a user has such permission, the function will be called. If not, the code processing will continue normally.

Checking Board Permissions

When inside a board there is no difference between checking board or membergroup permissions. Board permissions are, however, only given to users when they are inside a board, so testing for board permissions outside of a board or topic will generally return false.

Local permissions also complicate the system. If users have a certain board permission in one board, but not in another because of local permissions, they will only have that permission in one board. SMF will only tell you the permissions in the current board and not reveal the permissions of other boards.

If, however, you want to check board permissions when not inside a board or topic, or you want to check the permissions of a different board, this is possible as the following example shows:

<?php
	// Check for a permission in the board specified by $board_id
	if (allowedTo('my_board_permission', $board_id))
		take_over_the_world();
?>

Through a different function you can check which boards a user has a permission on:

<?php
	$my_boards = boardsAllowedTo('my_board_permission');
	// $my_boards now contains an array of board IDs that the user is allowed to do my_board_permission in.
	// If $my_boards is empty they do not have that permission in any boards.
	// If $my_boards contains 0, then they have the permission in all boards.
?>