diff --git a/lib/kolab_wopi/api.ex b/lib/kolab_wopi/api.ex index b60048c..ab7d37b 100644 --- a/lib/kolab_wopi/api.ex +++ b/lib/kolab_wopi/api.ex @@ -1,102 +1,112 @@ defmodule KolabWopi.API do @moduledoc """ An implementation of the Web Application Open Platform Interface (WOPI) API. See https://wopi.readthedocs.io/en/latest/ """ use Plug.Router use Plug.Debugger require Logger plug Plug.Logger plug :access_token_handler plug :match plug :dispatch def init(options) do options end def start_link do - {:ok, _} = Plug.Adapters.Cowboy.http __MODULE__, [], Application.get_env(:kolab_wopi, :http, []) + startHttp?(Application.get_env(:kolab_wopi, :http)) + startHttps?(Application.get_env(:kolab_wopi, :https)) + end + - startSSL?(Application.get_env(:kolab_wopi, :https)) + defp startHttp?(:nil) do + :no end - defp startSSL?(nil) do + defp startHttp?(http_config) do + Plug.Adapters.Cowboy.http __MODULE__, [], http_config + end + + + defp startHttps?(:nil) do :no end - defp startSSL?(ssl_config) do - Plug.Adapters.Cowboy.https __MODULE__, [], ssl_config + defp startHttps?(https_config) do + Plug.Adapters.Cowboy.https __MODULE__, [], https_config end + forward "/wopi/files", to: __MODULE__.Files forward "/wopi/containers", to: __MODULE__.Containers forward "/wopi/ecosystem", to: __MODULE__.Ecosystem forward "/wopibootstrapper", to: __MODULE__.Bootstrap match _ do send_status_resp(conn, 404) end @doc """ Plug that fetches query parameters and validates the access_token. The access_token parameter is required in every WOPI request. If it's missing "401 Unauthorized" response will be send and request processing aborted. """ def access_token_handler(conn, _opts) do conn = Plug.Conn.fetch_query_params(conn) token = conn.query_params["access_token"] check_token(conn, token) end # valid token handler defp check_token(conn, token) when is_binary(token) and byte_size(token) > 0 do assign(conn, :access_token, token) end # invalid token handler defp check_token(conn, _) do conn |> send_status_resp(401) |> halt() end @doc """ Sends the response with setting status code. It supports Chwala status codes. """ def send_status_resp(conn, code, reason \\ nil) def send_status_resp(conn, 403, reason) do # Chwala uses only 200, 403, 500, 501, 503 send_status_resp(conn, 401, reason) end def send_status_resp(conn, code, _reason) do # TODO: log status reason? send_resp(conn, code, "") end @doc """ Return X-WOPI-Override header value. With some buggy collabora versions support. """ def get_wopi_action(conn) do action = case get_req_header(conn, "x-wopi-override") do a when length(a) > 0 -> a _ -> get_req_header(conn, "x-wopioverride") end to_string(action) end end