Preconditions
The following conditions are assumed:
- You have the sources of a contract with one of the actions defined, let's call it
hi
action. - The
hi
action has defined one input parameteruser
of typename
. - The
hi
action prints the name of theuser
account. - The
hi
action needs to authorize theuser
account.
Authorization Methods
To restrict access to the hi
action, you can do it in three ways.
1. Use eosio::check(eosio::has_auth(...)...)
The below code enforces the action hi
to be executed only by the account that is sent as parameter to the action, no matter what permission the account uses to sign the transaction (e.g. owner, active, code).
#include <capi/eosio/action.h>
void hi( name user ) {
check(has_auth(user), "User is not authorized to perform this action.");
print( "Hello, ", name{user} );
}
Another example can be found in the Tic Tac Toe Tutorial.
2. Use require_auth
The below code enforces the action hi
to be executed only by the account that is sent as parameter to the action, no matter what permission the account uses to sign the transaction (e.g. owner, active, code).
void hi( name user ) {
require_auth( user );
print( "Hello, ", name{user} );
}
3. Use require_auth2
The below code is enforces the action hi
to be executed only by the account that is sent as parameter to the action and only if the permission used to sign the transaction is the 'active' one. In other words, if the same user uses the transaction with a different permission (e.g. code, owner) the execution of the action is halted.
#include <capi/eosio/action.h>
void hi( name user ) {
require_auth2(user.value, "active"_n.value);
print( "Hello, ", name{user} );
}