Add plug to generate Matrix error
This commit is contained in:
parent
dac1a429b9
commit
1ec18163c1
6 changed files with 47 additions and 50 deletions
lib/matrix_server_web/plug
36
lib/matrix_server_web/plug/authenticate.ex
Normal file
36
lib/matrix_server_web/plug/authenticate.ex
Normal file
|
@ -0,0 +1,36 @@
|
|||
defmodule MatrixServerWeb.Plug.Authenticate do
|
||||
import MatrixServerWeb.Plug.Error
|
||||
import Plug.Conn
|
||||
import Phoenix.Controller, only: [json: 2]
|
||||
|
||||
alias MatrixServer.Account
|
||||
alias Plug.Conn
|
||||
|
||||
def init(opts), do: opts
|
||||
|
||||
def call(%Conn{params: %{"access_token" => access_token}} = conn, _opts) do
|
||||
authenticate(conn, access_token)
|
||||
end
|
||||
|
||||
def call(%Conn{req_headers: headers} = conn, _opts) do
|
||||
case List.keyfind(headers, "authorization", 0) do
|
||||
{_, "Bearer " <> access_token} ->
|
||||
authenticate(conn, access_token)
|
||||
|
||||
_ ->
|
||||
put_error(conn, :missing_token)
|
||||
end
|
||||
end
|
||||
|
||||
defp authenticate(conn, access_token) do
|
||||
case Account.get_by_access_token(access_token) do
|
||||
%Account{devices: [device]} = account ->
|
||||
conn
|
||||
|> assign(:account, account)
|
||||
|> assign(:device, device)
|
||||
|
||||
nil ->
|
||||
put_error(conn, :unknown_token)
|
||||
end
|
||||
end
|
||||
end
|
Loading…
Add table
Add a link
Reference in a new issue