Created
May 25, 2016 16:11
-
-
Save jeffreybaird/b71497cf24dd2074abc1e9214cbda974 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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