martins

martins

Where to put code that should run after sign_in?

When a user signs up, then I want to run some checks before I let him into the app.
E.g. check if he is already affiliated with an existing Company.

Do I write a plug or do I do something else? :slight_smile:

I’m using auth.gen for authentication.

Best,
Martin

Most Liked

odd

odd

Are these things that would block signing up or not? Based on your example, I’ll assume they’re not.

In one of our apps, we perform similar tasks and really like using Oban to handle these background jobs. We enqueue the jobs in Accounts.create_user/1, which manages everything within an %Ecto.Multi{}. For your case it would be something like this:

defmodule MyApp.Users.CheckUsersExistingCompaniesWorker do
  use Oban.Worker,
    queue: :default,
    priority: 3,
    max_attempts: 3,
    tags: ["users"],
    unique: [period: 30]

  @impl Oban.Worker
  def perform(%Oban.Job{args: %{"user_id" => user_id}}) do
    # do the check, maybe update db

    # :ok | {:ok, value} | {:cancel, reason} | {:error, error} | {:snooze, seconds}
  end
end

defmodule MyApp.Users do
  def enqueue_existing_companies_job(user_id) do
    %{user_id: user_id}
    |> __MODULE__.CheckUsersExistingCompaniesWorker.new()
    |> Oban.insert()
  end
end

You could choose your preferred method of spawning processes, but if you want an easy and solid solution, then I’d recommend going with a robust library like Oban or a similar one.

But if you’re talking about things that would block signing up or in, then you’d want to do this in a Plug or an on_mount handler for LiveView.

odd

odd

A plug for this use case would be something along the lines of this:

defmodule MyAppWeb.Plugs.CheckUserCompany do
  import Plug.Conn

  def init(_opts), do: %{}

  def call(conn, _opts) do
    case MyApp.SomeContext.affiliated_with_existing_company?(conn.assigns.current_user) do
      true ->
        conn
        |> put_flash(:error, "Not allowed")
        |> redirect(to: "/")

      false ->
        conn
    end
  end
end

And an on_mount handler like this:

defmodule MyAppWeb.Live.OnMountHandlers do
  def on_mount(:affiliated_with_existing_company, _params, _session, socket) do
    case MyApp.SomeContext.affiliated_with_existing_company?(socket.assigns.current_user) do
      true -> {:halt, redirect(socket, to: "/")}
      false -> {:cont, socket}
    end
  end
end

Or whatever the logic is behind that check.

Where Next?

Popular in Questions Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New

Other popular topics Top

JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 47930 226
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

We're in Beta

About us Mission Statement