Skip to content

Commit

Permalink
add enrollment check plug
Browse files Browse the repository at this point in the history
  • Loading branch information
nmenag committed Dec 14, 2023
1 parent 8862371 commit 5bf0f51
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 5 deletions.
2 changes: 2 additions & 0 deletions apps/core/lib/core/schema/course.ex
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ defmodule GoEscuelaLms.Core.Schema.Course do

def find(uuid) do
Repo.get(Course, uuid)
|> Repo.preload(:topics)
|> Repo.preload(:enrollments)
end

def create(attrs \\ %{}) do
Expand Down
2 changes: 2 additions & 0 deletions apps/web/lib/web/controllers/topics/topics_controller.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ defmodule Web.Topics.TopicsController do

plug :is_permit_authorized when action in [:create]
plug :load_course when action in [:create]
plug :load_course when action in [:create]
plug :check_enrollment when action in [:create]

@create_params %{
name: [type: :string, required: true]
Expand Down
26 changes: 21 additions & 5 deletions apps/web/lib/web/plug/check_request.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ defmodule Web.Plug.CheckRequest do
def load_course(conn, _) do
course_id = conn.params["courses_id"]

IO.puts "COURSE_ID ==> #{course_id}"

with :ok <- valid_uuids(course_id),
course <- Course.find(course_id),
false <- is_nil(course) do
Expand All @@ -21,11 +19,29 @@ defmodule Web.Plug.CheckRequest do
end

defp valid_uuids(id) do
with {:ok, _} <- Ecto.UUID.dump(id) do
case Ecto.UUID.dump(id) do
{:ok, _} ->
:ok
else
_ ->
{:error, "invalid params"}
end
end

def check_enrollment(%{assigns: %{account: %{role: :organizer}}} = conn, _), do: conn

def check_enrollment(conn, _) do
user_id = conn.assigns.account.uuid
course = conn.assigns.course

case is_nil(
course.enrollments
|> Enum.find(fn enrollment -> enrollment.user_id == user_id end)
) do
false ->
conn

_ ->
{:error, "invalid params"}
Web.FallbackController.call(conn, {:error, :forbidden}) |> halt()
end
end
end

0 comments on commit 5bf0f51

Please sign in to comment.