Skip to content

Instantly share code, notes, and snippets.

@jeffreybaird
Created May 25, 2016 16:11
Show Gist options
  • Save jeffreybaird/b71497cf24dd2074abc1e9214cbda974 to your computer and use it in GitHub Desktop.
Save jeffreybaird/b71497cf24dd2074abc1e9214cbda974 to your computer and use it in GitHub Desktop.
efmodule Rumbl.UserController do
use Rumbl.Web, :controller
alias Rumbl.User
def index(conn, _params) do
case authenticate(conn) do
%Plug.Conn{halted: true} = conn ->
conn
conn ->
users = Repo.all(User)
render conn, "index.html", users: users
end
end
def show(conn, %{"id" => id}) do
user = Repo.get(Rumbl.User, id)
render conn, "show.html", user: user
end
def new(conn, _params) do
changeset = User.changeset(%User{})
render conn, "new.html", changeset: changeset
end
def create(conn, %{"user" => user_params}) do
changeset = User.registration_changeset(%User{}, user_params)
case Repo.insert(changeset) do
{:ok, user} ->
conn
|> Rumbl.Auth.login(user)
|> put_flash(:info, "#{user.name} created!")
|> redirect(to: user_path(conn, :index))
{:error, changeset} ->
render(conn, "new.html", changeset: changeset)
end
end
defp authenticate(conn) do
if conn.assigns.current_user do
conn
else
conn
|> put_flash(:error, "You must be logged in to access that page")
|> redirect(to: page_path(conn, :index))
|> halt()
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment