frenzy/lib/frenzy_web/controllers/login_controller.ex

32 lines
861 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
def login(conn, _params) do
render(conn, "login.html")
end
@error_message "Invalid username or password"
def login_post(conn, %{"username" => username, "password" => password}) 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(:user_token, user_token)
|> redirect(to: Routes.group_path(Endpoint, :index))
{:error, _reason} ->
conn
|> put_flash(:error, @error_message)
|> redirect(to: Routes.login_path(Endpoint, :login))
end
end
end