# External-facing route for /message/:id defget_message(context, message_id) # AnylogichereissafeaslongasweusethesafeAPIs returnsafe_read_message(context.user, message_id) end # SafeAPIsreplacedirectORMcalls # These methods are usually not handwritten, but this shows the logic defsafe_read_message(user, message_id) # Unsafe direct ORM call, not used outside of this method message = Message.unsafe_find(message_id)
# .can? explicitly checks authorization via authorize if user.can?(:read, message) return message
raise NotAuthorizedException end
# Central Authorization Logic defauthorize(user) # Examples: users can read profiles, update their own profile, write messages can :read, UserProfile can :update, UserProfile, id: user.profile.id can :create, Message
# Users can only read messages where they are the recipient readable_messages = Message.where(recipient: user) can :read, Message, id: readable_messages end