Implement access token authentication

Add whoami endpoint
This commit is contained in:
Pim Kunis 2021-06-26 00:29:33 +02:00
parent d81a42bf8a
commit dac1a429b9
8 changed files with 96 additions and 4 deletions

View file

@ -0,0 +1,45 @@
defmodule MatrixServerWeb.Authenticate do
import Plug.Conn
import Phoenix.Controller, only: [json: 2]
alias MatrixServer.Account
alias Plug.Conn
def init(options), do: options
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)
_ ->
data = %{errcode: "M_MISSING_TOKEN", error: "Access token missing."}
conn
|> put_status(401)
|> json(data)
|> halt()
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 ->
data = %{errcode: "M_UNKNOWN_TOKEN", error: "Invalid access token."}
conn
|> put_status(401)
|> json(data)
|> halt()
end
end
end

View file

@ -1,6 +1,10 @@
defmodule MatrixServerWeb.AccountController do
use MatrixServerWeb, :controller
import MatrixServer, only: [get_mxid: 1]
alias MatrixServer.Account
alias Plug.Conn
def available(conn, params) do
localpart = Map.get(params, "username", "")
@ -21,4 +25,12 @@ defmodule MatrixServerWeb.AccountController do
|> put_status(status)
|> json(data)
end
def whoami(%Conn{assigns: %{account: %Account{localpart: localpart}}} = conn, _params) do
data = %{user_id: get_mxid(localpart)}
conn
|> put_status(200)
|> json(data)
end
end

View file

@ -1,12 +1,17 @@
defmodule MatrixServerWeb.Router do
use MatrixServerWeb, :router
pipeline :api do
pipeline :public do
plug :accepts, ["json"]
end
pipeline :authenticated do
plug :accepts, ["json"]
plug MatrixServerWeb.Authenticate
end
scope "/_matrix", MatrixServerWeb do
pipe_through :api
pipe_through :public
scope "/client/r0", as: :client do
post "/register", AuthController, :register
@ -16,4 +21,12 @@ defmodule MatrixServerWeb.Router do
get "/client/versions", InfoController, :versions
end
scope "/_matrix", MatrixServerWeb do
pipe_through :authenticated
scope "/client/r0", as: :client do
get "/account/whoami", AccountController, :whoami
end
end
end