thojanssens1
Sometimes you require foreign key ids to be included in the user form data.
Imagine a dropdown list where the user has to select a “location” when creating an “event”. His locations are saved and the dropdown shows a limited list of locations available.
Context function might typically look like:
def create_event(attrs) do
%Event{}
|> Event.changeset(attrs)
|> Repo.insert()
end
where the event changeset accepts a location_id key.
However, the user could send an ID not available from the dropdown (bypassing the form input); even a location ID that doesn’t belong to him but to another user from the database.
There would need to be some sort of authorization for all those relations coming from external user data.
How do/would you manage that in your application? Where do you enforce authorization?
My take: the context functions should take the current user and the authorization logic belongs in the context. (this logic shouldn’t be in the controller/resolvers/etc. because it would be needed in multiple places and could be forgotten; implementing it in the contexts gives more guarantees).
But it means that most of my context functions will take some current-user struct and I’m not sure this is a commonly seen pattern.
Trending in Discussions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixirconf-us
- #elixir-ls
- #ai
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming











Showing Posts 1 to 3- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
joseph-lozano
FWIW, passing a user (or in one of the cases, a team) into context functions is a pattern I have seen in at least 2 codebases/companies.
al2o3cr
Depending on your domain, consider making
create_eventtake an already-foundLocation:As a bonus,
Event.changesetdoesn’t need to castlocation_idat all - useful if “reassigninglocation_id” isn’t a meaningful operation in your domain.chungwong
You can consider using validate_change/3
You can validate based on the
user_idandlocation_idin theattrs