Update the API Authentication.
continuous-integration/drone/push Build is passing

This commit is contained in:
2024-08-24 16:18:11 +03:00
parent 32ea2c4ff8
commit 8697be9f17
12 changed files with 196 additions and 1 deletions
@@ -0,0 +1,26 @@
defmodule LinkShortenerWeb.Api.V1.AccountsController do
use LinkShortenerWeb, :controller
alias LinkShortener.Accounts
alias LinkShortener.Accounts.User
alias LinkShortenerWeb.Auth.Guardian
action_fallback LinkShortenerWeb.FallbackController
def sign_up(conn, %{"user" => user_params}) do
with {:ok, %User{} = user} <- Accounts.register_user(user_params),
{:ok, token, _claims} <- Guardian.encode_and_sign(user) do
conn
|> put_status(:created)
|> render(:user, %{user: user, token: token})
end
end
def sign_in(conn, %{"email" => email, "password" => password}) do
with {:ok, user, token} <- Guardian.authenticate(email, password) do
conn
|> put_status(:created)
|> render(:user, %{user: user, token: token})
end
end
end
@@ -0,0 +1,11 @@
defmodule LinkShortenerWeb.Api.V1.AccountsJSON do
alias LinkShortener.Links.Link
def user(%{user: user, token: token}) do
%{
id: user.id,
email: user.email,
token: token
}
end
end
@@ -21,4 +21,11 @@ defmodule LinkShortenerWeb.FallbackController do
|> put_view(html: LinkShortenerWeb.ErrorHTML, json: LinkShortenerWeb.ErrorJSON)
|> render(:"404")
end
def call(conn, {:error, :unauthorized}) do
conn
|> put_status(:unauthorized)
|> put_view(html: LinkShortenerWeb.ErrorHTML, json: LinkShortenerWeb.ErrorJSON)
|> render(:"401")
end
end