Fakultas Ilmu Komputer UI

Commit 1eb6cb68 authored by Muhammad Rafif Elfazri's avatar Muhammad Rafif Elfazri
Browse files

Authorized Update and delete

parent a45d1e1f
......@@ -35,4 +35,13 @@ defmodule DiskuyWeb.Auth.Guardian do
{:ok, user, token}
end
def check_authorized(user, id_entity) do
case user.id == id_entity do
true ->
{:ok, :authorized}
false ->
{:error, :unauthorized}
end
end
end
......@@ -5,6 +5,7 @@ defmodule DiskuyWeb.PostController do
alias Diskuy.Forum.Post
alias Diskuy.Likes
alias Diskuy.Likes.PostLike
alias DiskuyWeb.Auth.Guardian
action_fallback DiskuyWeb.FallbackController
......@@ -29,17 +30,20 @@ defmodule DiskuyWeb.PostController do
end
def update(conn, %{"id" => id, "post" => post_params}) do
current_user = Guardian.Plug.current_resource(conn)
post = Forum.get_post!(id)
with {:ok, %Post{} = post} <- Forum.update_post(post, post_params) do
with {:ok, :authorized} <- Guardian.check_authorized(current_user, post.user_id),
{:ok, %Post{} = post} <- Forum.update_post(post, post_params) do
render(conn, "show.json", post: post)
end
end
def delete(conn, %{"id" => id}) do
current_user = Guardian.Plug.current_resource(conn)
post = Forum.get_post!(id)
with {:ok, %Post{}} <- Forum.delete_post(post) do
with {:ok, :authorized} <- Guardian.check_authorized(current_user, post.user_id),
{:ok, %Post{}} <- Forum.delete_post(post) do
send_resp(conn, :no_content, "")
end
end
......
......@@ -30,15 +30,19 @@ defmodule DiskuyWeb.ThreadController do
end
def update(conn, %{"id" => id, "thread" => thread_params}) do
current_user = Guardian.Plug.current_resource(conn)
thread = Forum.get_thread!(id)
with {:ok, %Thread{} = thread} <- Forum.update_thread(thread, thread_params) do
with {:ok, :authorized} <- Guardian.check_authorized(current_user, thread.user_id),
{:ok, %Thread{} = thread} <- Forum.update_thread(thread, thread_params) do
render(conn, "show.json", thread: thread)
end
end
def delete(conn, %{"id" => id}) do
current_user = Guardian.Plug.current_resource(conn)
thread = Forum.get_thread!(id)
with {:ok, %Thread{}} <- Forum.delete_thread(thread) do
with {:ok, :authorized} <- Guardian.check_authorized(current_user, thread.user_id),
{:ok, %Thread{}} <- Forum.delete_thread(thread) do
send_resp(conn, :no_content, "")
end
end
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment