frenzy/lib/frenzy_web/controllers/login_controller.ex

39 lines
1.1 KiB
Elixir
Raw Normal View History

2019-03-23 23:42:38 +00:00
defmodule FrenzyWeb.LoginController do
use FrenzyWeb, :controller
alias Frenzy.{Repo, User}
alias FrenzyWeb.Router.Helpers, as: Routes
alias FrenzyWeb.Endpoint
import Ecto.Query
2019-03-28 21:11:25 +00:00
def login(conn, params) do
render(conn, "login.html", %{
continue: Map.get(params, "continue")
})
2019-03-23 23:42:38 +00:00
end
2019-03-28 21:11:25 +00:00
def login_post(conn, %{"username" => username, "password" => password} = params) do
2019-03-23 23:42:38 +00:00
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)
2019-03-28 21:11:25 +00:00
conn = put_session(conn, :user_token, user_token)
2019-03-23 23:42:38 +00:00
2019-03-28 21:11:25 +00:00
redirect_uri = Map.get(params, "continue") || Routes.group_path(Endpoint, :index)
redirect(conn, to: redirect_uri)
2019-03-23 23:42:38 +00:00
{:error, _reason} ->
conn
2019-04-01 15:34:26 +00:00
|> put_flash(:error, "Invalid username or password.")
2019-03-23 23:42:38 +00:00
|> redirect(to: Routes.login_path(Endpoint, :login))
end
end
2019-04-01 15:34:26 +00:00
def logout(conn, params) do
conn
|> put_flash(:info, "Logged out.")
|> clear_session()
|> redirect(to: "/")
end
2019-03-23 23:42:38 +00:00
end