oauth: implement grant_type=password for single-page apps
[akkoma] / lib / transports.ex
1 defmodule Phoenix.Transports.WebSocket.Raw do
2 import Plug.Conn, only: [
3 fetch_query_params: 1,
4 send_resp: 3
5 ]
6 alias Phoenix.Socket.Transport
7
8 def default_config do
9 [
10 timeout: 60_000,
11 transport_log: false,
12 cowboy: Phoenix.Endpoint.CowboyWebSocket
13 ]
14 end
15
16 def init(%Plug.Conn{method: "GET"} = conn, {endpoint, handler, transport}) do
17 {_, opts} = handler.__transport__(transport)
18
19 conn = conn
20 |> fetch_query_params
21 |> Transport.transport_log(opts[:transport_log])
22 |> Transport.force_ssl(handler, endpoint, opts)
23 |> Transport.check_origin(handler, endpoint, opts)
24
25 case conn do
26 %{halted: false} = conn ->
27 case Transport.connect(endpoint, handler, transport, __MODULE__, nil, conn.params) do
28 {:ok, socket} ->
29 {:ok, conn, {__MODULE__, {socket, opts}}}
30 :error ->
31 send_resp(conn, :forbidden, "")
32 {:error, conn}
33 end
34 _ ->
35 {:error, conn}
36 end
37 end
38
39 def init(conn, _) do
40 send_resp(conn, :bad_request, "")
41 {:error, conn}
42 end
43
44 def ws_init({socket, config}) do
45 Process.flag(:trap_exit, true)
46 {:ok, %{socket: socket}, config[:timeout]}
47 end
48
49 def ws_handle(op, data, state) do
50 state.socket.handler
51 |> apply(:handle, [op, data, state])
52 |> case do
53 {op, data} ->
54 {:reply, {op, data}, state}
55 {op, data, state} ->
56 {:reply, {op, data}, state}
57 %{} = state ->
58 {:ok, state}
59 _ ->
60 {:ok, state}
61 end
62 end
63
64 def ws_info({_,_} = tuple, state) do
65 {:reply, tuple, state}
66 end
67
68 def ws_info(_tuple, state), do: {:ok, state}
69
70 def ws_close(state) do
71 ws_handle(:closed, :normal, state)
72 end
73
74 def ws_terminate(reason, state) do
75 ws_handle(:closed, reason, state)
76 end
77 end