2021-02-24 07:49:39 -05:00
|
|
|
defmodule Bones73kWeb.UserSessionController do
|
|
|
|
use Bones73kWeb, :controller
|
2020-09-12 20:07:02 -04:00
|
|
|
|
2021-03-02 16:48:00 -05:00
|
|
|
alias Phoenix.HTML
|
2021-02-24 07:49:39 -05:00
|
|
|
alias Bones73k.Accounts
|
2021-03-01 13:42:26 -05:00
|
|
|
alias Bones73k.Accounts.User
|
2021-02-24 07:49:39 -05:00
|
|
|
alias Bones73kWeb.UserAuth
|
2020-09-12 20:07:02 -04:00
|
|
|
|
|
|
|
def new(conn, _params) do
|
|
|
|
render(conn, "new.html", error_message: nil)
|
|
|
|
end
|
|
|
|
|
2021-03-01 13:42:26 -05:00
|
|
|
def create(conn, %{"user" => %{"email" => email, "password" => password} = user_params}) do
|
2020-09-12 20:07:02 -04:00
|
|
|
if user = Accounts.get_user_by_email_and_password(email, password) do
|
2021-03-02 16:48:00 -05:00
|
|
|
conn
|
|
|
|
|> put_flash(
|
|
|
|
:info,
|
|
|
|
HTML.raw("Welcome back, #{user.email} — you were logged in successfuly.")
|
|
|
|
)
|
|
|
|
|> UserAuth.log_in_user(user, user_params)
|
2020-09-12 20:07:02 -04:00
|
|
|
else
|
|
|
|
render(conn, "new.html", error_message: "Invalid email or password")
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2021-03-01 13:42:26 -05:00
|
|
|
def create(conn, %{"user" => %{"params_token" => token} = user_params}) do
|
|
|
|
with {:ok, params} <- Phoenix.Token.decrypt(Bones73kWeb.Endpoint, "login_params", token),
|
|
|
|
%User{} = user <- Accounts.get_user(params.user_id) do
|
|
|
|
conn
|
|
|
|
|> collect_messages(params.messages)
|
|
|
|
|> put_session(:user_return_to, params.user_return_to)
|
|
|
|
|> UserAuth.log_in_user(user, Map.put_new(user_params, "remember_me", "false"))
|
|
|
|
else
|
|
|
|
_ -> render(conn, "new.html", error_message: "Invalid email or password")
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
defp collect_messages(conn, messages) do
|
|
|
|
Enum.reduce(messages, conn, fn {type, msg}, acc -> put_flash(acc, type, msg) end)
|
|
|
|
end
|
|
|
|
|
2020-09-12 20:07:02 -04:00
|
|
|
def delete(conn, _params) do
|
|
|
|
conn
|
|
|
|
|> put_flash(:info, "Logged out successfully.")
|
|
|
|
|> UserAuth.log_out_user()
|
|
|
|
end
|
2020-09-28 05:06:15 -04:00
|
|
|
|
|
|
|
def force_logout(conn, _params) do
|
|
|
|
conn
|
|
|
|
|> put_flash(
|
|
|
|
:info,
|
|
|
|
"You were logged out. Please login again to continue using our application."
|
|
|
|
)
|
|
|
|
|> UserAuth.log_out_user()
|
|
|
|
end
|
2020-09-12 20:07:02 -04:00
|
|
|
end
|