Skip to content

Commit

Permalink
feat (WIP): Remove all keycloak_auth? branching
Browse files Browse the repository at this point in the history
Now that all of our environments have switched to Keycloak for auth, we
no longer need to support the local auth option.
  • Loading branch information
arkadyan committed Aug 23, 2023
1 parent 16e2304 commit b275ad2
Show file tree
Hide file tree
Showing 17 changed files with 73 additions and 589 deletions.
42 changes: 0 additions & 42 deletions apps/alert_processor/lib/model/user.ex
Original file line number Diff line number Diff line change
Expand Up @@ -242,15 +242,6 @@ defmodule AlertProcessor.Model.User do
end
end

@doc """
Builds a changeset to verify login
"""
def login_changeset(struct, params \\ %{}) do
struct
|> cast(params, [:email, :password])
|> validate_required([:email, :password])
end

def opt_in_phone_number(%__MODULE__{phone_number: nil}), do: {:ok, nil}

def opt_in_phone_number(%__MODULE__{phone_number: phone_number}) do
Expand All @@ -259,39 +250,6 @@ defmodule AlertProcessor.Model.User do
|> AwsClient.request()
end

@doc """
Checks if user's login credentials are valid
"""
def authenticate(%{"email" => email, "password" => password} = params) do
changeset = login_changeset(%__MODULE__{}, params)

case changeset.errors do
[] ->
user = Repo.get_by(__MODULE__, email: String.downcase(email))

cond do
user && user.encrypted_password == "" ->
{:error, :disabled}

check_password(user, password) ->
{:ok, user}

true ->
{:error, changeset}
end

_ ->
{:error, changeset}
end
end

def check_password(user, password) do
case user do
nil -> Bcrypt.no_user_verify()
_ -> Bcrypt.verify_pass(password, user.encrypted_password)
end
end

@doc "Records an email rejection status for a user and disables notifications for them."
def set_email_rejection(user, status) when not is_nil(status),
do: update_email_rejection(user, "none", status, "email-rejection")
Expand Down
55 changes: 0 additions & 55 deletions apps/alert_processor/test/alert_processor/model/user_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,6 @@ defmodule AlertProcessor.Model.UserTest do
"communication_mode" => "email"
}
@invalid_attrs %{}
@password "password1"
@encrypted_password Bcrypt.hash_pwd_salt(@password)
@disabled_password ""

describe "user changeset" do
test "changeset with valid attributes" do
Expand Down Expand Up @@ -194,58 +191,6 @@ defmodule AlertProcessor.Model.UserTest do
end
end

describe "authenticate/1" do
test "authenticates if email and password valid" do
Repo.insert!(%User{
email: "[email protected]",
role: "user",
encrypted_password: @encrypted_password
})

assert {:ok, _} = User.authenticate(%{"email" => "[email protected]", "password" => @password})
end

test "does not authenticate if invalid password for existing user" do
Repo.insert!(%User{
email: "[email protected]",
role: "user",
encrypted_password: @encrypted_password
})

assert {:error, _} =
User.authenticate(%{
"email" => "[email protected]",
"password" => "different_password"
})
end

test "does not authenticate if user doesn't exist" do
assert {:error, _} =
User.authenticate(%{"email" => "[email protected]", "password" => @password})
end

test "does not authenticate if user's account is disabled" do
Repo.insert!(%User{
email: "[email protected]",
role: "user",
encrypted_password: @disabled_password
})

assert {:error, :disabled} =
User.authenticate(%{"email" => "[email protected]", "password" => @password})
end

test "email is not case sensitive" do
Repo.insert!(%User{
email: "[email protected]",
role: "user",
encrypted_password: @encrypted_password
})

assert {:ok, _} = User.authenticate(%{"email" => "[email protected]", "password" => @password})
end
end

