From c793b46e53215af1a1f1181bfa57f5e224c909df Mon Sep 17 00:00:00 2001 From: KKlochko Date: Wed, 9 Aug 2023 21:37:54 +0300 Subject: [PATCH] Add the authentication for API sing in. --- CHANGELOG.org | 2 ++ lib/link_shortener_web/auth/guardian.ex | 15 +++++++++++++++ .../controllers/fallback_controller.ex | 6 ++++++ 3 files changed, 23 insertions(+) diff --git a/CHANGELOG.org b/CHANGELOG.org index 8b450b3..dcdffbe 100644 --- a/CHANGELOG.org +++ b/CHANGELOG.org @@ -57,3 +57,5 @@ Add tests for UserController, Accounts, Generators. ** 0.8.0 <2023-08-08 Tue> Add the Web Authentication. +** 0.8.1 <2023-08-09 Wed> + Add the authentication for API sing in. diff --git a/lib/link_shortener_web/auth/guardian.ex b/lib/link_shortener_web/auth/guardian.ex index 48e1bba..c53ec3c 100644 --- a/lib/link_shortener_web/auth/guardian.ex +++ b/lib/link_shortener_web/auth/guardian.ex @@ -2,6 +2,7 @@ defmodule LinkShortenerWeb.Auth.Guardian do use Guardian, otp_app: :link_shortener alias LinkShortener.Accounts + alias LinkShortener.Accounts.User def subject_for_token(user, _claims) do sub = to_string(user.id) @@ -13,4 +14,18 @@ defmodule LinkShortenerWeb.Auth.Guardian do resource = Accounts.get_user!(id) {:ok, resource} end + + def authenticate(email, password) do + with user <- Accounts.get_user_by_email_and_password(email, password) do + case user do + %User{} -> create_token(user) + nil -> {:error, :unauthorized} + end + end + end + + defp create_token(user) do + {:ok, token, _claims} = encode_and_sign(user) + {:ok, user, token} + end end diff --git a/lib/link_shortener_web/controllers/fallback_controller.ex b/lib/link_shortener_web/controllers/fallback_controller.ex index 5f25eb5..c1a87df 100644 --- a/lib/link_shortener_web/controllers/fallback_controller.ex +++ b/lib/link_shortener_web/controllers/fallback_controller.ex @@ -21,4 +21,10 @@ defmodule LinkShortenerWeb.FallbackController do |> put_view(LinkShortenerWeb.ErrorView) |> render(:"404") end + + def call(conn, {:error, :unauthorized}) do + conn + |> put_status(:unauthorized) + |> render(LinkShortenerWeb.ErrorView, :"401") + end end