frenzy/lib/frenzy_web/controllers/login_controller.ex

34 lines
990 B
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
@error_message "Invalid username or password"
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
|> put_flash(:error, @error_message)
|> redirect(to: Routes.login_path(Endpoint, :login))
end
end
end