Skip to content

Commit 466f445

Browse files
committed
Add error handling to token controller
1 parent 2b73812 commit 466f445

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

test/controllers/token_controller_test.exs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,28 @@ defmodule CodeCorps.TokenControllerTest do
3030
assert_received {:track, ^user_id, "Signed In", %{}}
3131
end
3232

33+
test "does not authenticate and renders errors when the email and password are missing", %{conn: conn} do
34+
conn = post conn, token_path(conn, :create), %{"username" => ""}
35+
36+
response = json_response(conn, 401)
37+
[error | _] = response["errors"]
38+
assert error["detail"] == "Please enter your email and password."
39+
assert renders_401_unauthorized?(error)
40+
refute response["token"]
41+
refute response["user_id"]
42+
end
43+
44+
test "does not authenticate and renders errors when only the password is missing", %{conn: conn} do
45+
conn = post conn, token_path(conn, :create), %{"username" => "test@email.com"}
46+
47+
response = json_response(conn, 401)
48+
[error | _] = response["errors"]
49+
assert error["detail"] == "Please enter your password."
50+
assert renders_401_unauthorized?(error)
51+
refute response["token"]
52+
refute response["user_id"]
53+
end
54+
3355
test "does not authenticate and renders errors when the password is wrong", %{conn: conn} do
3456
user = build(:user, %{password: "password"}) |> set_password("password") |> insert
3557
conn = post conn, token_path(conn, :create), create_payload(user.email, "wrong password")

web/controllers/token_controller.ex

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,12 @@ defmodule CodeCorps.TokenController do
1919
{:error, reason} -> handle_unauthenticated(conn, reason)
2020
end
2121
end
22+
def create(conn, %{"username" => ""}) do
23+
handle_unauthenticated(conn, "Please enter your email and password.")
24+
end
25+
def create(conn, %{"username" => _email}) do
26+
handle_unauthenticated(conn, "Please enter your password.")
27+
end
2228

2329
def refresh(conn, %{"token" => current_token}) do
2430
with {:ok, claims} <- Guardian.decode_and_verify(current_token),

0 commit comments

Comments
 (0)