Compare commits

..
1 Commits
Author SHA1 Message Date
KKlochko c793b46e53 Add the authentication for API sing in.
continuous-integration/drone/push Build is failing
continuous-integration/drone/tag Build was killed
2023-08-09 21:38:20 +03:00
3 changed files with 23 additions and 0 deletions
+2
View File
@@ -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.
+15
View File
@@ -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