04 / 08
Authentication
This lesson uses a basic Twitter clone to compare how authentication works in Solidity and in Rell.
Solidity
Solidity has authentication built into the language. msg.sender gives you the address of whoever started the current function call, whether a person or a contract. You typically rely on it to authenticate callers and authorize what they can do.
Here is how you might add a post to a user's account:
function createPost(string memory _text) public { Post memory newPost = Post(_text, block.timestamp); users[msg.sender].posts.push(newPost);}msg.sender also lets you lock down specific functions. To limit administrative functions to the account that deployed the contract, check the caller with the require function:
require(msg.sender == owner, "Only the owner can call this function.");
Rell
Rell handles authentication through the FT4 library. It plays a role similar to Solidity's msg.sender, but you first need to configure an authentication handler. You then call auth.authenticate() to authenticate the caller and retrieve the user. The user has to be registered in the dapp before auth.authenticate() can be called.
Start by defining the auth handler as an extension:
import lib.ft4.auth;@extend(auth.auth_handler)function () = auth.add_auth_handler( flags = ["MySession"]);Next, add authentication to a create_post operation:
entity user { mutable name; key id: byte_array; key account: byte_array;}operation create_post(user_id : byte_array, content: text) { var account = auth.authenticate(); create Post ( user @ { account }, content = content );}As in Solidity, authentication in Rell takes only a few lines and fits naturally into your operations.
To restrict an operation to an owner, define an owner user in your blockchain configuration and enforce the check with require:
require(op_context.is_signer(owner), "Only the owner can call this operation");To summarize how each language handles authentication:
- Solidity: Relies on msg.sender to authenticate and authorize callers.
- Rell: Relies on the FT4 library, calling
auth.authenticate()to get the authenticated user.
For more on FT4 and authentication in Rell, see the FT4 accounts and auth descriptors documentation.