Hash :
3a8aeef0
Author :
Thomas de Grivel
Date :
2021-11-16T11:27:16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
defmodule KmxgitWeb.SessionController do
use KmxgitWeb, :controller
alias Kmxgit.{UserManager, UserManager.User}
def new(conn, params) do
changeset = UserManager.change_user(%User{})
user = UserManager.Guardian.Plug.current_resource(conn)
if user do
redirect(conn, to: params["redirect"] || User.after_login_path(user))
else
redirect = params["redirect"]
action = if redirect do
Routes.session_path(conn, :login, redirect: redirect)
else
Routes.session_path(conn, :login)
end
conn
|> assign(:action, action)
|> assign(:changeset, changeset)
|> assign(:page_title, gettext "Login")
|> render("new.html")
end
end
def login(conn, params = %{"user" => %{"login" => login,
"password" => password}}) do
redirect = params["redirect"] || "/"
conn
|> login_reply(UserManager.authenticate_user(login, password), redirect)
end
def logout(conn, _params) do
conn
|> UserManager.Guardian.Plug.sign_out()
|> redirect(to: Routes.session_path(conn, :new))
end
defp login_reply(conn, {:ok, user}, redirect) do
conn
|> UserManager.Guardian.Plug.sign_in(user)
|> redirect(to: redirect || User.after_login_path(user))
end
defp login_reply(conn, {:error, reason}, _redirect) do
conn
|> put_flash(:error, to_string(reason))
|> new(%{})
end
@behaviour Guardian.Plug.ErrorHandler
@impl Guardian.Plug.ErrorHandler
def auth_error(conn, {type, _reason}, _opts) do
body = to_string(type)
case conn.request_path do
"/sessions/new" ->
conn
|> put_view(KmxgitWeb.SessionView)
|> put_layout({KmxgitWeb.LayoutView, "app.html"})
|> put_flash(:error, body)
|> new(conn.params)
|> halt()
"/sessions/login" ->
conn
|> put_view(KmxgitWeb.SessionView)
|> put_layout({KmxgitWeb.LayoutView, "app.html"})
|> put_flash(:error, body)
|> login(conn.params)
|> halt()
_ ->
conn
|> put_flash(:error, body)
|> redirect(to: Routes.session_path(conn, :new, redirect: current_path(conn) |> halt()
))
end
end
end