-
Notifications
You must be signed in to change notification settings - Fork 2
/
authorize.ex
45 lines (39 loc) · 1.18 KB
/
authorize.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
defmodule HelloWorld.Auth.Authorize do
@moduledoc """
Plug for authorizing endpoints using Bearer authorization token.
"""
@behaviour Plug
import Plug.Conn
import Phoenix.Controller, only: [json: 2, put_view: 2, render: 3]
alias HelloWorld.Auth.Token
@spec init(any) :: any
def init(default), do: default
@doc """
Extracts the Bearer token from the authorization header and verifies the claims.
"""
@spec call(Plug.Conn.t(), any) :: Plug.Conn.t()
def call(conn, _default) do
with {:ok, token} when is_binary(token) <- get_token(conn),
{:ok, _claims} <- Token.verify_and_validate(token) do
conn
else
{:error, error} -> handle_error_response(conn, error)
end
end
defp get_token(conn) do
case get_req_header(conn, "authorization") do
["Bearer " <> token] -> {:ok, token}
["bearer " <> token] -> {:ok, token}
[] -> {:error, :missing_token}
["Bearer"] -> {:error, :invalid_token}
_ -> {:error, :invalid_token}
end
end
defp handle_error_response(conn, error) do
conn
|> put_status(401)
|> put_view(HelloWorldWeb.ErrorView)
|> render("401.json", %{error: error})
|> halt()
end
end