frenzy/lib/frenzy_web/controllers/login_controller.ex

34 lines
990 B
Elixir

defmodule FrenzyWeb.LoginController do
use FrenzyWeb, :controller
alias Frenzy.{Repo, User}
alias FrenzyWeb.Router.Helpers, as: Routes
alias FrenzyWeb.Endpoint
import Ecto.Query
def login(conn, params) do
render(conn, "login.html", %{
continue: Map.get(params, "continue")
})
end
@error_message "Invalid username or password"
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, @error_message)
|> redirect(to: Routes.login_path(Endpoint, :login))
end
end
end