   end
 
   def login(conn, %{"login" => %{"username" => username, "password" => password}}) do
-    # user = Repo.all(from u in User, 
-    #                 where: u.username == ^username,
-    #                 select: u)
-    user = Repo.get_by(User, username: username)
+    user = find_user_and_pass(username, password)
 
     if user do
       conn
       |> put_flash(:info, "Welcome #{user.username}! I like your password #{password}")
-      |> put_session(:username, username)
       |> put_session(:current_user_id, user.id)
       |> redirect(to: user_session_path(conn, :index))
     else
       conn
-      |> put_flash(:error, "Username not found.")
+      |> put_flash(:error, "Username and password not found.")
       |> redirect(to: user_session_path(conn, :index))
     end
   end

defmodule Officetournament.UserSessionController do
  use Officetournament.Web, :controller

  alias Officetournament.Login
  alias Officetournament.User

  plug :find_user
  plug :scrub_params, "login" when action in [:create, :update]

  def index(conn, _params) do

    end
  end

  defp find_user_and_pass(username, password) do
    user = Repo.one(from u in User,
                    where: u.username == ^username,
                    select: u)

    if !is_nil(user) do
      Logger.debug "Testing #{user.username}:#{user.password}" 
    end

    if check_password(user, password) do
      user
    else
      nil
    end
  end

  defp check_password(nil, password) do
    nil
  end

  defp check_password(user, password) do
    user.password == password
  end
end
