acrolink

acrolink

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?

Showing Posts 1 to 9

mbuhot

mbuhot

Looks pretty good. You could optionally merge the user.id into the params earlier in the plug pipeline.

acrolink

acrolink OP

You mean creating a plug to inject the user id inside the parameters?

blatyo

blatyo

Conduit Core Team

Personally, I’d pass user to create_book as a first argument. In create_book, I’d do something like this:

def create_book(user, book_params) do
  user
  |> build_assoc(:books)
  |> Book.changeset(book_params)
  |> Repo.create()
end

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

idi527

Or

  def create(conn, %{"book" => book_params}, user) do
    with {:ok, %Book{} = book} <- Books.create_book(book_params, for: user) do
      conn
      |> put_status(:created)
      |> put_resp_header("location", book_path(conn, :show, book))
      |> render("show.json", book: book)
    end
  end
def create_book(book_params, for: %User{id: user_id}) do
  %Book{user_id: user_id}
  |> Book.changeset(book_params)
  |> Repo.insert()
end
joaquinalcerro

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:

defmodule Multiplatform.Documents.Detail do
use Ecto.Schema
import Ecto.Changeset

def changeset(%Detail{invoice_id: nil}, attrs, invoice) do
  Ecto.build_assoc(invoice, :details)
  |> cast(attrs, [:tax, :code, :desc, :up, :invoice_id])
  |> validate_required([:tax, :code, :desc, :up, :invoice_id])
end

def changeset(%Detail{} = detail, attrs, _invoice) do
  detail
  |> cast(attrs, [:tax, :code, :desc, :up, :invoice_id])
  |> validate_required([:tax, :code, :desc, :up, :invoice_id])
  |> mark_for_delete()
end

end

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

idi527

To reiterate what @blatyo posted above

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.

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_id into there changesets, thus allowing me to modify any “shop” in their database without having any privileged access to it.

joaquinalcerro

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

acrolink OP

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

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 raise if something is wrong.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
Aludel - LLM Evaluation Workbench Aludel is an embeddable Phoenix LiveView dashboard for evaluating and comparing LLM prompts across mult...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews