Skip to content

Commit

Permalink
API to receive a session token for mobile clients
Browse files Browse the repository at this point in the history
  • Loading branch information
sb8244 committed Oct 10, 2019
1 parent effaaa0 commit 711eba5
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/web/controllers/session_token_controller.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
defmodule Web.SessionTokenController do
use Web, :controller

def create(conn = %{assigns: %{session_token: token}}, _params) do
conn
|> put_status(201)
|> json(%{session_token: token})
end
end
7 changes: 7 additions & 0 deletions lib/web/routers/router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ defmodule Web.Router do
end

pipeline :session_token do
plug(:fetch_session)
plug Web.Plugs.SessionToken
end

Expand Down Expand Up @@ -178,6 +179,12 @@ defmodule Web.Router do
post("/token", TokenController, :create)
end

scope "/", Web do
pipe_through([:api, :session_token])

post("/session_tokens", SessionTokenController, :create)
end

if Mix.env() == :dev do
forward("/emails/sent", Bamboo.SentEmailViewerPlug)
end
Expand Down
27 changes: 27 additions & 0 deletions test/web/controllers/session_token_controller_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
defmodule Web.SessionTokenControllerTest do
use Web.ConnCase

describe "POST /session_tokens" do
test "a session token is returned", %{conn: conn} do
conn = post(conn, Routes.session_token_path(Web.Endpoint, :create))
assert %{"session_token" => token} = json_response(conn, 201)

assert {:ok, uuid} =
Phoenix.Token.verify(Web.Endpoint, "session token", token, max_age: 86_400)

assert UUID.info!(uuid)
end

test "an existing session token can be returned", %{conn: conn} do
conn =
conn
|> Plug.Test.init_test_session(session_token: "steve")
|> post(Routes.session_token_path(conn, :create))

assert %{"session_token" => token} = json_response(conn, 201)

assert Phoenix.Token.verify(Web.Endpoint, "session token", token, max_age: 86_400) ==
{:ok, "steve"}
end
end
end

0 comments on commit 711eba5

Please sign in to comment.