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:
- userid “1” is found within the result list of userids
- 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!