peppy

peppy

I’m trying to build a simple function to see if a user is authorized to join a conversation. Basically, it needs to query the mysql database to get a list of all users in the conversation, and then compare the userid on the socket to the results list.

This is what I have so far:

 def join("conv:" <> convid, _message, socket) do
    if authorized?(convid, socket) do
      IO.inspect("join conversation " <> convid)
      send(self(), :after_join)
      {:ok, socket}
    else
      IO.inspect("not authorized to join room")
      :error
    end
  end

 defp authorized?(convid, socket) do
    IO.inspect("run conv auth function")
    results =
    from(m in GetUsersInConv, # use lib/app_web/schemas/usersinconv.ex
      where: m.id == ^convid,
      select: %{userid: m.userid, status: m.status}
    )
    |> Repo.all()
    userIdInSocket = socket.assigns.user_id
    IO.inspect("socket userid: " <> userIdInSocket)
    IO.inspect(results)
    # Need to add matching function next...
  end

These are the results I get, a list of all userids in the conversation and their status:

"run conv auth function"
[debug] QUERY OK source="conversations" db=0.7ms idle=1289.4ms
SELECT p0.`userid`, p0.`status` FROM `conversations` AS p0 WHERE (p0.`id` = ?) [107876]
"socket userid: 1"
[
  %{status: 0, userid: 1},
  %{status: 0, userid: 299},
  %{status: 0, userid: 664},
  %{status: 0, userid: 782},
  %{status: 0, userid: 1035},
  %{status: 0, userid: 4609},
  %{status: 0, userid: 4684},
  %{status: 0, userid: 5974},
  %{status: 0, userid: 6755},
  %{status: 0, userid: 6755},
  %{status: 0, userid: 8980},
  %{status: 0, userid: 9246},
  %{status: 0, userid: 10759},
  %{status: 0, userid: 15517},
  %{status: 0, userid: 16502},
  %{status: 0, userid: 32428},
  %{status: 0, userid: 61240},
  %{status: 0, userid: 79131},
  %{status: 0, userid: 98521},
  %{status: 3, userid: 145222}
]

If the userid of the socket is “1”, how can I build an Enum iteration function to match the following conditions:

  1. userid “1” is found within the result list of userids
  2. status != 3 AND status != 7 for that user as well.

If all those conditions are met, return “true”, otherwise “false” for the entire “authorized?” function.

I’m getting better and better at figuring out elixir, but syntax for enum and pattern matching is still a little tricky.

Thanks!

Showing Posts 1 to 5

al2o3cr

al2o3cr

Both of these are expressible in SQL - for instance, you could rephrase the above as:

“does a row exist with user_id = 1 and status != 3 and status != 7”

Check out Repo.exists?.

peppy

peppy OP

Thanks for that function, that is actually pretty useful and I didn’t about it. I’ll definitely be using that for later purposes.

I thought about simply putting the entire conditions into the mysql query, but I’d have to index all three of those columns in mysql (id,userid,status). I was hoping strengthen my knowledge a little bit more with elixir pattern matching, as I have even more complicated things to implement later on, and some that can’t access the database.

peppy

peppy OP

Well, I’ve been studying all night and hit a dead end. This is about as far as I could get:

userIdInSocket = 1
results = 
[
  %{status: 0, userid: 1}, #this should cause function to return true: userid matched, status not in [3,7]
  %{status: 0, userid: 299},
  %{status: 0, userid: 664},
  %{status: 0, userid: 782},
  %{status: 0, userid: 1035},
  %{status: 0, userid: 4609},
  %{status: 0, userid: 4684},
  %{status: 0, userid: 5974},
  %{status: 0, userid: 6755},
  %{status: 0, userid: 6755},
  %{status: 0, userid: 8980},
  %{status: 0, userid: 9246},
  %{status: 0, userid: 10759},
  %{status: 0, userid: 15517},
  %{status: 0, userid: 16502},
  %{status: 0, userid: 32428},
  %{status: 0, userid: 61240},
  %{status: 0, userid: 79131},
  %{status: 0, userid: 98521},
  %{status: 3, userid: 145222}
]

isFound = Enum.any?(results, fn (x) -> match?(%{status: x, userid: userIdInSocket} when x not in [3,7], x) end)

isFound keeps coming up true even if I edit the condition to: when x not in [0].

Basically x in this function is the user’s status. When I get a list of users in the conversation, I want to run the function to detect if the user is added to the conversation - AND - that the user’s status is not 3 or 7 (which means they are blocked).

The function should return true only if that userid is found in the results list, and their status anything except 3 or 7.

LostKobrakai

LostKobrakai

You’re close and the compiler should’ve warned you about the actual issue:

warning: variable “userIdInSocket” is unused (there is a variable with the same name in the context, use the pin operator (^) to match on it or prefix this variable with underscore if it is not meant to be used)

Pattern matching for %{status: x, userid: userIdInSocket} means that you match for a map with key status and assign the status value to variable x and a key of userid and assign the userid value to userIdInSocket. That pattern works for all of your inputs elements.

You wanted to match only rows where userids value matches your existing value in the variable userIdInSocket, which you denote with the pin operator like so:

%{status: x, userid: ^userIdInSocket} …

dimitarvp

dimitarvp

While I am not convinced that I understood your requirements well, this works:

defmodule UserChecks do
  def authorized?(user_id, %{userid: user_id, status: status}) when status not in [3, 7], do: true
  def authorized?(_user_id, %{userid: _other_user_id, status: _status}), do: false

  def any_authorized?(user_id, user_ids_and_statuses) when is_list(user_ids_and_statuses) do
    Enum.any?(user_ids_and_statuses, &authorized?(user_id, &1))
  end

  def test() do
    user_ids_and_statuses = [
      %{status: 0, userid: 1},
      %{status: 3, userid: 100},
      %{status: 7, userid: 200},
      %{status: 0, userid: 299},
      %{status: 0, userid: 664}
    ]

    IO.inspect(user_ids_and_statuses, label: "userids and statuses")
    IO.inspect(any_authorized?(1, user_ids_and_statuses), label: "Is userid 1 authorized?")
    IO.inspect(any_authorized?(2, user_ids_and_statuses), label: "Is userid 2 authorized?")
    IO.inspect(any_authorized?(100, user_ids_and_statuses), label: "Is userid 100 authorized?")
    IO.inspect(any_authorized?(200, user_ids_and_statuses), label: "Is userid 200 authorized?")
    IO.inspect(any_authorized?(299, user_ids_and_statuses), label: "Is userid 299 authorized?")
    IO.inspect(any_authorized?(664, user_ids_and_statuses), label: "Is userid 664 authorized?")
  end
end

authorized? basically emulates the match? you are trying to do. IMO a function with multiple pattern-matching heads reads better. Notice how user_id is specified twice in the first head; this a neat trick that matches only when there’s the same value in the first function argument and the userid field of the map.

But if you really must know how does it look with match?, here you go:

  def authorized?(searched_user_id, %{userid: _user_id, status: _status} = userid_and_status) do
    match?(
      %{userid: ^searched_user_id, status: status} when status not in [3, 7],
      userid_and_status
    )
  end
— All posts loaded —

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
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
spammy
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
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
bottlenecked
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
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

JesseHerrick
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
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews