09 / 27Module 1: A Rell backend with FT accountsBeginner
Authentication with FT4 accounts
This lesson shows how to authenticate users with FT4 accounts.
FT4 makes authentication straightforward. Start by importing the auth module:
import lib.ft4.auth;Then call auth.authenticate inside your operations:
operation make_post(content: text) { val account = auth.authenticate(); require(content.size() <= 255, "A post cannot be longer than 255 characters"); val user = user @ { account }; create post ( user, content );}operation follow_user(follow_id: byte_array) { val account = auth.authenticate(); val user = user @ { account }; val follow = require_user(follow_id); create follower ( user = follow, follower = user );}operation unfollow_user(unfollow_id: byte_array) { val account = auth.authenticate(); val user = user @ { account }; val follow = require_user(unfollow_id); delete follower @? { .user == follow, .follower == user };}Calling auth.authenticate takes care of authentication for you, which simplifies your code and improves security. Your operations also no longer need to receive the user's public key as a parameter.
Authentication only takes effect once you register an auth handler. Add this code to your Rell module:
@extend(auth.auth_handler)function () = auth.add_auth_handler( flags = ["S"]);This extension function registers a handler with the "S" flag, the same flag you used when creating the account. The handler is global, so it applies to every operation in your app that calls auth.authenticate. To attach a handler to one specific operation or module instead, pass a scope argument to auth.add_auth_handler.