woohaaha
Authorization as business logic
I see a lot of posts/discussions around authorization and how one should not mix it up with business logic. So in the controller they will authorize, and then perform the action.
In my head I feel like authorization IS business logic. Authorization is part of the rules that make an app operate as intended. I kind of want authorization logic to sit right next to resource actions.
def create_user(attrs, %User{role: role} = current_user) do
with :ok <- authorize(:create_user, role),
changeset = User.changeset(attrs),
{:ok, user} = Repo.insert(attrs) do:
# stuff
end
Can anyone explain concretely why authorization is NOT business logic?
Most Liked
bennelsonweiss
Two comments about this, see the reference number in the code block for each:
-
It depends what
Blogs.get_postreturns here, but if it returns likeMap.getthen it will either return a blog post ornil, and since you’re using=there either will be a valid return value.This means that you could be passing
niltoBlogs.update_postwhich would probably result in an error if you’re not checking fornilinBlogs.update_post.A cleaner solution would be either to use a version of
Blogs.get_post!that raises or aBlogs.fetch_postthat returns either{:ok, post}or and error that you can match on during thewith. -
error -> {:error, error}may not behave how you expect- ifBlogs.update_postreturns{:error, error}then you’re capturing that value aserror, which means you’re returning{:error, {:error, error}}from thewith.
hauleth
While I agree that authorisation is part of the business logic, I disagree that authorisation is part of create_user function. While this indeed prevents (in most cases) accidental omission of the check, it makes API less flexible, which mean that we need additional functions to create 1st user or create users in tests.
benwilson512
If this is related to comments I made in the RBAC thread, I’ll clarify a bit here.
In my head I feel like authorization IS business logic
I agree with this. What I was warning about was making all business logic authorization logic. That is to say, it’s reasonable to ask “is this user authorized to create a user”. It’s also reasonable to say “Is it valid to create a user with no username? No”. But it’d be weird to say “You are authorized to create a user with a valid user name, and not authorized to create a user without a username”.
All of it is business logic, but within the domain of business logic there are some questions that make sense rendered in terms of authorization, and other questions that make more sense rendered in terms of validation. If you treat auth as merely one of a dozen different properties that must be true about an entity when it is being created then it blurs that line in a way that I think is unhelpful.
stefanchrobot
Wow, great insight! I always struggled whether my context should return the schema or an ok/error tuple. Using get/fetch approach makes total sense and it follows the std lib.







