defmodule FrenzyWeb.LoginController do use FrenzyWeb, :controller alias Frenzy.{Repo, User} alias FrenzyWeb.Endpoint def login(conn, params) do render(conn, "login.html", %{ continue: Map.get(params, "continue") }) end def login_post(conn, %{"username" => username, "password" => password} = params) do user = Repo.get_by(User, username: username) case Bcrypt.check_pass(user, password) do {:ok, user} -> user_token = Phoenix.Token.sign(Endpoint, "user token", user.id) conn = put_session(conn, :user_token, user_token) redirect_uri = Map.get(params, "continue") || Routes.group_path(Endpoint, :index) redirect(conn, to: redirect_uri) {:error, _reason} -> conn |> put_flash(:error, "Invalid username or password.") |> redirect(to: Routes.login_path(Endpoint, :login)) end end def logout(conn, _params) do conn |> put_flash(:info, "Logged out.") |> clear_session() |> redirect(to: "/") end end