32 lines
653 B
Elixir
32 lines
653 B
Elixir
defmodule VishnyaWeb.Plugs.Authenticate do
|
|
import Plug.Conn
|
|
alias Vishnya.Repo
|
|
alias Vishnya.Accounts.User
|
|
|
|
def init(default), do: default
|
|
|
|
def call(conn, _default) do
|
|
case get_req_header(conn, "authorization") do
|
|
["Bearer " <> token] ->
|
|
case authenticate_token(token) do
|
|
nil ->
|
|
conn
|
|
|> send_resp(401, "Unauthorized")
|
|
|> halt()
|
|
|
|
user ->
|
|
assign(conn, :user, user)
|
|
end
|
|
|
|
_ ->
|
|
conn
|
|
|> send_resp(401, "Unauthorized")
|
|
|> halt()
|
|
end
|
|
end
|
|
|
|
defp authenticate_token(token) do
|
|
Repo.get_by(User, token: token)
|
|
end
|
|
end
|