describe "set_email_rejection/2" do
test "sets a user's email rejection status and disables notifications" do
user = insert(:user, communication_mode: "email", email_rejection_status: nil)
Expand Down
67 changes: 4 additions & 63 deletions apps/concierge_site/lib/controllers/account_controller.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,55 +4,22 @@ defmodule ConciergeSite.AccountController do
alias AlertProcessor.Model.User
alias AlertProcessor.Repo
alias ConciergeSite.ConfirmationMessage
alias ConciergeSite.SessionHelper
alias ConciergeSite.Mailchimp

require Logger

def new(conn, _params) do
if SessionHelper.keycloak_auth?() do
redirect(conn, to: "/auth/keycloak/register")
else
render(conn, "new.html", account_changeset: new_user_changeset())
end
redirect(conn, to: "/auth/keycloak/register")
end

def edit(%{assigns: %{current_user: user}} = conn, _params) do
conn
|> put_flash(:warning, communication_mode_flash(user))
|> render(edit_template(), changeset: User.changeset(user), user_id: user.id)
|> render("edit.html", changeset: User.changeset(user), user_id: user.id)
end

def edit_password(conn, _params) do
if SessionHelper.keycloak_auth?() do
redirect(conn, external: ConciergeSite.AccountView.edit_password_url(conn))
else
render(conn, "edit_password.html")
end
end

def create(conn, %{"user" => params, "g-recaptcha-response" => recaptcha_response}) do
with {:ok, _resp} <- Recaptcha.verify(recaptcha_response),
{:ok, user} <- User.create_account(params) do
SessionHelper.sign_in(conn, user)
else
{:error, errors} when is_list(errors) ->
Logger.warn("AccountController event=recaptcha_error errors=#{Enum.join(errors, ",")}")

conn
|> put_flash(:error, "reCAPTCHA validation error. Please try again.")
|> render("new.html", account_changeset: new_user_changeset(params))

{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "new.html", account_changeset: changeset, errors: errors(changeset))
end
end

def create(conn, _params) do
conn
|> put_flash(:error, "Required params error. \
Please ensure your web browser is up-to-date and you have JavaScript enabled.")
|> render("new.html", account_changeset: new_user_changeset())
redirect(conn, external: ConciergeSite.AccountView.edit_password_url(conn))
end

def update(%{assigns: %{current_user: user}} = conn, %{"user" => params}) do
Expand All @@ -74,34 +41,14 @@ defmodule ConciergeSite.AccountController do
{:error, changeset} ->
render(
conn,
edit_template(),
"edit.html",
changeset: changeset,
user_id: user.id,
errors: errors(changeset)
)
end
end

def update_password(%{assigns: %{current_user: user}} = conn, %{"user" => params}) do
if User.check_password(user, params["current_password"]) do
case User.update_password(user, %{"password" => params["password"]}, user) do
{:ok, _} ->
conn
|> put_flash(:info, "Your password has been updated.")
|> redirect(to: trip_path(conn, :index))

{:error, _} ->
conn
|> put_flash(:error, "New password format is incorrect. Please try again.")
|> render("edit_password.html")
end
else
conn
|> put_flash(:error, "Current password is incorrect. Please try again.")
|> render("edit_password.html")
end
end

def delete(%{assigns: %{current_user: user}} = conn, _params) do
Mailchimp.delete_member(user)
Repo.delete!(user)
Expand Down Expand Up @@ -144,9 +91,6 @@ defmodule ConciergeSite.AccountController do
end)
end

defp new_user_changeset(params \\ %{"sms_toggle" => false}),
do: User.create_account_changeset(%User{}, params)

defp communication_mode_flash(%User{sms_opted_out_at: sms_opted_out_at} = user)
when not is_nil(sms_opted_out_at) do
communication_mode_flash_for_sms_opt_out(user, User.inside_opt_out_freeze_window?(user))
Expand Down Expand Up @@ -238,7 +182,4 @@ defmodule ConciergeSite.AccountController do
def mailchimp_update(conn, _params) do
json(conn, %{status: "ok", message: "invalid request"})
end

