changed project/app name

This commit is contained in:
Adam Piontek 2021-02-24 07:49:39 -05:00
parent 4fbafbfa5e
commit cd31432f88
89 changed files with 421 additions and 417 deletions

2
.gitignore vendored
View file

@ -24,7 +24,7 @@ erl_crash.dump
*.ez *.ez
# Ignore package tarball (built via "mix hex.build"). # Ignore package tarball (built via "mix hex.build").
real_estate-*.tar bones73k-*.tar
# If NPM crashes, it generates a log, let's ignore it too. # If NPM crashes, it generates a log, let's ignore it too.
npm-debug.log npm-debug.log

View file

@ -1,4 +1,4 @@
# RealEstate # Bones73k
See full article [here](https://www.leanpanda.com/blog/authentication-and-authorisation-in-phoenix-liveview/). See full article [here](https://www.leanpanda.com/blog/authentication-and-authorisation-in-phoenix-liveview/).

View file

@ -7,15 +7,15 @@
# General application configuration # General application configuration
use Mix.Config use Mix.Config
config :real_estate, config :bones73k,
ecto_repos: [RealEstate.Repo] ecto_repos: [Bones73k.Repo]
# Configures the endpoint # Configures the endpoint
config :real_estate, RealEstateWeb.Endpoint, config :bones73k, Bones73kWeb.Endpoint,
url: [host: "localhost"], url: [host: "localhost"],
secret_key_base: "LdIQmzV5UCWSbB2SdiWFHLgxYNObKq9Za/VyguoILxfOAMDb5IsptKCKtXTRn+Tf", secret_key_base: "LdIQmzV5UCWSbB2SdiWFHLgxYNObKq9Za/VyguoILxfOAMDb5IsptKCKtXTRn+Tf",
render_errors: [view: RealEstateWeb.ErrorView, accepts: ~w(html json), layout: false], render_errors: [view: Bones73kWeb.ErrorView, accepts: ~w(html json), layout: false],
pubsub_server: RealEstate.PubSub, pubsub_server: Bones73k.PubSub,
live_view: [signing_salt: "2D4GC4ac"] live_view: [signing_salt: "2D4GC4ac"]
# Configures Elixir's Logger # Configures Elixir's Logger

View file

@ -9,7 +9,7 @@ use Mix.Config
# manifest is generated by the `mix phx.digest` task, # manifest is generated by the `mix phx.digest` task,
# which you should run after static files are built and # which you should run after static files are built and
# before starting your production server. # before starting your production server.
config :real_estate, RealEstateWeb.Endpoint, config :bones73k, Bones73kWeb.Endpoint,
url: [host: "example.com", port: 80], url: [host: "example.com", port: 80],
cache_static_manifest: "priv/static/cache_manifest.json" cache_static_manifest: "priv/static/cache_manifest.json"
@ -21,7 +21,7 @@ config :logger, level: :info
# To get SSL working, you will need to add the `https` key # To get SSL working, you will need to add the `https` key
# to the previous section and set your `:url` port to 443: # to the previous section and set your `:url` port to 443:
# #
# config :real_estate, RealEstateWeb.Endpoint, # config :bones73k, Bones73kWeb.Endpoint,
# ... # ...
# url: [host: "example.com", port: 443], # url: [host: "example.com", port: 443],
# https: [ # https: [
@ -45,7 +45,7 @@ config :logger, level: :info
# We also recommend setting `force_ssl` in your endpoint, ensuring # We also recommend setting `force_ssl` in your endpoint, ensuring
# no data is ever sent via http, always redirecting to https: # no data is ever sent via http, always redirecting to https:
# #
# config :real_estate, RealEstateWeb.Endpoint, # config :bones73k, Bones73kWeb.Endpoint,
# force_ssl: [hsts: true] # force_ssl: [hsts: true]
# #
# Check `Plug.SSL` for all available options in `force_ssl`. # Check `Plug.SSL` for all available options in `force_ssl`.

View file

@ -1,6 +1,6 @@
defmodule RealEstate do defmodule Bones73k do
@moduledoc """ @moduledoc """
RealEstate keeps the contexts that define your domain Bones73k keeps the contexts that define your domain
and business logic. and business logic.
Contexts are also responsible for managing your data, regardless Contexts are also responsible for managing your data, regardless

View file

@ -1,12 +1,12 @@
defmodule RealEstate.Accounts do defmodule Bones73k.Accounts do
@moduledoc """ @moduledoc """
The Accounts context. The Accounts context.
""" """
import Ecto.Query, warn: false import Ecto.Query, warn: false
alias RealEstate.Repo alias Bones73k.Repo
alias RealEstate.Accounts.{User, UserToken, UserNotifier} alias Bones73k.Accounts.{User, UserToken, UserNotifier}
alias RealEstateWeb.UserAuth alias Bones73kWeb.UserAuth
## Database getters ## Database getters
@ -103,7 +103,7 @@ defmodule RealEstate.Accounts do
Repo.delete_all(UserToken.user_and_contexts_query(user, :all)) Repo.delete_all(UserToken.user_and_contexts_query(user, :all))
# Broadcast to all liveviews to immediately disconnect the user # Broadcast to all liveviews to immediately disconnect the user
RealEstateWeb.Endpoint.broadcast_from( Bones73kWeb.Endpoint.broadcast_from(
self(), self(),
UserAuth.pubsub_topic(), UserAuth.pubsub_topic(),
"logout_user", "logout_user",

View file

@ -1,4 +1,4 @@
defmodule RealEstate.Accounts.User do defmodule Bones73k.Accounts.User do
use Ecto.Schema use Ecto.Schema
import Ecto.Changeset import Ecto.Changeset
import EctoEnum import EctoEnum
@ -48,7 +48,7 @@ defmodule RealEstate.Accounts.User do
|> validate_required([:email]) |> validate_required([:email])
|> validate_format(:email, ~r/^[^\s]+@[^\s]+$/, message: "must have the @ sign and no spaces") |> validate_format(:email, ~r/^[^\s]+@[^\s]+$/, message: "must have the @ sign and no spaces")
|> validate_length(:email, max: 160) |> validate_length(:email, max: 160)
|> unsafe_validate_unique(:email, RealEstate.Repo) |> unsafe_validate_unique(:email, Bones73k.Repo)
|> unique_constraint(:email) |> unique_constraint(:email)
end end
@ -114,7 +114,7 @@ defmodule RealEstate.Accounts.User do
If there is no user or the user doesn't have a password, we call If there is no user or the user doesn't have a password, we call
`Bcrypt.no_user_verify/0` to avoid timing attacks. `Bcrypt.no_user_verify/0` to avoid timing attacks.
""" """
def valid_password?(%RealEstate.Accounts.User{hashed_password: hashed_password}, password) def valid_password?(%Bones73k.Accounts.User{hashed_password: hashed_password}, password)
when is_binary(hashed_password) and byte_size(password) > 0 do when is_binary(hashed_password) and byte_size(password) > 0 do
Bcrypt.verify_pass(password, hashed_password) Bcrypt.verify_pass(password, hashed_password)
end end

View file

@ -1,4 +1,4 @@
defmodule RealEstate.Accounts.UserNotifier do defmodule Bones73k.Accounts.UserNotifier do
# For simplicity, this module simply logs messages to the terminal. # For simplicity, this module simply logs messages to the terminal.
# You should replace it by a proper email or notification tool, such as: # You should replace it by a proper email or notification tool, such as:
# #

View file

@ -1,4 +1,4 @@
defmodule RealEstate.Accounts.UserToken do defmodule Bones73k.Accounts.UserToken do
use Ecto.Schema use Ecto.Schema
import Ecto.Query import Ecto.Query
@ -16,7 +16,7 @@ defmodule RealEstate.Accounts.UserToken do
field :token, :binary field :token, :binary
field :context, :string field :context, :string
field :sent_to, :string field :sent_to, :string
belongs_to :user, RealEstate.Accounts.User belongs_to :user, Bones73k.Accounts.User
timestamps(updated_at: false) timestamps(updated_at: false)
end end
@ -28,7 +28,7 @@ defmodule RealEstate.Accounts.UserToken do
""" """
def build_session_token(user) do def build_session_token(user) do
token = :crypto.strong_rand_bytes(@rand_size) token = :crypto.strong_rand_bytes(@rand_size)
{token, %RealEstate.Accounts.UserToken{token: token, context: "session", user_id: user.id}} {token, %Bones73k.Accounts.UserToken{token: token, context: "session", user_id: user.id}}
end end
@doc """ @doc """
@ -63,7 +63,7 @@ defmodule RealEstate.Accounts.UserToken do
hashed_token = :crypto.hash(@hash_algorithm, token) hashed_token = :crypto.hash(@hash_algorithm, token)
{Base.url_encode64(token, padding: false), {Base.url_encode64(token, padding: false),
%RealEstate.Accounts.UserToken{ %Bones73k.Accounts.UserToken{
token: hashed_token, token: hashed_token,
context: context, context: context,
sent_to: sent_to, sent_to: sent_to,
@ -123,17 +123,17 @@ defmodule RealEstate.Accounts.UserToken do
Returns the given token with the given context. Returns the given token with the given context.
""" """
def token_and_context_query(token, context) do def token_and_context_query(token, context) do
from RealEstate.Accounts.UserToken, where: [token: ^token, context: ^context] from Bones73k.Accounts.UserToken, where: [token: ^token, context: ^context]
end end
@doc """ @doc """
Gets all tokens for the given user for the given contexts. Gets all tokens for the given user for the given contexts.
""" """
def user_and_contexts_query(user, :all) do def user_and_contexts_query(user, :all) do
from t in RealEstate.Accounts.UserToken, where: t.user_id == ^user.id from t in Bones73k.Accounts.UserToken, where: t.user_id == ^user.id
end end
def user_and_contexts_query(user, [_ | _] = contexts) do def user_and_contexts_query(user, [_ | _] = contexts) do
from t in RealEstate.Accounts.UserToken, where: t.user_id == ^user.id and t.context in ^contexts from t in Bones73k.Accounts.UserToken, where: t.user_id == ^user.id and t.context in ^contexts
end end
end end

View file

@ -1,4 +1,4 @@
defmodule RealEstate.Application do defmodule Bones73k.Application do
# See https://hexdocs.pm/elixir/Application.html # See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications # for more information on OTP Applications
@moduledoc false @moduledoc false
@ -8,27 +8,27 @@ defmodule RealEstate.Application do
def start(_type, _args) do def start(_type, _args) do
children = [ children = [
# Start the Ecto repository # Start the Ecto repository
RealEstate.Repo, Bones73k.Repo,
# Start the Telemetry supervisor # Start the Telemetry supervisor
RealEstateWeb.Telemetry, Bones73kWeb.Telemetry,
# Start the PubSub system # Start the PubSub system
{Phoenix.PubSub, name: RealEstate.PubSub}, {Phoenix.PubSub, name: Bones73k.PubSub},
# Start the Endpoint (http/https) # Start the Endpoint (http/https)
RealEstateWeb.Endpoint Bones73kWeb.Endpoint
# Start a worker by calling: RealEstate.Worker.start_link(arg) # Start a worker by calling: Bones73k.Worker.start_link(arg)
# {RealEstate.Worker, arg} # {Bones73k.Worker, arg}
] ]
# See https://hexdocs.pm/elixir/Supervisor.html # See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options # for other strategies and supported options
opts = [strategy: :one_for_one, name: RealEstate.Supervisor] opts = [strategy: :one_for_one, name: Bones73k.Supervisor]
Supervisor.start_link(children, opts) Supervisor.start_link(children, opts)
end end
# Tell Phoenix to update the endpoint configuration # Tell Phoenix to update the endpoint configuration
# whenever the application is updated. # whenever the application is updated.
def config_change(changed, _new, removed) do def config_change(changed, _new, removed) do
RealEstateWeb.Endpoint.config_change(changed, removed) Bones73kWeb.Endpoint.config_change(changed, removed)
:ok :ok
end end
end end

View file

@ -1,12 +1,12 @@
defmodule RealEstate.Properties do defmodule Bones73k.Properties do
@moduledoc """ @moduledoc """
The Properties context. The Properties context.
""" """
import Ecto.Query, warn: false import Ecto.Query, warn: false
alias RealEstate.Repo alias Bones73k.Repo
alias RealEstate.Properties.Property alias Bones73k.Properties.Property
@doc """ @doc """
Returns the list of properties. Returns the list of properties.

View file

@ -1,4 +1,4 @@
defmodule RealEstate.Properties.Property do defmodule Bones73k.Properties.Property do
use Ecto.Schema use Ecto.Schema
import Ecto.Changeset import Ecto.Changeset

View file

@ -1,5 +1,5 @@
defmodule RealEstate.Repo do defmodule Bones73k.Repo do
use Ecto.Repo, use Ecto.Repo,
otp_app: :real_estate, otp_app: :bones73k,
adapter: Ecto.Adapters.Postgres adapter: Ecto.Adapters.Postgres
end end

View file

@ -1,12 +1,12 @@
defmodule RealEstateWeb do defmodule Bones73kWeb do
@moduledoc """ @moduledoc """
The entrypoint for defining your web interface, such The entrypoint for defining your web interface, such
as controllers, views, channels and so on. as controllers, views, channels and so on.
This can be used in your application as: This can be used in your application as:
use RealEstateWeb, :controller use Bones73kWeb, :controller
use RealEstateWeb, :view use Bones73kWeb, :view
The definitions below will be executed for every view, The definitions below will be executed for every view,
controller, etc, so keep them short and clean, focused controller, etc, so keep them short and clean, focused
@ -19,19 +19,19 @@ defmodule RealEstateWeb do
def controller do def controller do
quote do quote do
use Phoenix.Controller, namespace: RealEstateWeb use Phoenix.Controller, namespace: Bones73kWeb
import Plug.Conn import Plug.Conn
import RealEstateWeb.Gettext import Bones73kWeb.Gettext
alias RealEstateWeb.Router.Helpers, as: Routes alias Bones73kWeb.Router.Helpers, as: Routes
end end
end end
def view do def view do
quote do quote do
use Phoenix.View, use Phoenix.View,
root: "lib/real_estate_web/templates", root: "lib/bones73k_web/templates",
namespace: RealEstateWeb namespace: Bones73kWeb
# Import convenience functions from controllers # Import convenience functions from controllers
import Phoenix.Controller, import Phoenix.Controller,
@ -45,12 +45,12 @@ defmodule RealEstateWeb do
def live_view do def live_view do
quote do quote do
use Phoenix.LiveView, use Phoenix.LiveView,
layout: {RealEstateWeb.LayoutView, "live.html"} layout: {Bones73kWeb.LayoutView, "live.html"}
unquote(view_helpers()) unquote(view_helpers())
import RealEstateWeb.LiveHelpers import Bones73kWeb.LiveHelpers
alias RealEstate.Accounts.User alias Bones73k.Accounts.User
@impl true @impl true
def handle_info(%{event: "logout_user", payload: %{user: %User{id: id}}}, socket) do def handle_info(%{event: "logout_user", payload: %{user: %User{id: id}}}, socket) do
@ -86,7 +86,7 @@ defmodule RealEstateWeb do
def channel do def channel do
quote do quote do
use Phoenix.Channel use Phoenix.Channel
import RealEstateWeb.Gettext import Bones73kWeb.Gettext
end end
end end
@ -101,9 +101,9 @@ defmodule RealEstateWeb do
# Import basic rendering functionality (render, render_layout, etc) # Import basic rendering functionality (render, render_layout, etc)
import Phoenix.View import Phoenix.View
import RealEstateWeb.ErrorHelpers import Bones73kWeb.ErrorHelpers
import RealEstateWeb.Gettext import Bones73kWeb.Gettext
alias RealEstateWeb.Router.Helpers, as: Routes alias Bones73kWeb.Router.Helpers, as: Routes
end end
end end

View file

@ -1,8 +1,8 @@
defmodule RealEstateWeb.UserSocket do defmodule Bones73kWeb.UserSocket do
use Phoenix.Socket use Phoenix.Socket
## Channels ## Channels
# channel "room:*", RealEstateWeb.RoomChannel # channel "room:*", Bones73kWeb.RoomChannel
# Socket params are passed from the client and can # Socket params are passed from the client and can
# be used to verify and authenticate a user. After # be used to verify and authenticate a user. After
@ -27,7 +27,7 @@ defmodule RealEstateWeb.UserSocket do
# Would allow you to broadcast a "disconnect" event and terminate # Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user: # all active sockets and channels for a given user:
# #
# RealEstateWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{}) # Bones73kWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
# #
# Returning `nil` makes this socket anonymous. # Returning `nil` makes this socket anonymous.
@impl true @impl true

View file

@ -1,9 +1,9 @@
defmodule RealEstateWeb.UserAuth do defmodule Bones73kWeb.UserAuth do
import Plug.Conn import Plug.Conn
import Phoenix.Controller import Phoenix.Controller
alias RealEstate.Accounts alias Bones73k.Accounts
alias RealEstateWeb.Router.Helpers, as: Routes alias Bones73kWeb.Router.Helpers, as: Routes
@pubsub_topic "user_updates" @pubsub_topic "user_updates"
@ -77,7 +77,7 @@ defmodule RealEstateWeb.UserAuth do
user_token && Accounts.delete_session_token(user_token) user_token && Accounts.delete_session_token(user_token)
if live_socket_id = get_session(conn, :live_socket_id) do if live_socket_id = get_session(conn, :live_socket_id) do
RealEstateWeb.Endpoint.broadcast(live_socket_id, "disconnect", %{}) Bones73kWeb.Endpoint.broadcast(live_socket_id, "disconnect", %{})
end end
conn conn

View file

@ -1,7 +1,7 @@
defmodule RealEstateWeb.UserConfirmationController do defmodule Bones73kWeb.UserConfirmationController do
use RealEstateWeb, :controller use Bones73kWeb, :controller
alias RealEstate.Accounts alias Bones73k.Accounts
def new(conn, _params) do def new(conn, _params) do
render(conn, "new.html") render(conn, "new.html")

View file

@ -1,9 +1,9 @@
defmodule RealEstateWeb.UserRegistrationController do defmodule Bones73kWeb.UserRegistrationController do
use RealEstateWeb, :controller use Bones73kWeb, :controller
alias RealEstate.Accounts alias Bones73k.Accounts
alias RealEstate.Accounts.User alias Bones73k.Accounts.User
alias RealEstateWeb.UserAuth alias Bones73kWeb.UserAuth
def new(conn, _params) do def new(conn, _params) do
changeset = Accounts.change_user_registration(%User{}) changeset = Accounts.change_user_registration(%User{})

View file

@ -1,9 +1,9 @@
defmodule RealEstateWeb.UserResetPasswordController do defmodule Bones73kWeb.UserResetPasswordController do
use RealEstateWeb, :controller use Bones73kWeb, :controller
alias RealEstate.Accounts alias Bones73k.Accounts
plug :get_user_by_reset_password_token when action in [:edit, :update] plug(:get_user_by_reset_password_token when action in [:edit, :update])
def new(conn, _params) do def new(conn, _params) do
render(conn, "new.html") render(conn, "new.html")

View file

@ -1,8 +1,8 @@
defmodule RealEstateWeb.UserSessionController do defmodule Bones73kWeb.UserSessionController do
use RealEstateWeb, :controller use Bones73kWeb, :controller
alias RealEstate.Accounts alias Bones73k.Accounts
alias RealEstateWeb.UserAuth alias Bones73kWeb.UserAuth
def new(conn, _params) do def new(conn, _params) do
render(conn, "new.html", error_message: nil) render(conn, "new.html", error_message: nil)

View file

@ -1,10 +1,10 @@
defmodule RealEstateWeb.UserSettingsController do defmodule Bones73kWeb.UserSettingsController do
use RealEstateWeb, :controller use Bones73kWeb, :controller
alias RealEstate.Accounts alias Bones73k.Accounts
alias RealEstateWeb.UserAuth alias Bones73kWeb.UserAuth
plug :assign_email_and_password_changesets plug(:assign_email_and_password_changesets)
def edit(conn, _params) do def edit(conn, _params) do
render(conn, "edit.html") render(conn, "edit.html")

View file

@ -1,54 +1,58 @@
defmodule RealEstateWeb.Endpoint do defmodule Bones73kWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :real_estate use Phoenix.Endpoint, otp_app: :bones73k
# The session will be stored in the cookie and signed, # The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with. # this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it. # Set :encryption_salt if you would also like to encrypt it.
@session_options [ @session_options [
store: :cookie, store: :cookie,
key: "_real_estate_key", key: "_bones73k_key",
signing_salt: "9CKxo0VJ" signing_salt: "9CKxo0VJ"
] ]
socket "/socket", RealEstateWeb.UserSocket, socket("/socket", Bones73kWeb.UserSocket,
websocket: true, websocket: true,
longpoll: false longpoll: false
)
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]] socket("/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]])
# Serve at "/" the static files from "priv/static" directory. # Serve at "/" the static files from "priv/static" directory.
# #
# You should set gzip to true if you are running phx.digest # You should set gzip to true if you are running phx.digest
# when deploying your static files in production. # when deploying your static files in production.
plug Plug.Static, plug(Plug.Static,
at: "/", at: "/",
from: :real_estate, from: :bones73k,
gzip: false, gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt) only: ~w(css fonts images js favicon.ico robots.txt)
)
# Code reloading can be explicitly enabled under the # Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint. # :code_reloader configuration of your endpoint.
if code_reloading? do if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket socket("/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket)
plug Phoenix.LiveReloader plug(Phoenix.LiveReloader)
plug Phoenix.CodeReloader plug(Phoenix.CodeReloader)
plug Phoenix.Ecto.CheckRepoStatus, otp_app: :real_estate plug(Phoenix.Ecto.CheckRepoStatus, otp_app: :bones73k)
end end
plug Phoenix.LiveDashboard.RequestLogger, plug(Phoenix.LiveDashboard.RequestLogger,
param_key: "request_logger", param_key: "request_logger",
cookie_key: "request_logger" cookie_key: "request_logger"
)
plug Plug.RequestId plug(Plug.RequestId)
plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint] plug(Plug.Telemetry, event_prefix: [:phoenix, :endpoint])
plug Plug.Parsers, plug(Plug.Parsers,
parsers: [:urlencoded, :multipart, :json], parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"], pass: ["*/*"],
json_decoder: Phoenix.json_library() json_decoder: Phoenix.json_library()
)
plug Plug.MethodOverride plug(Plug.MethodOverride)
plug Plug.Head plug(Plug.Head)
plug Plug.Session, @session_options plug(Plug.Session, @session_options)
plug RealEstateWeb.Router plug(Bones73kWeb.Router)
end end

View file

@ -1,11 +1,11 @@
defmodule RealEstateWeb.Gettext do defmodule Bones73kWeb.Gettext do
@moduledoc """ @moduledoc """
A module providing Internationalization with a gettext-based API. A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext), By using [Gettext](https://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example: your module gains a set of macros for translations, for example:
import RealEstateWeb.Gettext import Bones73kWeb.Gettext
# Simple translation # Simple translation
gettext("Here is the string to translate") gettext("Here is the string to translate")
@ -20,5 +20,5 @@ defmodule RealEstateWeb.Gettext do
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage. See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
""" """
use Gettext, otp_app: :real_estate use Gettext, otp_app: :bones73k
end end

View file

@ -1,5 +1,5 @@
defmodule RealEstateWeb.AdminDashboardLive do defmodule Bones73kWeb.AdminDashboardLive do
use RealEstateWeb, :live_view use Bones73kWeb, :live_view
@impl true @impl true
def mount(_params, session, socket) do def mount(_params, session, socket) do

View file

@ -1,20 +1,20 @@
defmodule RealEstateWeb.LiveHelpers do defmodule Bones73kWeb.LiveHelpers do
import Phoenix.LiveView import Phoenix.LiveView
alias RealEstate.Accounts alias Bones73k.Accounts
alias RealEstate.Accounts.User alias Bones73k.Accounts.User
alias RealEstateWeb.Router.Helpers, as: Routes alias Bones73kWeb.Router.Helpers, as: Routes
alias RealEstateWeb.UserAuth alias Bones73kWeb.UserAuth
import Phoenix.LiveView.Helpers import Phoenix.LiveView.Helpers
@doc """ @doc """
Renders a component inside the `RealEstateWeb.ModalComponent` component. Renders a component inside the `Bones73kWeb.ModalComponent` component.
The rendered modal receives a `:return_to` option to properly update The rendered modal receives a `:return_to` option to properly update
the URL when the modal is closed. the URL when the modal is closed.
## Examples ## Examples
<%= live_modal @socket, RealEstateWeb.PropertyLive.FormComponent, <%= live_modal @socket, Bones73kWeb.PropertyLive.FormComponent,
id: @property.id || :new, id: @property.id || :new,
action: @live_action, action: @live_action,
property: @property, property: @property,
@ -23,11 +23,11 @@ defmodule RealEstateWeb.LiveHelpers do
def live_modal(socket, component, opts) do def live_modal(socket, component, opts) do
path = Keyword.fetch!(opts, :return_to) path = Keyword.fetch!(opts, :return_to)
modal_opts = [id: :modal, return_to: path, component: component, opts: opts] modal_opts = [id: :modal, return_to: path, component: component, opts: opts]
live_component(socket, RealEstateWeb.ModalComponent, modal_opts) live_component(socket, Bones73kWeb.ModalComponent, modal_opts)
end end
def assign_defaults(session, socket) do def assign_defaults(session, socket) do
RealEstateWeb.Endpoint.subscribe(UserAuth.pubsub_topic()) Bones73kWeb.Endpoint.subscribe(UserAuth.pubsub_topic())
socket = socket =
assign_new(socket, :current_user, fn -> assign_new(socket, :current_user, fn ->

View file

@ -1,5 +1,5 @@
defmodule RealEstateWeb.ModalComponent do defmodule Bones73kWeb.ModalComponent do
use RealEstateWeb, :live_component use Bones73kWeb, :live_component
@impl true @impl true
def render(assigns) do def render(assigns) do

View file

@ -1,5 +1,5 @@
defmodule RealEstateWeb.PageLive do defmodule Bones73kWeb.PageLive do
use RealEstateWeb, :live_view use Bones73kWeb, :live_view
@impl true @impl true
def mount(_params, session, socket) do def mount(_params, session, socket) do
@ -27,7 +27,7 @@ defmodule RealEstateWeb.PageLive do
end end
defp search(query) do defp search(query) do
if not RealEstateWeb.Endpoint.config(:code_reloader) do if not Bones73kWeb.Endpoint.config(:code_reloader) do
raise "action disabled when not in development" raise "action disabled when not in development"
end end

View file

@ -1,7 +1,7 @@
defmodule RealEstateWeb.PropertyLive.FormComponent do defmodule Bones73kWeb.PropertyLive.FormComponent do
use RealEstateWeb, :live_component use Bones73kWeb, :live_component
alias RealEstate.Properties alias Bones73k.Properties
@impl true @impl true
def update(%{property: property} = assigns, socket) do def update(%{property: property} = assigns, socket) do

View file

@ -1,9 +1,9 @@
defmodule RealEstateWeb.PropertyLive.Index do defmodule Bones73kWeb.PropertyLive.Index do
use RealEstateWeb, :live_view use Bones73kWeb, :live_view
alias RealEstate.Properties alias Bones73k.Properties
alias RealEstate.Properties.Property alias Bones73k.Properties.Property
alias RealEstateWeb.Roles alias Bones73kWeb.Roles
@impl true @impl true
def mount(_params, session, socket) do def mount(_params, session, socket) do
@ -51,7 +51,7 @@ defmodule RealEstateWeb.PropertyLive.Index do
current_user = socket.assigns.current_user current_user = socket.assigns.current_user
property = Properties.get_property!(id) property = Properties.get_property!(id)
if RealEstateWeb.Roles.can?(current_user, property, :delete) do if Bones73kWeb.Roles.can?(current_user, property, :delete) do
property = Properties.get_property!(id) property = Properties.get_property!(id)
{:ok, _} = Properties.delete_property(property) {:ok, _} = Properties.delete_property(property)

View file

@ -1,7 +1,7 @@
<h1>Listing Properties</h1> <h1>Listing Properties</h1>
<%= if @live_action in [:new, :edit] do %> <%= if @live_action in [:new, :edit] do %>
<%= live_modal @socket, RealEstateWeb.PropertyLive.FormComponent, <%= live_modal @socket, Bones73kWeb.PropertyLive.FormComponent,
id: @property.id || :new, id: @property.id || :new,
title: @page_title, title: @page_title,
action: @live_action, action: @live_action,

View file

@ -1,8 +1,8 @@
defmodule RealEstateWeb.PropertyLive.Show do defmodule Bones73kWeb.PropertyLive.Show do
use RealEstateWeb, :live_view use Bones73kWeb, :live_view
alias RealEstate.Properties alias Bones73k.Properties
alias RealEstateWeb.Roles alias Bones73kWeb.Roles
@impl true @impl true
def mount(_params, session, socket) do def mount(_params, session, socket) do

View file

@ -1,7 +1,7 @@
<h1>Show Property</h1> <h1>Show Property</h1>
<%= if @live_action in [:edit] do %> <%= if @live_action in [:edit] do %>
<%= live_modal @socket, RealEstateWeb.PropertyLive.FormComponent, <%= live_modal @socket, Bones73kWeb.PropertyLive.FormComponent,
id: @property.id, id: @property.id,
title: @page_title, title: @page_title,
action: @live_action, action: @live_action,

View file

@ -1,5 +1,5 @@
defmodule RealEstateWeb.UserDashboardLive do defmodule Bones73kWeb.UserDashboardLive do
use RealEstateWeb, :live_view use Bones73kWeb, :live_view
@impl true @impl true
def mount(_params, session, socket) do def mount(_params, session, socket) do

View file

@ -1,4 +1,4 @@
defmodule RealEstateWeb.EnsureRolePlug do defmodule Bones73kWeb.EnsureRolePlug do
@moduledoc """ @moduledoc """
This plug ensures that a user has a particular role before accessing a given route. This plug ensures that a user has a particular role before accessing a given route.
@ -6,15 +6,15 @@ defmodule RealEstateWeb.EnsureRolePlug do
Let's suppose we have three roles: :admin, :manager and :user. Let's suppose we have three roles: :admin, :manager and :user.
If you want a user to have at least manager role, so admins and managers are authorised to access a given route If you want a user to have at least manager role, so admins and managers are authorised to access a given route
plug RealEstateWeb.EnsureRolePlug, [:admin, :manager] plug Bones73kWeb.EnsureRolePlug, [:admin, :manager]
If you want to give access only to an admin: If you want to give access only to an admin:
plug RealEstateWeb.EnsureRolePlug, :admin plug Bones73kWeb.EnsureRolePlug, :admin
""" """
import Plug.Conn import Plug.Conn
alias RealEstate.Accounts alias Bones73k.Accounts
alias RealEstate.Accounts.User alias Bones73k.Accounts.User
alias Phoenix.Controller alias Phoenix.Controller
alias Plug.Conn alias Plug.Conn

View file

@ -1,10 +1,10 @@
defmodule RealEstateWeb.Roles do defmodule Bones73kWeb.Roles do
@moduledoc """ @moduledoc """
Defines roles related functions. Defines roles related functions.
""" """
alias RealEstate.Accounts.User alias Bones73k.Accounts.User
alias RealEstate.Properties.Property alias Bones73k.Properties.Property
@type entity :: struct() @type entity :: struct()
@type action :: :new | :index | :edit | :show | :delete @type action :: :new | :index | :edit | :show | :delete

103
lib/bones73k_web/router.ex Normal file
View file

@ -0,0 +1,103 @@
defmodule Bones73kWeb.Router do
use Bones73kWeb, :router
import Bones73kWeb.UserAuth
alias Bones73kWeb.EnsureRolePlug
pipeline :browser do
plug(:accepts, ["html"])
plug(:fetch_session)
plug(:fetch_live_flash)
plug(:put_root_layout, {Bones73kWeb.LayoutView, :root})
plug(:protect_from_forgery)
plug(:put_secure_browser_headers)
plug(:fetch_current_user)
end
pipeline :api do
plug(:accepts, ["json"])
end
pipeline :user do
plug(EnsureRolePlug, [:admin, :user])
end
pipeline :admin do
plug(EnsureRolePlug, :admin)
end
# Other scopes may use custom stacks.
# scope "/api", Bones73kWeb do
# pipe_through :api
# end
# Enables LiveDashboard only for development
#
# If you want to use the LiveDashboard in production, you should put
# it behind authentication and allow only admins to access it.
# If your application does not have an admins-only section yet,
# you can use Plug.BasicAuth to set up some basic authentication
# as long as you are also using SSL (which you should anyway).
if Mix.env() in [:dev, :test] do
import Phoenix.LiveDashboard.Router
scope "/" do
pipe_through(:browser)
live_dashboard("/dashboard", metrics: Bones73kWeb.Telemetry)
end
end
## Authentication routes
scope "/", Bones73kWeb do
pipe_through([:browser, :redirect_if_user_is_authenticated])
get("/users/register", UserRegistrationController, :new)
post("/users/register", UserRegistrationController, :create)
get("/users/log_in", UserSessionController, :new)
post("/users/log_in", UserSessionController, :create)
get("/users/reset_password", UserResetPasswordController, :new)
post("/users/reset_password", UserResetPasswordController, :create)
get("/users/reset_password/:token", UserResetPasswordController, :edit)
put("/users/reset_password/:token", UserResetPasswordController, :update)
end
scope "/", Bones73kWeb do
pipe_through([:browser, :require_authenticated_user])
get("/users/settings", UserSettingsController, :edit)
put("/users/settings/update_password", UserSettingsController, :update_password)
put("/users/settings/update_email", UserSettingsController, :update_email)
get("/users/settings/confirm_email/:token", UserSettingsController, :confirm_email)
# This line was moved
live("/", PageLive, :index)
end
scope "/", Bones73kWeb do
pipe_through([:browser])
get("/users/force_logout", UserSessionController, :force_logout)
delete("/users/log_out", UserSessionController, :delete)
get("/users/confirm", UserConfirmationController, :new)
post("/users/confirm", UserConfirmationController, :create)
get("/users/confirm/:token", UserConfirmationController, :confirm)
end
scope "/", Bones73kWeb do
pipe_through([:browser, :require_authenticated_user, :user])
live("/user_dashboard", UserDashboardLive, :index)
live("/properties", PropertyLive.Index, :index)
live("/properties/new", PropertyLive.Index, :new)
live("/properties/:id/edit", PropertyLive.Index, :edit)
live("/properties/:id", PropertyLive.Show, :show)
live("/properties/:id/show/edit", PropertyLive.Show, :edit)
end
scope "/", Bones73kWeb do
pipe_through([:browser, :require_authenticated_user, :admin])
live("/admin_dashboard", AdminDashboardLive, :index)
end
end

View file

@ -1,4 +1,4 @@
defmodule RealEstateWeb.Telemetry do defmodule Bones73kWeb.Telemetry do
use Supervisor use Supervisor
import Telemetry.Metrics import Telemetry.Metrics
@ -31,11 +31,11 @@ defmodule RealEstateWeb.Telemetry do
), ),
# Database Metrics # Database Metrics
summary("real_estate.repo.query.total_time", unit: {:native, :millisecond}), summary("bones73k.repo.query.total_time", unit: {:native, :millisecond}),
summary("real_estate.repo.query.decode_time", unit: {:native, :millisecond}), summary("bones73k.repo.query.decode_time", unit: {:native, :millisecond}),
summary("real_estate.repo.query.query_time", unit: {:native, :millisecond}), summary("bones73k.repo.query.query_time", unit: {:native, :millisecond}),
summary("real_estate.repo.query.queue_time", unit: {:native, :millisecond}), summary("bones73k.repo.query.queue_time", unit: {:native, :millisecond}),
summary("real_estate.repo.query.idle_time", unit: {:native, :millisecond}), summary("bones73k.repo.query.idle_time", unit: {:native, :millisecond}),
# VM Metrics # VM Metrics
summary("vm.memory.total", unit: {:byte, :kilobyte}), summary("vm.memory.total", unit: {:byte, :kilobyte}),
@ -49,7 +49,7 @@ defmodule RealEstateWeb.Telemetry do
[ [
# A module, function and arguments to be invoked periodically. # A module, function and arguments to be invoked periodically.
# This function must call :telemetry.execute/3 and a metric must be added above. # This function must call :telemetry.execute/3 and a metric must be added above.
# {RealEstateWeb, :count_users, []} # {Bones73kWeb, :count_users, []}
] ]
end end
end end

View file

@ -5,7 +5,7 @@
<meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<%= csrf_meta_tag() %> <%= csrf_meta_tag() %>
<%= live_title_tag assigns[:page_title] || "RealEstate", suffix: " · Phoenix Framework" %> <%= live_title_tag assigns[:page_title] || "Bones73k", suffix: " · Phoenix Framework" %>
<link phx-track-static rel="stylesheet" href="<%= Routes.static_path(@conn, "/css/app.css") %>"/> <link phx-track-static rel="stylesheet" href="<%= Routes.static_path(@conn, "/css/app.css") %>"/>
<script defer phx-track-static type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script> <script defer phx-track-static type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script>
</head> </head>

View file

@ -1,4 +1,4 @@
defmodule RealEstateWeb.ErrorHelpers do defmodule Bones73kWeb.ErrorHelpers do
@moduledoc """ @moduledoc """
Conveniences for translating and building error messages. Conveniences for translating and building error messages.
""" """
@ -39,9 +39,9 @@ defmodule RealEstateWeb.ErrorHelpers do
# should be written to the errors.po file. The :count option is # should be written to the errors.po file. The :count option is
# set by Ecto and indicates we should also apply plural rules. # set by Ecto and indicates we should also apply plural rules.
if count = opts[:count] do if count = opts[:count] do
Gettext.dngettext(RealEstateWeb.Gettext, "errors", msg, msg, count, opts) Gettext.dngettext(Bones73kWeb.Gettext, "errors", msg, msg, count, opts)
else else
Gettext.dgettext(RealEstateWeb.Gettext, "errors", msg, opts) Gettext.dgettext(Bones73kWeb.Gettext, "errors", msg, opts)
end end
end end
end end

View file

@ -1,5 +1,5 @@
defmodule RealEstateWeb.ErrorView do defmodule Bones73kWeb.ErrorView do
use RealEstateWeb, :view use Bones73kWeb, :view
# If you want to customize a particular status code # If you want to customize a particular status code
# for a certain format, you may uncomment below. # for a certain format, you may uncomment below.

View file

@ -0,0 +1,3 @@
defmodule Bones73kWeb.LayoutView do
use Bones73kWeb, :view
end

View file

@ -0,0 +1,3 @@
defmodule Bones73kWeb.UserConfirmationView do
use Bones73kWeb, :view
end

View file

@ -0,0 +1,3 @@
defmodule Bones73kWeb.UserRegistrationView do
use Bones73kWeb, :view
end

View file

@ -0,0 +1,3 @@
defmodule Bones73kWeb.UserResetPasswordView do
use Bones73kWeb, :view
end

View file

@ -0,0 +1,3 @@
defmodule Bones73kWeb.UserSessionView do
use Bones73kWeb, :view
end

View file

@ -0,0 +1,3 @@
defmodule Bones73kWeb.UserSettingsView do
use Bones73kWeb, :view
end

View file

@ -1,103 +0,0 @@
defmodule RealEstateWeb.Router do
use RealEstateWeb, :router
import RealEstateWeb.UserAuth
alias RealEstateWeb.EnsureRolePlug
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {RealEstateWeb.LayoutView, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
plug :fetch_current_user
end
pipeline :api do
plug :accepts, ["json"]
end
pipeline :user do
plug EnsureRolePlug, [:admin, :user]
end
pipeline :admin do
plug EnsureRolePlug, :admin
end
# Other scopes may use custom stacks.
# scope "/api", RealEstateWeb do
# pipe_through :api
# end
# Enables LiveDashboard only for development
#
# If you want to use the LiveDashboard in production, you should put
# it behind authentication and allow only admins to access it.
# If your application does not have an admins-only section yet,
# you can use Plug.BasicAuth to set up some basic authentication
# as long as you are also using SSL (which you should anyway).
if Mix.env() in [:dev, :test] do
import Phoenix.LiveDashboard.Router
scope "/" do
pipe_through :browser
live_dashboard "/dashboard", metrics: RealEstateWeb.Telemetry
end
end
## Authentication routes
scope "/", RealEstateWeb do
pipe_through [:browser, :redirect_if_user_is_authenticated]
get "/users/register", UserRegistrationController, :new
post "/users/register", UserRegistrationController, :create
get "/users/log_in", UserSessionController, :new
post "/users/log_in", UserSessionController, :create
get "/users/reset_password", UserResetPasswordController, :new
post "/users/reset_password", UserResetPasswordController, :create
get "/users/reset_password/:token", UserResetPasswordController, :edit
put "/users/reset_password/:token", UserResetPasswordController, :update
end
scope "/", RealEstateWeb do
pipe_through [:browser, :require_authenticated_user]
get "/users/settings", UserSettingsController, :edit
put "/users/settings/update_password", UserSettingsController, :update_password
put "/users/settings/update_email", UserSettingsController, :update_email
get "/users/settings/confirm_email/:token", UserSettingsController, :confirm_email
# This line was moved
live "/", PageLive, :index
end
scope "/", RealEstateWeb do
pipe_through [:browser]
get "/users/force_logout", UserSessionController, :force_logout
delete "/users/log_out", UserSessionController, :delete
get "/users/confirm", UserConfirmationController, :new
post "/users/confirm", UserConfirmationController, :create
get "/users/confirm/:token", UserConfirmationController, :confirm
end
scope "/", RealEstateWeb do
pipe_through [:browser, :require_authenticated_user, :user]
live "/user_dashboard", UserDashboardLive, :index
live "/properties", PropertyLive.Index, :index
live "/properties/new", PropertyLive.Index, :new
live "/properties/:id/edit", PropertyLive.Index, :edit
live "/properties/:id", PropertyLive.Show, :show
live "/properties/:id/show/edit", PropertyLive.Show, :edit
end
scope "/", RealEstateWeb do
pipe_through [:browser, :require_authenticated_user, :admin]
live "/admin_dashboard", AdminDashboardLive, :index
end
end

View file

@ -1,3 +0,0 @@
defmodule RealEstateWeb.LayoutView do
use RealEstateWeb, :view
end

View file

@ -1,3 +0,0 @@
defmodule RealEstateWeb.UserConfirmationView do
use RealEstateWeb, :view
end

View file

@ -1,3 +0,0 @@
defmodule RealEstateWeb.UserRegistrationView do
use RealEstateWeb, :view
end

View file

@ -1,3 +0,0 @@
defmodule RealEstateWeb.UserResetPasswordView do
use RealEstateWeb, :view
end

View file

@ -1,3 +0,0 @@
defmodule RealEstateWeb.UserSessionView do
use RealEstateWeb, :view
end

View file

@ -1,3 +0,0 @@
defmodule RealEstateWeb.UserSettingsView do
use RealEstateWeb, :view
end

View file

@ -1,9 +1,9 @@
defmodule RealEstate.MixProject do defmodule Bones73k.MixProject do
use Mix.Project use Mix.Project
def project do def project do
[ [
app: :real_estate, app: :bones73k,
version: "0.1.0", version: "0.1.0",
elixir: "~> 1.7", elixir: "~> 1.7",
elixirc_paths: elixirc_paths(Mix.env()), elixirc_paths: elixirc_paths(Mix.env()),
@ -19,7 +19,7 @@ defmodule RealEstate.MixProject do
# Type `mix help compile.app` for more information. # Type `mix help compile.app` for more information.
def application do def application do
[ [
mod: {RealEstate.Application, []}, mod: {Bones73k.Application, []},
extra_applications: [:logger, :runtime_tools] extra_applications: [:logger, :runtime_tools]
] ]
end end

View file

@ -1,27 +1,27 @@
defmodule RealEstate.Repo.Migrations.CreateUsersAuthTables do defmodule Bones73k.Repo.Migrations.CreateUsersAuthTables do
use Ecto.Migration use Ecto.Migration
def change do def change do
execute "CREATE EXTENSION IF NOT EXISTS citext", "" execute("CREATE EXTENSION IF NOT EXISTS citext", "")
create table(:users) do create table(:users) do
add :email, :citext, null: false add(:email, :citext, null: false)
add :hashed_password, :string, null: false add(:hashed_password, :string, null: false)
add :confirmed_at, :naive_datetime add(:confirmed_at, :naive_datetime)
timestamps() timestamps()
end end
create unique_index(:users, [:email]) create(unique_index(:users, [:email]))
create table(:users_tokens) do create table(:users_tokens) do
add :user_id, references(:users, on_delete: :delete_all), null: false add(:user_id, references(:users, on_delete: :delete_all), null: false)
add :token, :binary, null: false add(:token, :binary, null: false)
add :context, :string, null: false add(:context, :string, null: false)
add :sent_to, :string add(:sent_to, :string)
timestamps(updated_at: false) timestamps(updated_at: false)
end end
create index(:users_tokens, [:user_id]) create(index(:users_tokens, [:user_id]))
create unique_index(:users_tokens, [:context, :token]) create(unique_index(:users_tokens, [:context, :token]))
end end
end end

View file

@ -1,19 +1,19 @@
defmodule RealEstate.Repo.Migrations.AddRoleToUsers do defmodule Bones73k.Repo.Migrations.AddRoleToUsers do
use Ecto.Migration use Ecto.Migration
alias RealEstate.Accounts.User.RolesEnum alias Bones73k.Accounts.User.RolesEnum
def up do def up do
RolesEnum.create_type() RolesEnum.create_type()
alter table(:users) do alter table(:users) do
add :role, RolesEnum.type(), null: false add(:role, RolesEnum.type(), null: false)
end end
end end
def down do def down do
alter table(:users) do alter table(:users) do
remove :role remove(:role)
end end
RolesEnum.drop_type() RolesEnum.drop_type()

View file

@ -1,16 +1,16 @@
defmodule RealEstate.Repo.Migrations.CreateProperties do defmodule Bones73k.Repo.Migrations.CreateProperties do
use Ecto.Migration use Ecto.Migration
def change do def change do
create table(:properties) do create table(:properties) do
add :name, :string add(:name, :string)
add :price, :decimal add(:price, :decimal)
add :description, :text add(:description, :text)
add :user_id, references(:users, on_delete: :nothing) add(:user_id, references(:users, on_delete: :nothing))
timestamps() timestamps()
end end
create index(:properties, [:user_id]) create(index(:properties, [:user_id]))
end end
end end

View file

@ -5,27 +5,27 @@
# Inside the script, you can read and write to any of your # Inside the script, you can read and write to any of your
# repositories directly: # repositories directly:
# #
# RealEstate.Repo.insert!(%RealEstate.SomeSchema{}) # Bones73k.Repo.insert!(%Bones73k.SomeSchema{})
# #
# We recommend using the bang functions (`insert!`, `update!` # We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong. # and so on) as they will fail if something goes wrong.
{:ok, admin} = {:ok, admin} =
RealEstate.Accounts.register_admin(%{ Bones73k.Accounts.register_admin(%{
email: "admin@company.com", email: "admin@company.com",
password: "123456789abc", password: "123456789abc",
password_confirmation: "123456789abc" password_confirmation: "123456789abc"
}) })
{:ok, user_1} = {:ok, user_1} =
RealEstate.Accounts.register_user(%{ Bones73k.Accounts.register_user(%{
email: "user1@company.com", email: "user1@company.com",
password: "123456789abc", password: "123456789abc",
password_confirmation: "123456789abc" password_confirmation: "123456789abc"
}) })
{:ok, user_2} = {:ok, user_2} =
RealEstate.Accounts.register_user(%{ Bones73k.Accounts.register_user(%{
email: "user2@company.com", email: "user2@company.com",
password: "123456789abc", password: "123456789abc",
password_confirmation: "123456789abc" password_confirmation: "123456789abc"
@ -38,7 +38,7 @@ Enum.each(1..10, fn i ->
description: "Property that belongs to user 1", description: "Property that belongs to user 1",
user_id: user_1.id user_id: user_1.id
} }
|> RealEstate.Properties.create_property() |> Bones73k.Properties.create_property()
%{ %{
name: "Property #{i} - User 2", name: "Property #{i} - User 2",
@ -46,7 +46,7 @@ Enum.each(1..10, fn i ->
description: "Property that belongs to user 2", description: "Property that belongs to user 2",
user_id: user_2.id user_id: user_2.id
} }
|> RealEstate.Properties.create_property() |> Bones73k.Properties.create_property()
%{ %{
name: "Property #{i} - Admin", name: "Property #{i} - Admin",
@ -54,5 +54,5 @@ Enum.each(1..10, fn i ->
description: "Property that belongs to admin", description: "Property that belongs to admin",
user_id: admin.id user_id: admin.id
} }
|> RealEstate.Properties.create_property() |> Bones73k.Properties.create_property()
end) end)

View file

@ -1,9 +1,9 @@
defmodule RealEstate.AccountsTest do defmodule Bones73k.AccountsTest do
use RealEstate.DataCase use Bones73k.DataCase
alias RealEstate.Accounts alias Bones73k.Accounts
import RealEstate.AccountsFixtures import Bones73k.AccountsFixtures
alias RealEstate.Accounts.{User, UserToken} alias Bones73k.Accounts.{User, UserToken}
describe "get_user_by_email/1" do describe "get_user_by_email/1" do
test "does not return the user if the email does not exist" do test "does not return the user if the email does not exist" do

View file

@ -1,11 +1,11 @@
defmodule RealEstate.PropertiesTest do defmodule Bones73k.PropertiesTest do
use RealEstate.DataCase use Bones73k.DataCase
alias RealEstate.Properties alias Bones73k.Properties
import RealEstate.AccountsFixtures import Bones73k.AccountsFixtures
describe "properties" do describe "properties" do
alias RealEstate.Properties.Property alias Bones73k.Properties.Property
@valid_attrs %{description: "some description", name: "some name", price: "120.5"} @valid_attrs %{description: "some description", name: "some name", price: "120.5"}
@update_attrs %{ @update_attrs %{

View file

@ -1,14 +1,14 @@
defmodule RealEstateWeb.UserAuthTest do defmodule Bones73kWeb.UserAuthTest do
use RealEstateWeb.ConnCase, async: true use Bones73kWeb.ConnCase, async: true
alias RealEstate.Accounts alias Bones73k.Accounts
alias RealEstateWeb.UserAuth alias Bones73kWeb.UserAuth
import RealEstate.AccountsFixtures import Bones73k.AccountsFixtures
setup %{conn: conn} do setup %{conn: conn} do
conn = conn =
conn conn
|> Map.replace!(:secret_key_base, RealEstateWeb.Endpoint.config(:secret_key_base)) |> Map.replace!(:secret_key_base, Bones73kWeb.Endpoint.config(:secret_key_base))
|> init_test_session(%{}) |> init_test_session(%{})
%{user: user_fixture(), conn: conn} %{user: user_fixture(), conn: conn}
@ -63,7 +63,7 @@ defmodule RealEstateWeb.UserAuthTest do
test "broadcasts to the given live_socket_id", %{conn: conn} do test "broadcasts to the given live_socket_id", %{conn: conn} do
live_socket_id = "users_sessions:abcdef-token" live_socket_id = "users_sessions:abcdef-token"
RealEstateWeb.Endpoint.subscribe(live_socket_id) Bones73kWeb.Endpoint.subscribe(live_socket_id)
conn conn
|> put_session(:live_socket_id, live_socket_id) |> put_session(:live_socket_id, live_socket_id)

View file

@ -1,9 +1,9 @@
defmodule RealEstateWeb.UserConfirmationControllerTest do defmodule Bones73kWeb.UserConfirmationControllerTest do
use RealEstateWeb.ConnCase, async: true use Bones73kWeb.ConnCase, async: true
alias RealEstate.Accounts alias Bones73k.Accounts
alias RealEstate.Repo alias Bones73k.Repo
import RealEstate.AccountsFixtures import Bones73k.AccountsFixtures
setup do setup do
%{user: user_fixture()} %{user: user_fixture()}

View file

@ -1,7 +1,7 @@
defmodule RealEstateWeb.UserRegistrationControllerTest do defmodule Bones73kWeb.UserRegistrationControllerTest do
use RealEstateWeb.ConnCase, async: true use Bones73kWeb.ConnCase, async: true
import RealEstate.AccountsFixtures import Bones73k.AccountsFixtures
describe "GET /users/register" do describe "GET /users/register" do
test "renders registration page", %{conn: conn} do test "renders registration page", %{conn: conn} do

View file

@ -1,9 +1,9 @@
defmodule RealEstateWeb.UserResetPasswordControllerTest do defmodule Bones73kWeb.UserResetPasswordControllerTest do
use RealEstateWeb.ConnCase, async: true use Bones73kWeb.ConnCase, async: true
alias RealEstate.Accounts alias Bones73k.Accounts
alias RealEstate.Repo alias Bones73k.Repo
import RealEstate.AccountsFixtures import Bones73k.AccountsFixtures
setup do setup do
%{user: user_fixture()} %{user: user_fixture()}

View file

@ -1,7 +1,7 @@
defmodule RealEstateWeb.UserSessionControllerTest do defmodule Bones73kWeb.UserSessionControllerTest do
use RealEstateWeb.ConnCase, async: true use Bones73kWeb.ConnCase, async: true
import RealEstate.AccountsFixtures import Bones73k.AccountsFixtures
setup do setup do
%{user: user_fixture()} %{user: user_fixture()}

View file

@ -1,8 +1,8 @@
defmodule RealEstateWeb.UserSettingsControllerTest do defmodule Bones73kWeb.UserSettingsControllerTest do
use RealEstateWeb.ConnCase, async: true use Bones73kWeb.ConnCase, async: true
alias RealEstate.Accounts alias Bones73k.Accounts
import RealEstate.AccountsFixtures import Bones73k.AccountsFixtures
setup :register_and_log_in_user setup :register_and_log_in_user

View file

@ -1,8 +1,8 @@
defmodule RealEstateWeb.AdminDashboardLiveTest do defmodule Bones73kWeb.AdminDashboardLiveTest do
use RealEstateWeb.ConnCase use Bones73kWeb.ConnCase
import Phoenix.LiveViewTest import Phoenix.LiveViewTest
import RealEstate.AccountsFixtures import Bones73k.AccountsFixtures
test "disconnected and connected render without authentication should redirect to login page", test "disconnected and connected render without authentication should redirect to login page",
%{conn: conn} do %{conn: conn} do
@ -38,7 +38,7 @@ defmodule RealEstateWeb.AdminDashboardLiveTest do
assert disconnected_html =~ "Welcome to the admin dashboard!" assert disconnected_html =~ "Welcome to the admin dashboard!"
assert render(admin_dashboard) =~ "Welcome to the admin dashboard!" assert render(admin_dashboard) =~ "Welcome to the admin dashboard!"
RealEstate.Accounts.logout_user(admin) Bones73k.Accounts.logout_user(admin)
# Assert our liveview process is down # Assert our liveview process is down
ref = Process.monitor(admin_dashboard.pid) ref = Process.monitor(admin_dashboard.pid)
@ -70,7 +70,7 @@ defmodule RealEstateWeb.AdminDashboardLiveTest do
assert disconnected_html =~ "Welcome to the admin dashboard!" assert disconnected_html =~ "Welcome to the admin dashboard!"
assert render(admin_dashboard) =~ "Welcome to the admin dashboard!" assert render(admin_dashboard) =~ "Welcome to the admin dashboard!"
RealEstate.Accounts.logout_user(admin2) Bones73k.Accounts.logout_user(admin2)
# Assert our liveview is alive # Assert our liveview is alive
ref = Process.monitor(admin_dashboard.pid) ref = Process.monitor(admin_dashboard.pid)

View file

@ -1,8 +1,8 @@
defmodule RealEstateWeb.PageLiveTest do defmodule Bones73kWeb.PageLiveTest do
use RealEstateWeb.ConnCase use Bones73kWeb.ConnCase
import Phoenix.LiveViewTest import Phoenix.LiveViewTest
import RealEstate.AccountsFixtures import Bones73k.AccountsFixtures
test "disconnected and connected render without authentication should redirect to login page", test "disconnected and connected render without authentication should redirect to login page",
%{conn: conn} do %{conn: conn} do
@ -30,7 +30,7 @@ defmodule RealEstateWeb.PageLiveTest do
assert disconnected_html =~ "Welcome to Phoenix!" assert disconnected_html =~ "Welcome to Phoenix!"
assert render(page_live) =~ "Welcome to Phoenix!" assert render(page_live) =~ "Welcome to Phoenix!"
RealEstate.Accounts.logout_user(user) Bones73k.Accounts.logout_user(user)
# Assert our liveview process is down # Assert our liveview process is down
ref = Process.monitor(page_live.pid) ref = Process.monitor(page_live.pid)
@ -62,7 +62,7 @@ defmodule RealEstateWeb.PageLiveTest do
assert disconnected_html =~ "Welcome to Phoenix!" assert disconnected_html =~ "Welcome to Phoenix!"
assert render(page_live) =~ "Welcome to Phoenix!" assert render(page_live) =~ "Welcome to Phoenix!"
RealEstate.Accounts.logout_user(user1) Bones73k.Accounts.logout_user(user1)
# Assert our liveview is alive # Assert our liveview is alive
ref = Process.monitor(page_live.pid) ref = Process.monitor(page_live.pid)

View file

@ -1,10 +1,10 @@
defmodule RealEstateWeb.PropertyLiveTest do defmodule Bones73kWeb.PropertyLiveTest do
use RealEstateWeb.ConnCase use Bones73kWeb.ConnCase
import Phoenix.LiveViewTest import Phoenix.LiveViewTest
import RealEstate.AccountsFixtures import Bones73k.AccountsFixtures
alias RealEstate.Properties alias Bones73k.Properties
@create_attrs %{description: "some description", name: "some name", price: "120.5"} @create_attrs %{description: "some description", name: "some name", price: "120.5"}
@update_attrs %{ @update_attrs %{
@ -181,7 +181,7 @@ defmodule RealEstateWeb.PropertyLiveTest do
assert html =~ "Listing Properties" assert html =~ "Listing Properties"
assert render(index_live) =~ "Listing Properties" assert render(index_live) =~ "Listing Properties"
RealEstate.Accounts.logout_user(user) Bones73k.Accounts.logout_user(user)
# Assert our liveview process is down # Assert our liveview process is down
ref = Process.monitor(index_live.pid) ref = Process.monitor(index_live.pid)
@ -214,7 +214,7 @@ defmodule RealEstateWeb.PropertyLiveTest do
assert html =~ "Listing Properties" assert html =~ "Listing Properties"
assert render(index_live) =~ "Listing Properties" assert render(index_live) =~ "Listing Properties"
RealEstate.Accounts.logout_user(user1) Bones73k.Accounts.logout_user(user1)
# Assert our liveview is alive # Assert our liveview is alive
ref = Process.monitor(index_live.pid) ref = Process.monitor(index_live.pid)
@ -324,7 +324,7 @@ defmodule RealEstateWeb.PropertyLiveTest do
assert html =~ property.description assert html =~ property.description
assert render(show_live) =~ property.description assert render(show_live) =~ property.description
RealEstate.Accounts.logout_user(user) Bones73k.Accounts.logout_user(user)
# Assert our liveview process is down # Assert our liveview process is down
ref = Process.monitor(show_live.pid) ref = Process.monitor(show_live.pid)
@ -356,7 +356,7 @@ defmodule RealEstateWeb.PropertyLiveTest do
assert html =~ property.description assert html =~ property.description
assert render(show_live) =~ property.description assert render(show_live) =~ property.description
RealEstate.Accounts.logout_user(user1) Bones73k.Accounts.logout_user(user1)
# Assert our liveview is alive # Assert our liveview is alive
ref = Process.monitor(show_live.pid) ref = Process.monitor(show_live.pid)

View file

@ -1,8 +1,8 @@
defmodule RealEstateWeb.UserDashboardLiveTest do defmodule Bones73kWeb.UserDashboardLiveTest do
use RealEstateWeb.ConnCase use Bones73kWeb.ConnCase
import Phoenix.LiveViewTest import Phoenix.LiveViewTest
import RealEstate.AccountsFixtures import Bones73k.AccountsFixtures
test "disconnected and connected render without authentication should redirect to login page", test "disconnected and connected render without authentication should redirect to login page",
%{conn: conn} do %{conn: conn} do
@ -40,7 +40,7 @@ defmodule RealEstateWeb.UserDashboardLiveTest do
assert disconnected_html =~ "Welcome to the user dashboard!" assert disconnected_html =~ "Welcome to the user dashboard!"
assert render(user_dashboard) =~ "Welcome to the user dashboard!" assert render(user_dashboard) =~ "Welcome to the user dashboard!"
RealEstate.Accounts.logout_user(user) Bones73k.Accounts.logout_user(user)
# Assert our liveview process is down # Assert our liveview process is down
ref = Process.monitor(user_dashboard.pid) ref = Process.monitor(user_dashboard.pid)
@ -72,7 +72,7 @@ defmodule RealEstateWeb.UserDashboardLiveTest do
assert disconnected_html =~ "Welcome to the user dashboard!" assert disconnected_html =~ "Welcome to the user dashboard!"
assert render(user_dashboard) =~ "Welcome to the user dashboard!" assert render(user_dashboard) =~ "Welcome to the user dashboard!"
RealEstate.Accounts.logout_user(user2) Bones73k.Accounts.logout_user(user2)
# Assert our liveview is alive # Assert our liveview is alive
ref = Process.monitor(user_dashboard.pid) ref = Process.monitor(user_dashboard.pid)

View file

@ -0,0 +1,14 @@
defmodule Bones73kWeb.ErrorViewTest do
use Bones73kWeb.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.html" do
assert render_to_string(Bones73kWeb.ErrorView, "404.html", []) == "Not Found"
end
test "renders 500.html" do
assert render_to_string(Bones73kWeb.ErrorView, "500.html", []) == "Internal Server Error"
end
end

View file

@ -1,5 +1,5 @@
defmodule RealEstateWeb.LayoutViewTest do defmodule Bones73kWeb.LayoutViewTest do
use RealEstateWeb.ConnCase, async: true use Bones73kWeb.ConnCase, async: true
# When testing helpers, you may want to import Phoenix.HTML and # When testing helpers, you may want to import Phoenix.HTML and
# use functions such as safe_to_string() to convert the helper # use functions such as safe_to_string() to convert the helper

View file

@ -1,14 +0,0 @@
defmodule RealEstateWeb.ErrorViewTest do
use RealEstateWeb.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.html" do
assert render_to_string(RealEstateWeb.ErrorView, "404.html", []) == "Not Found"
end
test "renders 500.html" do
assert render_to_string(RealEstateWeb.ErrorView, "500.html", []) == "Internal Server Error"
end
end

View file

@ -1,4 +1,4 @@
defmodule RealEstateWeb.ChannelCase do defmodule Bones73kWeb.ChannelCase do
@moduledoc """ @moduledoc """
This module defines the test case to be used by This module defines the test case to be used by
channel tests. channel tests.
@ -11,7 +11,7 @@ defmodule RealEstateWeb.ChannelCase do
we enable the SQL sandbox, so changes done to the database we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously PostgreSQL, you can even run database tests asynchronously
by setting `use RealEstateWeb.ChannelCase, async: true`, although by setting `use Bones73kWeb.ChannelCase, async: true`, although
this option is not recommended for other databases. this option is not recommended for other databases.
""" """
@ -21,18 +21,18 @@ defmodule RealEstateWeb.ChannelCase do
quote do quote do
# Import conveniences for testing with channels # Import conveniences for testing with channels
import Phoenix.ChannelTest import Phoenix.ChannelTest
import RealEstateWeb.ChannelCase import Bones73kWeb.ChannelCase
# The default endpoint for testing # The default endpoint for testing
@endpoint RealEstateWeb.Endpoint @endpoint Bones73kWeb.Endpoint
end end
end end
setup tags do setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(RealEstate.Repo) :ok = Ecto.Adapters.SQL.Sandbox.checkout(Bones73k.Repo)
unless tags[:async] do unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(RealEstate.Repo, {:shared, self()}) Ecto.Adapters.SQL.Sandbox.mode(Bones73k.Repo, {:shared, self()})
end end
:ok :ok

View file

@ -1,4 +1,4 @@
defmodule RealEstateWeb.ConnCase do defmodule Bones73kWeb.ConnCase do
@moduledoc """ @moduledoc """
This module defines the test case to be used by This module defines the test case to be used by
tests that require setting up a connection. tests that require setting up a connection.
@ -11,7 +11,7 @@ defmodule RealEstateWeb.ConnCase do
we enable the SQL sandbox, so changes done to the database we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously PostgreSQL, you can even run database tests asynchronously
by setting `use RealEstateWeb.ConnCase, async: true`, although by setting `use Bones73kWeb.ConnCase, async: true`, although
this option is not recommended for other databases. this option is not recommended for other databases.
""" """
@ -22,20 +22,20 @@ defmodule RealEstateWeb.ConnCase do
# Import conveniences for testing with connections # Import conveniences for testing with connections
import Plug.Conn import Plug.Conn
import Phoenix.ConnTest import Phoenix.ConnTest
import RealEstateWeb.ConnCase import Bones73kWeb.ConnCase
alias RealEstateWeb.Router.Helpers, as: Routes alias Bones73kWeb.Router.Helpers, as: Routes
# The default endpoint for testing # The default endpoint for testing
@endpoint RealEstateWeb.Endpoint @endpoint Bones73kWeb.Endpoint
end end
end end
setup tags do setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(RealEstate.Repo) :ok = Ecto.Adapters.SQL.Sandbox.checkout(Bones73k.Repo)
unless tags[:async] do unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(RealEstate.Repo, {:shared, self()}) Ecto.Adapters.SQL.Sandbox.mode(Bones73k.Repo, {:shared, self()})
end end
{:ok, conn: Phoenix.ConnTest.build_conn()} {:ok, conn: Phoenix.ConnTest.build_conn()}
@ -50,7 +50,7 @@ defmodule RealEstateWeb.ConnCase do
test context. test context.
""" """
def register_and_log_in_user(%{conn: conn}) do def register_and_log_in_user(%{conn: conn}) do
user = RealEstate.AccountsFixtures.user_fixture() user = Bones73k.AccountsFixtures.user_fixture()
%{conn: log_in_user(conn, user), user: user} %{conn: log_in_user(conn, user), user: user}
end end
@ -60,7 +60,7 @@ defmodule RealEstateWeb.ConnCase do
It returns an updated `conn`. It returns an updated `conn`.
""" """
def log_in_user(conn, user) do def log_in_user(conn, user) do
token = RealEstate.Accounts.generate_user_session_token(user) token = Bones73k.Accounts.generate_user_session_token(user)
conn conn
|> Phoenix.ConnTest.init_test_session(%{}) |> Phoenix.ConnTest.init_test_session(%{})

View file

@ -1,4 +1,4 @@
defmodule RealEstate.DataCase do defmodule Bones73k.DataCase do
@moduledoc """ @moduledoc """
This module defines the setup for tests requiring This module defines the setup for tests requiring
access to the application's data layer. access to the application's data layer.
@ -10,7 +10,7 @@ defmodule RealEstate.DataCase do
we enable the SQL sandbox, so changes done to the database we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously PostgreSQL, you can even run database tests asynchronously
by setting `use RealEstate.DataCase, async: true`, although by setting `use Bones73k.DataCase, async: true`, although
this option is not recommended for other databases. this option is not recommended for other databases.
""" """
@ -18,20 +18,20 @@ defmodule RealEstate.DataCase do
using do using do
quote do quote do
alias RealEstate.Repo alias Bones73k.Repo
import Ecto import Ecto
import Ecto.Changeset import Ecto.Changeset
import Ecto.Query import Ecto.Query
import RealEstate.DataCase import Bones73k.DataCase
end end
end end
setup tags do setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(RealEstate.Repo) :ok = Ecto.Adapters.SQL.Sandbox.checkout(Bones73k.Repo)
unless tags[:async] do unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(RealEstate.Repo, {:shared, self()}) Ecto.Adapters.SQL.Sandbox.mode(Bones73k.Repo, {:shared, self()})
end end
:ok :ok

View file

@ -1,7 +1,7 @@
defmodule RealEstate.AccountsFixtures do defmodule Bones73k.AccountsFixtures do
@moduledoc """ @moduledoc """
This module defines test helpers for creating This module defines test helpers for creating
entities via the `RealEstate.Accounts` context. entities via the `Bones73k.Accounts` context.
""" """
def unique_user_email, do: "user#{System.unique_integer()}@example.com" def unique_user_email, do: "user#{System.unique_integer()}@example.com"
@ -14,7 +14,7 @@ defmodule RealEstate.AccountsFixtures do
email: unique_user_email(), email: unique_user_email(),
password: valid_user_password() password: valid_user_password()
}) })
|> RealEstate.Accounts.register_user() |> Bones73k.Accounts.register_user()
user user
end end
@ -26,7 +26,7 @@ defmodule RealEstate.AccountsFixtures do
email: unique_user_email(), email: unique_user_email(),
password: valid_user_password() password: valid_user_password()
}) })
|> RealEstate.Accounts.register_admin() |> Bones73k.Accounts.register_admin()
user user
end end

View file

@ -1,2 +1,2 @@
ExUnit.start() ExUnit.start()
Ecto.Adapters.SQL.Sandbox.mode(RealEstate.Repo, :manual) Ecto.Adapters.SQL.Sandbox.mode(Bones73k.Repo, :manual)