clacks/lib/clacks_web/controllers/login_controller.ex

43 lines
1.1 KiB
Elixir
Raw Normal View History

2019-10-02 21:25:35 +00:00
defmodule ClacksWeb.LoginController do
use ClacksWeb, :controller
alias Clacks.User
alias ClacksWeb.Router.Helpers, as: Routes
alias ClacksWeb.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 = User.get_by_username(username)
case Bcrypt.check_pass(user, password) do
{:ok, user} ->
user_token = Phoenix.Token.sign(Endpoint, "user token", user.id)
redirect_uri = Map.get(params, "continue") || "/"
conn
|> put_session(:user_token, user_token)
|> redirect(to: redirect_uri)
{:error, _reason} ->
conn
|> put_flash(:error, "Invalid username or password.")
|> redirect(to: Routes.login_path(Endpoint, :login))
end
end
def login_post(conn, _params) do
redirect(conn, to: Routes.login_path(Endpoint, :login))
end
def logout(conn, _params) do
conn
|> clear_session()
|> put_flash(:info, "Logged out.")
|> redirect(to: "/")
end
end