defp edit_template,
do: if(SessionHelper.keycloak_auth?(), do: "edit_keycloak.html", else: "edit.html")
end
20 changes: 1 addition & 19 deletions apps/concierge_site/lib/controllers/session_controller.ex
Original file line number Diff line number Diff line change
@@ -1,28 +1,10 @@
defmodule ConciergeSite.SessionController do
use ConciergeSite.Web, :controller
alias AlertProcessor.Model.User
alias ConciergeSite.SessionHelper
plug(:scrub_params, "user" when action in [:create])

def new(conn, _params) do
if SessionHelper.keycloak_auth?() do
redirect(conn, to: "/auth/keycloak")
else
changeset = User.login_changeset(%User{})
render(conn, "new.html", login_changeset: changeset)
end
end

def create(conn, %{"user" => login_params}) do
case User.authenticate(login_params) do
{:ok, user} ->
SessionHelper.sign_in(conn, user)

{:error, changeset} ->
conn
|> put_flash(:error, "Sorry, your login information was incorrect. Please try again.")
|> render("new.html", login_changeset: changeset)
end
redirect(conn, to: "/auth/keycloak")
end

def delete(conn, _params) do
Expand Down
32 changes: 13 additions & 19 deletions apps/concierge_site/lib/helpers/session_helper.ex
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,12 @@ defmodule ConciergeSite.SessionHelper do

@spec sign_out(Conn.t()) :: Conn.t()
def sign_out(conn) do
redirect_to =
if keycloak_auth?() do
id_token = conn |> Guardian.Plug.current_claims() |> Map.get("id_token")

[
external:
URI.encode(
"#{System.get_env("KEYCLOAK_LOGOUT_URI")}?post_logout_redirect_uri=#{page_url(conn, :landing)}&id_token_hint=#{id_token}"
)
]
else
[to: page_path(conn, :landing)]
end
redirect_to = [
external:
URI.encode(
"#{System.get_env("KEYCLOAK_LOGOUT_URI")}?post_logout_redirect_uri=#{page_url(conn, :landing)}&id_token_hint=#{id_token(conn)}"
)
]

conn
|> put_flash(:info, "You have been signed out.")
Expand All @@ -40,17 +33,18 @@ defmodule ConciergeSite.SessionHelper do
|> redirect(redirect_to)
end

@spec keycloak_auth? :: boolean()
def keycloak_auth? do
Application.get_env(:concierge_site, ConciergeSite.Endpoint)[:authentication_source] ==
"keycloak"
end

defp sign_in_redirect_path(user) do
if Trip.get_trips_by_user(user.id) == [] do
account_path(@endpoint, :options_new)
else
trip_path(@endpoint, :index)
end
end

@spec id_token(Conn.t()) :: String.t()
defp id_token(conn) do
conn
|> Guardian.Plug.current_claims()
|> Map.get("id_token")
end
end
3 changes: 1 addition & 2 deletions apps/concierge_site/lib/router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ defmodule ConciergeSite.Router do
post("/api/feedback", FeedbackController, :new)
get("/digest/feedback", DigestFeedbackController, :feedback)
post("/api/digest/feedback", DigestFeedbackController, :new)
resources("/login", SessionController, only: [:new, :create], singleton: true)
resources("/login", SessionController, only: [:new], singleton: true)
resources("/account", AccountController, only: [:new, :create])
resources("/password_resets", PasswordResetController, only: [:new, :create, :edit, :update])
end
Expand All @@ -80,7 +80,6 @@ defmodule ConciergeSite.Router do
post("/account/edit", AccountController, :update)
delete("/account/delete", AccountController, :delete)
get("/password/edit", AccountController, :edit_password)
post("/password/edit", AccountController, :update_password)

resources("/trips", TripController, only: [:index, :edit, :update, :delete]) do
patch("/pause", TripController, :pause, as: :pause)
Expand Down
Loading

0 comments on commit b275ad2

Please sign in to comment.