diff --git a/lib/phoenix_api_template_web/auth/guardian_error_handler.ex b/lib/phoenix_api_template_web/auth/guardian_error_handler.ex new file mode 100644 index 0000000..f1d2f74 --- /dev/null +++ b/lib/phoenix_api_template_web/auth/guardian_error_handler.ex @@ -0,0 +1,11 @@ +defmodule PhoenixApiTemplateWeb.Auth.GuardianErrorHandler do + import Plug.Conn + + def auth_error(conn, {type, _reason}, _opts) do + body = Jason.encode!(%{error: to_string(type)}) + + conn + |> put_resp_content_type("application/json") + |> send_resp(401, body) + end +end diff --git a/lib/phoenix_api_template_web/auth/pipeline.ex b/lib/phoenix_api_template_web/auth/pipeline.ex new file mode 100644 index 0000000..3121a57 --- /dev/null +++ b/lib/phoenix_api_template_web/auth/pipeline.ex @@ -0,0 +1,11 @@ +defmodule PhoenixApiTemplateWeb.Auth.Pipeline do + use Guardian.Plug.Pipeline, + otp_app: :phoenix_api_template, + module: PhoenixApiTemplateWeb.Auth.Guardian, + error_handler: PhoenixApiTemplateWeb.Auth.GuardianErrorHandler + + plug Guardian.Plug.VerifySession + plug Guardian.Plug.VerifyHeader + plug Guardian.Plug.EnsureAuthenticated + plug Guardian.Plug.LoadResource +end diff --git a/lib/phoenix_api_template_web/router.ex b/lib/phoenix_api_template_web/router.ex index 296039b..5985fa6 100644 --- a/lib/phoenix_api_template_web/router.ex +++ b/lib/phoenix_api_template_web/router.ex @@ -18,6 +18,10 @@ defmodule PhoenixApiTemplateWeb.Router do plug(:accepts, ["json"]) end + pipeline :auth do + plug PhoenixApiTemplateWeb.Auth.Pipeline + end + scope "/api", PhoenixApiTemplateWeb do pipe_through(:api) @@ -25,4 +29,10 @@ defmodule PhoenixApiTemplateWeb.Router do post("/register", UserController, :create) post("/login", UserController, :sign_in) end + + scope "/api", PhoenixApiTemplateWeb do + pipe_through([:api, :auth]) + + get "/users/by_id/:id", UserController, :show + end end diff --git a/test_requests/get_user.http b/test_requests/get_user.http new file mode 100644 index 0000000..7c19f91 --- /dev/null +++ b/test_requests/get_user.http @@ -0,0 +1,4 @@ +GET http://localhost:4000/api/users/by_id/eae6f03c-6276-48e3-b6df-0797b2f8cb99 HTTP/1.1 +content-type: application/json +Authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJwaG9lbml4X2FwaV90ZW1wbGF0ZSIsImV4cCI6MTY3OTEzODAxMiwiaWF0IjoxNjc2NzE4ODEyLCJpc3MiOiJwaG9lbml4X2FwaV90ZW1wbGF0ZSIsImp0aSI6ImRmYjc5NDExLTgwY2QtNDNkZC1hYmU0LWMxYjg2OWJhODI4YyIsIm5iZiI6MTY3NjcxODgxMSwic3ViIjoiZWFlNmYwM2MtNjI3Ni00OGUzLWI2ZGYtMDc5N2IyZjhjYjk5IiwidHlwIjoiYWNjZXNzIn0.b1F2a57dv4hCp1015--QPaE3bEVePXNeg-JajkqA_PGxKZx_kJoedLt8KIuCDTVAF-Sn--iWr1miOUowwgbwhA + \ No newline at end of file