Add the authentication for API sing in.
continuous-integration/drone/push Build is failing Details
continuous-integration/drone/tag Build was killed Details

main 0.8.1
KKlochko 2 years ago
parent dad35c5c51
commit c793b46e53

@ -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.

@ -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

@ -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

Loading…
Cancel
Save