acrolink
Best way to access user_id inside changeset methods and data models
For some of my model methods (like creating or updating entities) I need to access the currently logged in user’s id. I have managed to do this using:
in books_controller.ex:
def create(conn, %{"book" => book_params}, user) do
with {:ok, %Book{} = book} <- Books.create_book(book_params |> Helpers.inject_user_id(user.id)) do
conn
|> put_status(:created)
|> put_resp_header("location", book_path(conn, :show, book))
|> render("show.json", book: book)
end
end
helpers.ex:
defmodule MangoWeb.Helpers do
def inject_user_id(input, user_id) do
Map.put(input, "user_id", user_id)
end
end
My question, is there a better way to do this?
Trending in Questions
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated!
To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead.
Sta...
New
Hello !
We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app?
Looking for hints regarding:
Addi...
New
Hi all, I wanted to ask how the community is dealing with post-release steps.
Today we have Ecto migrations, which make sure that the db...
New
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New
Other Trending Topics
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New
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
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #elixirconf-us
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #performance
- #security










First 9 of 9 Posts
mbuhot
Looks pretty good. You could optionally merge the
user.idinto the params earlier in the plug pipeline.acrolink
You mean creating a plug to inject the user id inside the parameters?
blatyo
Personally, I’d pass user to
create_bookas a first argument. In create_book, I’d do something like this:I would avoid putting user_id in the user supplied params, because then you’d have to allow it in the changeset. If you had another function that reused the changeset, the user might be able to inject a different user_id.
idi527
Or
joaquinalcerro
Hi @acrolink,
I personally like to handle this scenario on the schema itself where we handle the changeset creation and data validation. Just to be consistent where you do some specific actions in your code.
I leave the controller as simple as posible. For example:
I pass the parent association Invoice to the changeset function to build the association if “invoice_id is nil”.
It is the same result but the difference is where you perform the association and that you have to import the Ecto Library or build_assoc function in the controller in order to use the function. So with this in mind, if I have to handle the association in the controller I would use the Map.put/3 or %{ map | key: value } syntax to add the associated id like you are already using it.
Hope this helps.
idi527
To reiterate what @blatyo posted above
How do you protect your database from the malicious clients who can potentially supply invalid invoice ids (or valid, but not belonging to them)? Sure, in your case it might be not important, but in general it’s quite dangerous … I’ve seen projects passing
shop_idinto there changesets, thus allowing me to modify any “shop” in their database without having any privileged access to it.joaquinalcerro
I totally get it.
In the controller I validate if the user has authorization to execute the action. I use bodyguard for authorization and coherence for authentication purposes.
I also scope queries based on the user and I retrieve user’s information form the users session. I also understand that you can implement a more secure environment using prefixes (for postgres) but this may not be the case.
How are you tackling this issue? or what is the recommended way to do it?
Thanks for your comments.
acrolink
That’s a good practice, but yet when it comes to the identity of the currently logged in user, as far as I know it is not recommended to do and it is not easily accessible inside the schema definitions.
idi527
I leave all authorization logic to the context like here Should user permissions / data correctness logic live in my Ecto validations or Context logic? - #2 by idi527 and
raiseif something is wrong.