Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c793b46e53 |
@@ -57,3 +57,5 @@
|
|||||||
Add tests for UserController, Accounts, Generators.
|
Add tests for UserController, Accounts, Generators.
|
||||||
** 0.8.0 <2023-08-08 Tue>
|
** 0.8.0 <2023-08-08 Tue>
|
||||||
Add the Web Authentication.
|
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
|
use Guardian, otp_app: :link_shortener
|
||||||
|
|
||||||
alias LinkShortener.Accounts
|
alias LinkShortener.Accounts
|
||||||
|
alias LinkShortener.Accounts.User
|
||||||
|
|
||||||
def subject_for_token(user, _claims) do
|
def subject_for_token(user, _claims) do
|
||||||
sub = to_string(user.id)
|
sub = to_string(user.id)
|
||||||
@@ -13,4 +14,18 @@ defmodule LinkShortenerWeb.Auth.Guardian do
|
|||||||
resource = Accounts.get_user!(id)
|
resource = Accounts.get_user!(id)
|
||||||
{:ok, resource}
|
{:ok, resource}
|
||||||
end
|
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
|
end
|
||||||
|
|||||||
@@ -21,4 +21,10 @@ defmodule LinkShortenerWeb.FallbackController do
|
|||||||
|> put_view(LinkShortenerWeb.ErrorView)
|
|> put_view(LinkShortenerWeb.ErrorView)
|
||||||
|> render(:"404")
|
|> render(:"404")
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def call(conn, {:error, :unauthorized}) do
|
||||||
|
conn
|
||||||
|
|> put_status(:unauthorized)
|
||||||
|
|> render(LinkShortenerWeb.ErrorView, :"401")
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
Reference in New Issue
Block a user