Compare commits
41
Commits
6306fbe175
..
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b9c7cb7b84 | ||
|
|
b85e3cc96c | ||
|
|
fd5bcbfc05 | ||
|
|
5339fdb2b0 | ||
|
|
2f21ccd9de | ||
|
|
afa816d2c2 | ||
|
|
c495373a81 | ||
|
|
ce011e7d87 | ||
|
|
5ca34c2b6f | ||
|
|
bbf526d6a8 | ||
|
|
c72c09b1b2 | ||
|
|
90c3b06cfc | ||
|
|
d331da9e17 | ||
|
|
aa0c43aeb1 | ||
|
|
075ae78df2 | ||
|
|
1a4a7f0d0c | ||
|
|
f90c8621b9 | ||
|
|
2456c6d14b | ||
|
|
eccaca068d | ||
|
|
0c2f304b2f | ||
|
|
a86e5c9409 | ||
|
|
fe0d748a53 | ||
|
|
bb6d7e1e2d | ||
|
|
684adddc55 | ||
|
|
82e86de969 | ||
|
|
f49092a08a | ||
|
|
fc6ecbe9c8 | ||
|
|
120cb288d2 | ||
|
|
c67fbf6733 | ||
|
|
8577c9dddb | ||
|
|
f2ff002b98 | ||
|
|
90007d40e7 | ||
|
|
2284a437fa | ||
|
|
117ccf5e16 | ||
|
|
23e738ddc9 | ||
|
|
fe8fe1b9f7 | ||
|
|
b3aff0d742 | ||
|
|
6430858f92 | ||
|
|
29474f49c1 | ||
|
|
51e559478a | ||
|
|
a2842cdb2c |
@@ -3,6 +3,11 @@
|
||||
@import "tailwindcss/components";
|
||||
@import "tailwindcss/utilities";
|
||||
|
||||
/* mapbox */
|
||||
.mapboxgl-control-container{
|
||||
display:none;
|
||||
}
|
||||
|
||||
/* Override some defaults I don't like */
|
||||
.input{
|
||||
border-radius: inherit !important;
|
||||
|
||||
+104
-4
@@ -21,15 +21,21 @@
|
||||
// Include phoenix_html to handle method=PUT/DELETE in forms and buttons.
|
||||
import "phoenix_html"
|
||||
// Establish Phoenix Socket and LiveView configuration.
|
||||
import {Socket} from "phoenix"
|
||||
import {LiveSocket} from "phoenix_live_view"
|
||||
import { Socket } from "phoenix"
|
||||
import { LiveSocket } from "phoenix_live_view"
|
||||
import topbar from "../vendor/topbar"
|
||||
import mapboxgl from "../vendor/mapbox-gl"
|
||||
|
||||
let Hooks = {};
|
||||
|
||||
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
|
||||
let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}})
|
||||
let liveSocket = new LiveSocket("/live", Socket, {
|
||||
hooks: Hooks,
|
||||
params: { _csrf_token: csrfToken }
|
||||
})
|
||||
|
||||
// Show progress bar on live navigation and form submits
|
||||
topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"})
|
||||
topbar.config({ barColors: { 0: "#29d" }, shadowColor: "rgba(0, 0, 0, .3)" })
|
||||
window.addEventListener("phx:page-loading-start", info => topbar.show())
|
||||
window.addEventListener("phx:page-loading-stop", info => topbar.hide())
|
||||
|
||||
@@ -42,3 +48,97 @@ liveSocket.connect()
|
||||
// >> liveSocket.disableLatencySim()
|
||||
window.liveSocket = liveSocket
|
||||
|
||||
window.hideElement = function (id) {
|
||||
var el = document.getElementById(id);
|
||||
el.hidden = true;
|
||||
}
|
||||
|
||||
window.selectMapResult = function (latlon, display) {
|
||||
var name_el = document.querySelector("[autocomplete=name]");
|
||||
var latlon_el = document.querySelector("[autocomplete=latlon]");
|
||||
|
||||
name_el.value = display;
|
||||
latlon_el.value = latlon;
|
||||
|
||||
window.liveSocket.hooks.showMapbox.initMap();
|
||||
};
|
||||
|
||||
window.selectRelation = function (id, name) {
|
||||
var e = new Event('selectRelation');
|
||||
e.data = {
|
||||
id: id,
|
||||
name: name
|
||||
}
|
||||
window.dispatchEvent(e);
|
||||
}
|
||||
|
||||
window.deleteRelation = function (id) {
|
||||
var e = new Event('deleteRelation');
|
||||
e.data = {
|
||||
id: id
|
||||
}
|
||||
|
||||
window.dispatchEvent(e);
|
||||
}
|
||||
|
||||
window.relationType = function (rel_id, type) {
|
||||
var e = new Event('relationType');
|
||||
e.data = {
|
||||
rel_id: rel_id,
|
||||
type: type
|
||||
}
|
||||
window.dispatchEvent(e);
|
||||
}
|
||||
|
||||
|
||||
Hooks.NewRelation = {
|
||||
mounted() {
|
||||
var list_el = document.querySelector("div#relationships");
|
||||
window.addEventListener("selectRelation", e => {
|
||||
this.pushEvent("phx:select_relation", e.data, function (reply) {
|
||||
console.log(reply);
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Hooks.RelationshipCard = {
|
||||
mounted() {
|
||||
console.log("Mounted card for relationship " + this.el.getAttribute("relationship-id"));
|
||||
|
||||
window.addEventListener("deleteRelation", e => {
|
||||
this.pushEvent("phx:delete_relation", e.data, function (reply) {
|
||||
console.log(reply);
|
||||
})
|
||||
})
|
||||
|
||||
window.addEventListener("relationType", e => {
|
||||
this.pushEvent("phx:relation_type", e.data, function (reply) {
|
||||
document.querySelector("#type-selector-" + e.data.rel_id).hidden = true;
|
||||
})
|
||||
})
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Hooks.showMapbox = {
|
||||
initMap() {
|
||||
mapboxgl.accessToken = 'pk.eyJ1IjoicnlhbnBhbmR5YSIsImEiOiJja3psM2tlcDA1MXl1Mm9uZmo5bGxpNzdxIn0.TwBKpTTypcD5fWFc8XRyHg';
|
||||
|
||||
const latlon = JSON.parse(document.querySelector("[autocomplete=latlon]").value).reverse();
|
||||
|
||||
const map = new mapboxgl.Map({
|
||||
container: 'map',
|
||||
style: 'mapbox://styles/mapbox/outdoors-v11',
|
||||
center: latlon,
|
||||
zoom: 8
|
||||
});
|
||||
},
|
||||
|
||||
mounted() {
|
||||
if (this.el.getAttribute("latlon") != "null") {
|
||||
this.initMap();
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+2005
File diff suppressed because it is too large
Load Diff
@@ -7,8 +7,8 @@
|
||||
"acorn": "^7.4.1",
|
||||
"acorn-node": "^1.8.2",
|
||||
"acorn-walk": "^7.2.0",
|
||||
"arg": "^5.0.2",
|
||||
"anymatch": "^3.1.2",
|
||||
"arg": "^5.0.2",
|
||||
"autoprefixer": "^10.4.12",
|
||||
"binary-extensions": "^2.2.0",
|
||||
"braces": "^3.0.2",
|
||||
@@ -44,6 +44,7 @@
|
||||
"is-glob": "^4.0.3",
|
||||
"is-number": "^7.0.0",
|
||||
"lilconfig": "^2.0.6",
|
||||
"mapbox-gl": "^2.10.0",
|
||||
"merge2": "^1.4.1",
|
||||
"micromatch": "^4.0.5",
|
||||
"minimist": "^1.2.7",
|
||||
@@ -63,10 +64,10 @@
|
||||
"postcss-nested": "^6.0.0",
|
||||
"postcss-selector-parser": "^6.0.10",
|
||||
"postcss-value-parser": "^4.2.0",
|
||||
"queue-microtask": "^1.2.3",
|
||||
"quick-lru": "^5.1.1",
|
||||
"read-cache": "^1.0.0",
|
||||
"readdirp": "^3.6.0",
|
||||
"queue-microtask": "^1.2.3",
|
||||
"resolve": "^1.22.1",
|
||||
"reusify": "^1.0.4",
|
||||
"run-parallel": "^1.2.0",
|
||||
@@ -80,7 +81,6 @@
|
||||
"xtend": "^4.0.2",
|
||||
"yaml": "^1.10.2"
|
||||
},
|
||||
"devDependencies": {},
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
|
||||
Vendored
+1
File diff suppressed because one or more lines are too long
Vendored
+44
File diff suppressed because one or more lines are too long
@@ -24,10 +24,12 @@ config :friends, FriendsWeb.Endpoint,
|
||||
#
|
||||
# For production it's recommended to configure a different adapter
|
||||
# at the `config/runtime.exs`.
|
||||
config :friends, Friends.Mailer, adapter: Swoosh.Adapters.Local
|
||||
config :friends, Friends.Mailer,
|
||||
adapter: Swoosh.Adapters.Postmark,
|
||||
api_key: "9f88862b-b2b3-46bf-9d50-31ebc2f7820c"
|
||||
|
||||
# Swoosh API client is needed for adapters other than SMTP.
|
||||
config :swoosh, :api_client, false
|
||||
# config :swoosh, :api_client, false
|
||||
|
||||
# Configure esbuild (the version is required)
|
||||
config :esbuild,
|
||||
|
||||
@@ -4,9 +4,11 @@ import Config
|
||||
config :friends, Friends.Repo,
|
||||
username: "postgres",
|
||||
password: "pleasework",
|
||||
hostname: "10.0.0.22",
|
||||
# hostname: "10.0.0.22",
|
||||
hostname: "localhost",
|
||||
database: "friends_crm",
|
||||
port: "2345",
|
||||
#port: "2345",
|
||||
port: "5432",
|
||||
stacktrace: true,
|
||||
show_sensitive_data_on_connection_error: true,
|
||||
pool_size: 10
|
||||
|
||||
@@ -1,15 +1,21 @@
|
||||
import Config
|
||||
|
||||
# Only in tests, remove the complexity from the password hashing algorithm
|
||||
config :bcrypt_elixir, :log_rounds, 1
|
||||
|
||||
# Configure your database
|
||||
#
|
||||
# The MIX_TEST_PARTITION environment variable can be used
|
||||
# to provide built-in test partitioning in CI environment.
|
||||
# Run `mix help test` for more information.
|
||||
|
||||
config :friends, Friends.Repo,
|
||||
username: "postgres",
|
||||
password: "postgres",
|
||||
hostname: "localhost",
|
||||
database: "friends_test#{System.get_env("MIX_TEST_PARTITION")}",
|
||||
password: "pleasework",
|
||||
#hostname: "10.0.0.22",
|
||||
#port: "2345",
|
||||
hostname: "localhost", port: "5432",
|
||||
database: "friends_test",
|
||||
pool: Ecto.Adapters.SQL.Sandbox,
|
||||
pool_size: 10
|
||||
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
defmodule Friends.Accounts do
|
||||
@moduledoc """
|
||||
The Accounts context.
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
alias Friends.Repo
|
||||
|
||||
alias Friends.Accounts.{User, UserToken, UserNotifier}
|
||||
|
||||
## Database getters
|
||||
|
||||
@doc """
|
||||
Gets a user by email.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> get_user_by_email("foo@example.com")
|
||||
%User{}
|
||||
|
||||
iex> get_user_by_email("unknown@example.com")
|
||||
nil
|
||||
|
||||
"""
|
||||
def get_user_by_email(email) when is_binary(email) do
|
||||
Repo.get_by(User, email: email)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets a user by email and password.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> get_user_by_email_and_password("foo@example.com", "correct_password")
|
||||
%User{}
|
||||
|
||||
iex> get_user_by_email_and_password("foo@example.com", "invalid_password")
|
||||
nil
|
||||
|
||||
"""
|
||||
def get_user_by_email_and_password(email, password)
|
||||
when is_binary(email) and is_binary(password) do
|
||||
user = Repo.get_by(User, email: email)
|
||||
if User.valid_password?(user, password), do: user
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets a single user.
|
||||
|
||||
Raises `Ecto.NoResultsError` if the User does not exist.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> get_user!(123)
|
||||
%User{}
|
||||
|
||||
iex> get_user!(456)
|
||||
** (Ecto.NoResultsError)
|
||||
|
||||
"""
|
||||
def get_user!(id), do: Repo.get!(User, id)
|
||||
|
||||
## User registration
|
||||
|
||||
@doc """
|
||||
Registers a user.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> register_user(%{field: value})
|
||||
{:ok, %User{}}
|
||||
|
||||
iex> register_user(%{field: bad_value})
|
||||
{:error, %Ecto.Changeset{}}
|
||||
|
||||
"""
|
||||
def register_user(attrs) do
|
||||
%User{}
|
||||
|> Repo.preload(:profile)
|
||||
|> User.registration_changeset(attrs)
|
||||
|> Repo.insert()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets or links a user profile if it exists.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> assign_profile(%User{email: some_friend@exists.com})
|
||||
{:ok, friend}
|
||||
|
||||
iex> assign_profile(%User{email: another_friend@exists.com})
|
||||
|
||||
|
||||
iex> assign_profile
|
||||
"""
|
||||
def assign_profile(%User{} = user) do
|
||||
case user.email |> Friends.Friend.get_by_email do
|
||||
nil ->
|
||||
nil
|
||||
friend ->
|
||||
new_friend = friend
|
||||
|> Friends.Friend.changeset(%{
|
||||
user_id: user.id})
|
||||
|> Friends.Repo.update!()
|
||||
|> Friends.Friend.load_user
|
||||
|
||||
%{
|
||||
friend: new_friend,
|
||||
user: new_friend.user |> Friends.Accounts.User.load_profile
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@doc """
|
||||
Returns an `%Ecto.Changeset{}` for tracking user changes.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> change_user_registration(user)
|
||||
%Ecto.Changeset{data: %User{}}
|
||||
|
||||
"""
|
||||
def change_user_registration(%User{} = user, attrs \\ %{}) do
|
||||
User.registration_changeset(user, attrs, hash_password: false)
|
||||
end
|
||||
|
||||
## Settings
|
||||
|
||||
@doc """
|
||||
Returns an `%Ecto.Changeset{}` for changing the user email.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> change_user_email(user)
|
||||
%Ecto.Changeset{data: %User{}}
|
||||
|
||||
"""
|
||||
def change_user_email(user, attrs \\ %{}) do
|
||||
User.email_changeset(user, attrs)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Emulates that the email will change without actually changing
|
||||
it in the database.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> apply_user_email(user, "valid password", %{email: ...})
|
||||
{:ok, %User{}}
|
||||
|
||||
iex> apply_user_email(user, "invalid password", %{email: ...})
|
||||
{:error, %Ecto.Changeset{}}
|
||||
|
||||
"""
|
||||
def apply_user_email(user, password, attrs) do
|
||||
user
|
||||
|> User.email_changeset(attrs)
|
||||
|> User.validate_current_password(password)
|
||||
|> Ecto.Changeset.apply_action(:update)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates the user email using the given token.
|
||||
|
||||
If the token matches, the user email is updated and the token is deleted.
|
||||
The confirmed_at date is also updated to the current time.
|
||||
"""
|
||||
def update_user_email(user, token) do
|
||||
context = "change:#{user.email}"
|
||||
|
||||
with {:ok, query} <- UserToken.verify_change_email_token_query(token, context),
|
||||
%UserToken{sent_to: email} <- Repo.one(query),
|
||||
{:ok, _} <- Repo.transaction(user_email_multi(user, email, context)) do
|
||||
:ok
|
||||
else
|
||||
_ -> :error
|
||||
end
|
||||
end
|
||||
|
||||
defp user_email_multi(user, email, context) do
|
||||
changeset =
|
||||
user
|
||||
|> User.email_changeset(%{email: email})
|
||||
|> User.confirm_changeset()
|
||||
|
||||
Ecto.Multi.new()
|
||||
|> Ecto.Multi.update(:user, changeset)
|
||||
|> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, [context]))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Delivers the update email instructions to the given user.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> deliver_update_email_instructions(user, current_email, &Routes.user_update_email_url(conn, :edit, &1))
|
||||
{:ok, %{to: ..., body: ...}}
|
||||
|
||||
"""
|
||||
def deliver_update_email_instructions(%User{} = user, current_email, update_email_url_fun)
|
||||
when is_function(update_email_url_fun, 1) do
|
||||
{encoded_token, user_token} = UserToken.build_email_token(user, "change:#{current_email}")
|
||||
|
||||
Repo.insert!(user_token)
|
||||
UserNotifier.deliver_update_email_instructions(user, update_email_url_fun.(encoded_token))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns an `%Ecto.Changeset{}` for changing the user password.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> change_user_password(user)
|
||||
%Ecto.Changeset{data: %User{}}
|
||||
|
||||
"""
|
||||
def change_user_password(user, attrs \\ %{}) do
|
||||
User.password_changeset(user, attrs, hash_password: false)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates the user password.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> update_user_password(user, "valid password", %{password: ...})
|
||||
{:ok, %User{}}
|
||||
|
||||
iex> update_user_password(user, "invalid password", %{password: ...})
|
||||
{:error, %Ecto.Changeset{}}
|
||||
|
||||
"""
|
||||
def update_user_password(user, password, attrs) do
|
||||
changeset =
|
||||
user
|
||||
|> User.password_changeset(attrs)
|
||||
|> User.validate_current_password(password)
|
||||
|
||||
Ecto.Multi.new()
|
||||
|> Ecto.Multi.update(:user, changeset)
|
||||
|> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, :all))
|
||||
|> Repo.transaction()
|
||||
|> case do
|
||||
{:ok, %{user: user}} -> {:ok, user}
|
||||
{:error, :user, changeset, _} -> {:error, changeset}
|
||||
end
|
||||
end
|
||||
|
||||
## Session
|
||||
|
||||
@doc """
|
||||
Generates a session token.
|
||||
"""
|
||||
def generate_user_session_token(user) do
|
||||
{token, user_token} = UserToken.build_session_token(user)
|
||||
Repo.insert!(user_token)
|
||||
token
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets the user with the given signed token.
|
||||
"""
|
||||
def get_user_by_session_token(token) do
|
||||
{:ok, query} = UserToken.verify_session_token_query(token)
|
||||
Repo.one(query)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deletes the signed token with the given context.
|
||||
"""
|
||||
def delete_session_token(token) do
|
||||
Repo.delete_all(UserToken.token_and_context_query(token, "session"))
|
||||
:ok
|
||||
end
|
||||
|
||||
## Confirmation
|
||||
|
||||
@doc """
|
||||
Delivers the confirmation email instructions to the given user.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> deliver_user_confirmation_instructions(user, &Routes.user_confirmation_url(conn, :edit, &1))
|
||||
{:ok, %{to: ..., body: ...}}
|
||||
|
||||
iex> deliver_user_confirmation_instructions(confirmed_user, &Routes.user_confirmation_url(conn, :edit, &1))
|
||||
{:error, :already_confirmed}
|
||||
|
||||
"""
|
||||
def deliver_user_confirmation_instructions(%User{} = user, confirmation_url_fun)
|
||||
when is_function(confirmation_url_fun, 1) do
|
||||
if user.confirmed_at do
|
||||
{:error, :already_confirmed}
|
||||
else
|
||||
{encoded_token, user_token} = UserToken.build_email_token(user, "confirm")
|
||||
Repo.insert!(user_token)
|
||||
UserNotifier.deliver_confirmation_instructions(user, confirmation_url_fun.(encoded_token))
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Confirms a user by the given token.
|
||||
|
||||
If the token matches, the user account is marked as confirmed
|
||||
and the token is deleted.
|
||||
"""
|
||||
def confirm_user(token) do
|
||||
with {:ok, query} <- UserToken.verify_email_token_query(token, "confirm"),
|
||||
%User{} = user <- Repo.one(query),
|
||||
{:ok, %{user: user}} <- Repo.transaction(confirm_user_multi(user)) do
|
||||
{:ok, user}
|
||||
else
|
||||
_ -> :error
|
||||
end
|
||||
end
|
||||
|
||||
defp confirm_user_multi(user) do
|
||||
Ecto.Multi.new()
|
||||
|> Ecto.Multi.update(:user, User.confirm_changeset(user))
|
||||
|> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, ["confirm"]))
|
||||
end
|
||||
|
||||
## Reset password
|
||||
|
||||
@doc """
|
||||
Delivers the reset password email to the given user.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> deliver_user_reset_password_instructions(user, &Routes.user_reset_password_url(conn, :edit, &1))
|
||||
{:ok, %{to: ..., body: ...}}
|
||||
|
||||
"""
|
||||
def deliver_user_reset_password_instructions(%User{} = user, reset_password_url_fun)
|
||||
when is_function(reset_password_url_fun, 1) do
|
||||
{encoded_token, user_token} = UserToken.build_email_token(user, "reset_password")
|
||||
Repo.insert!(user_token)
|
||||
UserNotifier.deliver_reset_password_instructions(user, reset_password_url_fun.(encoded_token))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets the user by reset password token.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> get_user_by_reset_password_token("validtoken")
|
||||
%User{}
|
||||
|
||||
iex> get_user_by_reset_password_token("invalidtoken")
|
||||
nil
|
||||
|
||||
"""
|
||||
def get_user_by_reset_password_token(token) do
|
||||
with {:ok, query} <- UserToken.verify_email_token_query(token, "reset_password"),
|
||||
%User{} = user <- Repo.one(query) do
|
||||
user
|
||||
else
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Resets the user password.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> reset_user_password(user, %{password: "new long password", password_confirmation: "new long password"})
|
||||
{:ok, %User{}}
|
||||
|
||||
iex> reset_user_password(user, %{password: "valid", password_confirmation: "not the same"})
|
||||
{:error, %Ecto.Changeset{}}
|
||||
|
||||
"""
|
||||
def reset_user_password(user, attrs) do
|
||||
Ecto.Multi.new()
|
||||
|> Ecto.Multi.update(:user, User.password_changeset(user, attrs))
|
||||
|> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, :all))
|
||||
|> Repo.transaction()
|
||||
|> case do
|
||||
{:ok, %{user: user}} -> {:ok, user}
|
||||
{:error, :user, changeset, _} -> {:error, changeset}
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,153 @@
|
||||
defmodule Friends.Accounts.User do
|
||||
use Ecto.Schema
|
||||
import Ecto.Changeset
|
||||
|
||||
@repo Friends.Repo
|
||||
|
||||
schema "users" do
|
||||
field :email, :string
|
||||
field :password, :string, virtual: true, redact: true
|
||||
field :hashed_password, :string, redact: true
|
||||
field :confirmed_at, :naive_datetime
|
||||
|
||||
timestamps()
|
||||
|
||||
has_one :profile, Friends.Friend
|
||||
end
|
||||
|
||||
def load_profile(%Friends.Accounts.User{profile: %Ecto.Association.NotLoaded{}} = model) do
|
||||
model
|
||||
|> @repo.preload(:profile)
|
||||
end
|
||||
|
||||
def load_profile(nil) do
|
||||
%{profile: nil}
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for registration.
|
||||
|
||||
It is important to validate the length of both email and password.
|
||||
Otherwise databases may truncate the email without warnings, which
|
||||
could lead to unpredictable or insecure behaviour. Long passwords may
|
||||
also be very expensive to hash for certain algorithms.
|
||||
|
||||
## Options
|
||||
|
||||
* `:hash_password` - Hashes the password so it can be stored securely
|
||||
in the database and ensures the password field is cleared to prevent
|
||||
leaks in the logs. If password hashing is not needed and clearing the
|
||||
password field is not desired (like when using this changeset for
|
||||
validations on a LiveView form), this option can be set to `false`.
|
||||
Defaults to `true`.
|
||||
"""
|
||||
def registration_changeset(user, attrs, opts \\ []) do
|
||||
user
|
||||
|> cast(attrs, [:email, :password])
|
||||
|> validate_email()
|
||||
|> validate_password(opts)
|
||||
end
|
||||
|
||||
defp validate_email(changeset) do
|
||||
changeset
|
||||
|> validate_required([:email])
|
||||
|> validate_format(:email, ~r/^[^\s]+@[^\s]+$/, message: "must have the @ sign and no spaces")
|
||||
|> validate_length(:email, max: 160)
|
||||
|> unsafe_validate_unique(:email, Friends.Repo)
|
||||
|> unique_constraint(:email)
|
||||
end
|
||||
|
||||
defp validate_password(changeset, opts) do
|
||||
changeset
|
||||
|> validate_required([:password])
|
||||
|> validate_length(:password, min: 6, max: 72)
|
||||
# |> validate_format(:password, ~r/[a-z]/, message: "at least one lower case character")
|
||||
# |> validate_format(:password, ~r/[A-Z]/, message: "at least one upper case character")
|
||||
# |> validate_format(:password, ~r/[!?@#$%^&*_0-9]/, message: "at least one digit or punctuation character")
|
||||
|> maybe_hash_password(opts)
|
||||
end
|
||||
|
||||
defp maybe_hash_password(changeset, opts) do
|
||||
hash_password? = Keyword.get(opts, :hash_password, true)
|
||||
password = get_change(changeset, :password)
|
||||
|
||||
if hash_password? && password && changeset.valid? do
|
||||
changeset
|
||||
# If using Bcrypt, then further validate it is at most 72 bytes long
|
||||
|> validate_length(:password, max: 72, count: :bytes)
|
||||
|> put_change(:hashed_password, Bcrypt.hash_pwd_salt(password))
|
||||
|> delete_change(:password)
|
||||
else
|
||||
changeset
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for changing the email.
|
||||
|
||||
It requires the email to change otherwise an error is added.
|
||||
"""
|
||||
def email_changeset(user, attrs) do
|
||||
user
|
||||
|> cast(attrs, [:email])
|
||||
|> validate_email()
|
||||
|> case do
|
||||
%{changes: %{email: _}} = changeset -> changeset
|
||||
%{} = changeset -> add_error(changeset, :email, "did not change")
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for changing the password.
|
||||
|
||||
## Options
|
||||
|
||||
* `:hash_password` - Hashes the password so it can be stored securely
|
||||
in the database and ensures the password field is cleared to prevent
|
||||
leaks in the logs. If password hashing is not needed and clearing the
|
||||
password field is not desired (like when using this changeset for
|
||||
validations on a LiveView form), this option can be set to `false`.
|
||||
Defaults to `true`.
|
||||
"""
|
||||
def password_changeset(user, attrs, opts \\ []) do
|
||||
user
|
||||
|> cast(attrs, [:password])
|
||||
|> validate_confirmation(:password, message: "does not match password")
|
||||
|> validate_password(opts)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Confirms the account by setting `confirmed_at`.
|
||||
"""
|
||||
def confirm_changeset(user) do
|
||||
now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)
|
||||
change(user, confirmed_at: now)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Verifies the password.
|
||||
|
||||
If there is no user or the user doesn't have a password, we call
|
||||
`Bcrypt.no_user_verify/0` to avoid timing attacks.
|
||||
"""
|
||||
def valid_password?(%Friends.Accounts.User{hashed_password: hashed_password}, password)
|
||||
when is_binary(hashed_password) and byte_size(password) > 0 do
|
||||
Bcrypt.verify_pass(password, hashed_password)
|
||||
end
|
||||
|
||||
def valid_password?(_, _) do
|
||||
Bcrypt.no_user_verify()
|
||||
false
|
||||
end
|
||||
|
||||
@doc """
|
||||
Validates the current password otherwise adds an error to the changeset.
|
||||
"""
|
||||
def validate_current_password(changeset, password) do
|
||||
if valid_password?(changeset.data, password) do
|
||||
changeset
|
||||
else
|
||||
add_error(changeset, :current_password, "is not valid")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,79 @@
|
||||
defmodule Friends.Accounts.UserNotifier do
|
||||
import Swoosh.Email
|
||||
|
||||
alias Friends.Mailer
|
||||
|
||||
# Delivers the email using the application mailer.
|
||||
defp deliver(recipient, subject, body) do
|
||||
email =
|
||||
new()
|
||||
|> to(recipient)
|
||||
|> from({"Friends App", "ryan@pandu.ski"})
|
||||
|> subject(subject)
|
||||
|> text_body(body)
|
||||
|
||||
with {:ok, _metadata} <- Mailer.deliver(email) do
|
||||
{:ok, email}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deliver instructions to confirm account.
|
||||
"""
|
||||
def deliver_confirmation_instructions(user, url) do
|
||||
deliver(user.email, "Confirmation instructions", """
|
||||
|
||||
==============================
|
||||
|
||||
Hi #{user.email},
|
||||
|
||||
You can confirm your account by visiting the URL below:
|
||||
|
||||
#{url}
|
||||
|
||||
If you didn't create an account with us, please ignore this.
|
||||
|
||||
==============================
|
||||
""")
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deliver instructions to reset a user password.
|
||||
"""
|
||||
def deliver_reset_password_instructions(user, url) do
|
||||
deliver(user.email, "Reset password instructions", """
|
||||
|
||||
==============================
|
||||
|
||||
Hi #{user.email},
|
||||
|
||||
You can reset your password by visiting the URL below:
|
||||
|
||||
#{url}
|
||||
|
||||
If you didn't request this change, please ignore this.
|
||||
|
||||
==============================
|
||||
""")
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deliver instructions to update a user email.
|
||||
"""
|
||||
def deliver_update_email_instructions(user, url) do
|
||||
deliver(user.email, "Update email instructions", """
|
||||
|
||||
==============================
|
||||
|
||||
Hi #{user.email},
|
||||
|
||||
You can change your email by visiting the URL below:
|
||||
|
||||
#{url}
|
||||
|
||||
If you didn't request this change, please ignore this.
|
||||
|
||||
==============================
|
||||
""")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,179 @@
|
||||
defmodule Friends.Accounts.UserToken do
|
||||
use Ecto.Schema
|
||||
import Ecto.Query
|
||||
alias Friends.Accounts.UserToken
|
||||
|
||||
@hash_algorithm :sha256
|
||||
@rand_size 32
|
||||
|
||||
# It is very important to keep the reset password token expiry short,
|
||||
# since someone with access to the email may take over the account.
|
||||
@reset_password_validity_in_days 1
|
||||
@confirm_validity_in_days 7
|
||||
@change_email_validity_in_days 7
|
||||
@session_validity_in_days 60
|
||||
|
||||
schema "users_tokens" do
|
||||
field :token, :binary
|
||||
field :context, :string
|
||||
field :sent_to, :string
|
||||
belongs_to :user, Friends.Accounts.User
|
||||
|
||||
timestamps(updated_at: false)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Generates a token that will be stored in a signed place,
|
||||
such as session or cookie. As they are signed, those
|
||||
tokens do not need to be hashed.
|
||||
|
||||
The reason why we store session tokens in the database, even
|
||||
though Phoenix already provides a session cookie, is because
|
||||
Phoenix' default session cookies are not persisted, they are
|
||||
simply signed and potentially encrypted. This means they are
|
||||
valid indefinitely, unless you change the signing/encryption
|
||||
salt.
|
||||
|
||||
Therefore, storing them allows individual user
|
||||
sessions to be expired. The token system can also be extended
|
||||
to store additional data, such as the device used for logging in.
|
||||
You could then use this information to display all valid sessions
|
||||
and devices in the UI and allow users to explicitly expire any
|
||||
session they deem invalid.
|
||||
"""
|
||||
def build_session_token(user) do
|
||||
token = :crypto.strong_rand_bytes(@rand_size)
|
||||
{token, %UserToken{token: token, context: "session", user_id: user.id}}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks if the token is valid and returns its underlying lookup query.
|
||||
|
||||
The query returns the user found by the token, if any.
|
||||
|
||||
The token is valid if it matches the value in the database and it has
|
||||
not expired (after @session_validity_in_days).
|
||||
"""
|
||||
def verify_session_token_query(token) do
|
||||
query =
|
||||
from token in token_and_context_query(token, "session"),
|
||||
join: user in assoc(token, :user),
|
||||
where: token.inserted_at > ago(@session_validity_in_days, "day"),
|
||||
select: user
|
||||
|
||||
{:ok, query}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Builds a token and its hash to be delivered to the user's email.
|
||||
|
||||
The non-hashed token is sent to the user email while the
|
||||
hashed part is stored in the database. The original token cannot be reconstructed,
|
||||
which means anyone with read-only access to the database cannot directly use
|
||||
the token in the application to gain access. Furthermore, if the user changes
|
||||
their email in the system, the tokens sent to the previous email are no longer
|
||||
valid.
|
||||
|
||||
Users can easily adapt the existing code to provide other types of delivery methods,
|
||||
for example, by phone numbers.
|
||||
"""
|
||||
def build_email_token(user, context) do
|
||||
build_hashed_token(user, context, user.email)
|
||||
end
|
||||
|
||||
defp build_hashed_token(user, context, sent_to) do
|
||||
token = :crypto.strong_rand_bytes(@rand_size)
|
||||
hashed_token = :crypto.hash(@hash_algorithm, token)
|
||||
|
||||
{Base.url_encode64(token, padding: false),
|
||||
%UserToken{
|
||||
token: hashed_token,
|
||||
context: context,
|
||||
sent_to: sent_to,
|
||||
user_id: user.id
|
||||
}}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks if the token is valid and returns its underlying lookup query.
|
||||
|
||||
The query returns the user found by the token, if any.
|
||||
|
||||
The given token is valid if it matches its hashed counterpart in the
|
||||
database and the user email has not changed. This function also checks
|
||||
if the token is being used within a certain period, depending on the
|
||||
context. The default contexts supported by this function are either
|
||||
"confirm", for account confirmation emails, and "reset_password",
|
||||
for resetting the password. For verifying requests to change the email,
|
||||
see `verify_change_email_token_query/2`.
|
||||
"""
|
||||
def verify_email_token_query(token, context) do
|
||||
case Base.url_decode64(token, padding: false) do
|
||||
{:ok, decoded_token} ->
|
||||
hashed_token = :crypto.hash(@hash_algorithm, decoded_token)
|
||||
days = days_for_context(context)
|
||||
|
||||
query =
|
||||
from token in token_and_context_query(hashed_token, context),
|
||||
join: user in assoc(token, :user),
|
||||
where: token.inserted_at > ago(^days, "day") and token.sent_to == user.email,
|
||||
select: user
|
||||
|
||||
{:ok, query}
|
||||
|
||||
:error ->
|
||||
:error
|
||||
end
|
||||
end
|
||||
|
||||
defp days_for_context("confirm"), do: @confirm_validity_in_days
|
||||
defp days_for_context("reset_password"), do: @reset_password_validity_in_days
|
||||
|
||||
@doc """
|
||||
Checks if the token is valid and returns its underlying lookup query.
|
||||
|
||||
The query returns the user found by the token, if any.
|
||||
|
||||
This is used to validate requests to change the user
|
||||
email. It is different from `verify_email_token_query/2` precisely because
|
||||
`verify_email_token_query/2` validates the email has not changed, which is
|
||||
the starting point by this function.
|
||||
|
||||
The given token is valid if it matches its hashed counterpart in the
|
||||
database and if it has not expired (after @change_email_validity_in_days).
|
||||
The context must always start with "change:".
|
||||
"""
|
||||
def verify_change_email_token_query(token, "change:" <> _ = context) do
|
||||
case Base.url_decode64(token, padding: false) do
|
||||
{:ok, decoded_token} ->
|
||||
hashed_token = :crypto.hash(@hash_algorithm, decoded_token)
|
||||
|
||||
query =
|
||||
from token in token_and_context_query(hashed_token, context),
|
||||
where: token.inserted_at > ago(@change_email_validity_in_days, "day")
|
||||
|
||||
{:ok, query}
|
||||
|
||||
:error ->
|
||||
:error
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the token struct for the given token value and context.
|
||||
"""
|
||||
def token_and_context_query(token, context) do
|
||||
from UserToken, where: [token: ^token, context: ^context]
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets all tokens for the given user for the given contexts.
|
||||
"""
|
||||
def user_and_contexts_query(user, :all) do
|
||||
from t in UserToken, where: t.user_id == ^user.id
|
||||
end
|
||||
|
||||
def user_and_contexts_query(user, [_ | _] = contexts) do
|
||||
from t in UserToken, where: t.user_id == ^user.id and t.context in ^contexts
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,180 @@
|
||||
defmodule Friends.Event do
|
||||
use Ecto.Schema
|
||||
import Ecto.Query
|
||||
alias Friends.{Relationship, Event}
|
||||
alias Places.Place
|
||||
|
||||
@repo Friends.Repo
|
||||
|
||||
schema "events" do
|
||||
field(:date, :date)
|
||||
field(:name, :string)
|
||||
field(:story, :string)
|
||||
field(:defining, :boolean)
|
||||
field(:solo, :boolean)
|
||||
|
||||
belongs_to(:place, Place)
|
||||
belongs_to(:relationship, Relationship)
|
||||
end
|
||||
|
||||
def changeset(event, params \\ %{}) do
|
||||
event
|
||||
|> Ecto.Changeset.cast(params, [
|
||||
:name,
|
||||
:date,
|
||||
:story,
|
||||
:defining,
|
||||
:solo,
|
||||
:place_id,
|
||||
:relationship_id
|
||||
])
|
||||
|> Ecto.Changeset.validate_required([:name, :date, :solo, :relationship_id],
|
||||
message: "This field is required."
|
||||
)
|
||||
|> validate_date_in_past()
|
||||
|> validate_unique_event()
|
||||
end
|
||||
|
||||
defp validate_unique_event(changeset) do
|
||||
changeset
|
||||
end
|
||||
|
||||
defp validate_date_in_past(%{changes: %{date: date}} = changeset) do
|
||||
today = DateTime.utc_now() |> DateTime.to_date()
|
||||
|
||||
case date |> Date.diff(today) do
|
||||
age when age < 0 ->
|
||||
changeset |> Ecto.Changeset.add_error(:born, "Please enter a date in the past.")
|
||||
|
||||
_ ->
|
||||
changeset
|
||||
end
|
||||
end
|
||||
|
||||
defp validate_date_in_past(changeset), do: changeset
|
||||
|
||||
def new(params \\ %{}) do
|
||||
%Event{id: nil}
|
||||
|> struct(params)
|
||||
end
|
||||
|
||||
def get_by_id(id) do
|
||||
@repo.one(
|
||||
from(e in Event,
|
||||
where: e.id == ^id,
|
||||
preload: [:relationship, :place]
|
||||
)
|
||||
)
|
||||
end
|
||||
|
||||
def get(%{relationship_id: rel, date: date, name: name}) do
|
||||
@repo.one(
|
||||
from(e in Event,
|
||||
where: e.relationship_id == ^rel and e.date == ^date and e.name == ^name,
|
||||
preload: [:relationship, :place]
|
||||
)
|
||||
)
|
||||
end
|
||||
|
||||
def get_or_create(params) do
|
||||
case get(params) do
|
||||
nil -> create(params) |> commit()
|
||||
event -> event
|
||||
end
|
||||
end
|
||||
|
||||
def create(params \\ %{id: nil}) do
|
||||
Event.new(params)
|
||||
|> Event.changeset()
|
||||
|> Map.put(:action, :insert)
|
||||
end
|
||||
|
||||
def update(params) do
|
||||
Event.get_by_id(params.id |> String.to_integer())
|
||||
|> Event.changeset(params)
|
||||
|> Map.put(:action, :update)
|
||||
end
|
||||
|
||||
def commit(changeset) do
|
||||
changeset
|
||||
|> @repo.commit!
|
||||
|> load_preloads
|
||||
end
|
||||
|
||||
def load_preloads(
|
||||
%Event{
|
||||
place: %Ecto.Association.NotLoaded{},
|
||||
relationship: %Ecto.Association.NotLoaded{}
|
||||
} = model
|
||||
) do
|
||||
model
|
||||
|> @repo.preload([:place, :relationship])
|
||||
end
|
||||
|
||||
def load_preloads(event), do: event
|
||||
|
||||
def create_or_update(params) do
|
||||
case params.id do
|
||||
"new" ->
|
||||
params
|
||||
|> create()
|
||||
|> commit()
|
||||
|
||||
_number ->
|
||||
params
|
||||
|> update()
|
||||
|> commit()
|
||||
end
|
||||
end
|
||||
|
||||
def meet(friend1, friend2, opts \\ nil) do
|
||||
relationship = Relationship.get_or_new(friend1, friend2)
|
||||
|
||||
opts =
|
||||
opts ++
|
||||
[
|
||||
if opts[:place] do
|
||||
{
|
||||
:place_id,
|
||||
Places.Place.get_or_new(opts[:place]).id
|
||||
}
|
||||
end
|
||||
]
|
||||
|
||||
{:ok, event} =
|
||||
%Event{
|
||||
story: opts[:story],
|
||||
date: opts[:date],
|
||||
place_id: opts[:place_id],
|
||||
relationship_id: relationship.id
|
||||
}
|
||||
|> @repo.insert
|
||||
|
||||
event
|
||||
end
|
||||
|
||||
def person(event) do
|
||||
Friends.Friend.get_by_id(event.relationship.friend_id)
|
||||
end
|
||||
|
||||
def people(event) do
|
||||
if event.solo, do: event.person, else: event.relationship |> Relationship.members()
|
||||
end
|
||||
|
||||
def age(event) do
|
||||
years =
|
||||
Date.diff(Date.utc_today(), event.date)
|
||||
|> div(365)
|
||||
|
||||
if years == 0 do
|
||||
months = Date.diff(Date.utc_today(), event.date) |> rem(365) |> div(12)
|
||||
{months, :month}
|
||||
else
|
||||
{years, :year}
|
||||
end
|
||||
end
|
||||
|
||||
def print_age(age) do
|
||||
Friends.Helpers.pluralize(age |> elem(0), age |> elem(1))
|
||||
end
|
||||
end
|
||||
+206
-37
@@ -1,7 +1,7 @@
|
||||
defmodule Friends.Friend do
|
||||
use Ecto.Schema
|
||||
|
||||
alias Friends.{Relationship, Friend}
|
||||
alias Friends.{Relationship, Friend, Event}
|
||||
import Helpers
|
||||
import Ecto.Query
|
||||
|
||||
@@ -16,104 +16,273 @@ defmodule Friends.Friend do
|
||||
field(:slug, :string)
|
||||
field(:memories, {:array, :string})
|
||||
|
||||
# has_many(:photos, Media.Photo)
|
||||
belongs_to :user, Friends.Accounts.User, foreign_key: :user_id
|
||||
belongs_to :address, Friends.Places.Place, foreign_key: :address_id
|
||||
|
||||
many_to_many(
|
||||
:relationships,
|
||||
Friends.Friend,
|
||||
join_through: Relationship,
|
||||
join_keys: [friend_id: :id, relation_id: :id]
|
||||
join_keys: [friend_id: :id, relation_id: :id],
|
||||
on_delete: :delete_all
|
||||
)
|
||||
|
||||
many_to_many(
|
||||
:reverse_relationships,
|
||||
Friends.Friend,
|
||||
join_through: Relationship,
|
||||
join_keys: [relation_id: :id, friend_id: :id]
|
||||
join_keys: [relation_id: :id, friend_id: :id],
|
||||
on_delete: :delete_all
|
||||
)
|
||||
end
|
||||
|
||||
def changeset(friend, params \\ %{}) do
|
||||
friend
|
||||
|> Ecto.Changeset.cast(params, [:name, :born, :nickname, :email, :phone, :slug])
|
||||
|> Ecto.Changeset.validate_required([:name, :email, :phone, :born])
|
||||
|> Ecto.Changeset.validate_format(:name, ~r/\w+\ \w+/)
|
||||
|> Ecto.Changeset.validate_format(:email, Regex.compile!("^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$"))
|
||||
|> Ecto.Changeset.validate_format(:phone, Regex.compile!("^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$"))
|
||||
|> Ecto.Changeset.cast(params, [
|
||||
:name,
|
||||
:born,
|
||||
:nickname,
|
||||
:email,
|
||||
:phone,
|
||||
:slug,
|
||||
:user_id,
|
||||
:address_id
|
||||
])
|
||||
|> Ecto.Changeset.validate_required([:name],
|
||||
message: "This field is required."
|
||||
)
|
||||
# |> Ecto.Changeset.validate_format(:name, ~r/\w+\ \w+/, message: "Please enter your full name.")
|
||||
|> Ecto.Changeset.validate_format(
|
||||
:email,
|
||||
Regex.compile!("^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$"),
|
||||
message: "Invalid email format."
|
||||
)
|
||||
|> Ecto.Changeset.validate_format(
|
||||
:phone,
|
||||
Regex.compile!("^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$"),
|
||||
message: "Invalid phone format."
|
||||
)
|
||||
|> validate_birthdate()
|
||||
|> Ecto.Changeset.unique_constraint(:name)
|
||||
|> Ecto.Changeset.unique_constraint(:email)
|
||||
end
|
||||
|
||||
defp validate_birthdate(%{changes: %{born: born}} = changeset) do
|
||||
today = DateTime.utc_now() |> DateTime.to_date()
|
||||
|
||||
case born |> Date.diff(today) |> div(-365) do
|
||||
age when age < 0 ->
|
||||
changeset |> Ecto.Changeset.add_error(:born, "Please enter a date in the past.")
|
||||
|
||||
age when age > 90 ->
|
||||
changeset |> Ecto.Changeset.add_error(:born, "Are you sure you're #{age} years old?")
|
||||
|
||||
_ ->
|
||||
changeset
|
||||
end
|
||||
end
|
||||
|
||||
defp validate_birthdate(changeset), do: changeset
|
||||
|
||||
def all() do
|
||||
preloads = [:relationships, :reverse_relationships]
|
||||
preloads = [:relationships, :reverse_relationships, :user, :address]
|
||||
@repo.all(from(f in Friends.Friend, preload: ^preloads))
|
||||
end
|
||||
|
||||
|
||||
def new(params \\ %{}) do
|
||||
%Friend{id: "new"}
|
||||
%Friend{id: nil}
|
||||
|> struct(params)
|
||||
end
|
||||
|
||||
def get_by_slug(slug) do
|
||||
@repo.one(
|
||||
from(f in Friend,
|
||||
where: f.slug == ^slug,
|
||||
preload: [:relationships, :reverse_relationships]
|
||||
where: f.slug == ^slug
|
||||
)
|
||||
)
|
||||
|> load_preloads()
|
||||
end
|
||||
|
||||
def get_by_id(id) do
|
||||
@repo.one(
|
||||
from(f in Friend,
|
||||
where: f.id == ^id,
|
||||
preload: [:relationships, :reverse_relationships]
|
||||
preload: [:relationships, :reverse_relationships, :address]
|
||||
)
|
||||
)
|
||||
end
|
||||
|
||||
def get_by_email(email) do
|
||||
@repo.one(
|
||||
from(f in Friend,
|
||||
where: f.email == ^email
|
||||
)
|
||||
)
|
||||
|> load_preloads()
|
||||
end
|
||||
|
||||
def create(params \\ %{id: nil}) do
|
||||
Friend.new()
|
||||
|> Friend.changeset(params)
|
||||
|> Map.put(:action, :insert)
|
||||
end
|
||||
|
||||
def update(params) do
|
||||
Friend.get_by_id(params.id)
|
||||
|> Friend.changeset(params)
|
||||
|> Map.put(:action, :update)
|
||||
end
|
||||
|
||||
def commit(changeset) do
|
||||
changeset
|
||||
|> @repo.commit!
|
||||
|> load_preloads
|
||||
|> assign_user!()
|
||||
end
|
||||
|
||||
def generate_slug(%Ecto.Changeset{} = changeset) do
|
||||
slug = changeset.changes.name |> to_slug
|
||||
|
||||
changeset
|
||||
|> changeset(%{
|
||||
slug: slug
|
||||
})
|
||||
end
|
||||
|
||||
def generate_slug(%Friend{} = friend) do
|
||||
%{
|
||||
friend
|
||||
| slug: friend.name |> to_slug
|
||||
}
|
||||
end
|
||||
|
||||
def create_or_update(params) do
|
||||
case params.id do
|
||||
"new" ->
|
||||
%Friend{} |> Friend.changeset(%{params | id: nil})
|
||||
|> Map.put(:action, :insert)
|
||||
|> @repo.insert!
|
||||
nil ->
|
||||
params
|
||||
|> create()
|
||||
|> generate_slug()
|
||||
|> commit()
|
||||
|> create_birth_event()
|
||||
|
||||
_number ->
|
||||
Friend.get_by_id(params.id |> String.to_integer)
|
||||
|> Friend.changeset(params)
|
||||
|> Map.put(:action, :update)
|
||||
|> @repo.update!
|
||||
params
|
||||
|> update()
|
||||
|> commit()
|
||||
end
|
||||
end
|
||||
|
||||
def get_relationships(friend) do
|
||||
def get_relationships(friend, include_self \\ false) do
|
||||
friend
|
||||
|> relations
|
||||
|> Enum.map(&(relation(friend, &1)))
|
||||
|> relations(include_self)
|
||||
|> Enum.map(&relation(friend, &1))
|
||||
end
|
||||
|
||||
def get_events(friend) do
|
||||
friend
|
||||
|> get_relationships
|
||||
|> Enum.map(&(&1.events))
|
||||
|> List.flatten
|
||||
|> get_relationships(:all)
|
||||
|> Enum.flat_map(& &1.events)
|
||||
|> Enum.dedup()
|
||||
end
|
||||
|
||||
def age(friend) do
|
||||
# Age in years
|
||||
Date.diff(Date.utc_today,friend.born) |> div(365)
|
||||
Date.diff(Date.utc_today(), friend.born) |> div(365)
|
||||
end
|
||||
|
||||
# TODO: Refactor
|
||||
def create_birth_event(friend) do
|
||||
if is_nil @repo.all(
|
||||
from(e in Friends.Event,
|
||||
where: e.name == "born"
|
||||
)) |> List.flatten do
|
||||
def can_be_edited_by(friend, user) do
|
||||
true
|
||||
# if user |> is_nil(), do: false, else: friend.id == user.profile.id
|
||||
end
|
||||
|
||||
def assign_address(%Friend{} = friend, address) do
|
||||
friend
|
||||
|> Friends.Friend.changeset(%{
|
||||
address_id: address.id
|
||||
})
|
||||
|> Friends.Repo.update!()
|
||||
end
|
||||
|
||||
def assign_user(%Friend{} = friend) do
|
||||
case friend.email |> Friends.Accounts.get_user_by_email() do
|
||||
nil ->
|
||||
nil
|
||||
|
||||
user ->
|
||||
user |> Friends.Accounts.assign_profile()
|
||||
end
|
||||
end
|
||||
|
||||
def assign_user!(%Friend{} = friend) do
|
||||
case assign_user(friend) do
|
||||
%{friend: new_friend, user: _user} -> new_friend
|
||||
nil -> friend
|
||||
end
|
||||
end
|
||||
|
||||
def load_user(%Friends.Friend{user: %Ecto.Association.NotLoaded{}} = model) do
|
||||
model
|
||||
|> @repo.preload(:user)
|
||||
end
|
||||
|
||||
def load_user(%Friends.Friend{} = friend), do: friend
|
||||
|
||||
def load_relationships(
|
||||
%Friends.Friend{
|
||||
relationships: %Ecto.Association.NotLoaded{},
|
||||
reverse_relationships: %Ecto.Association.NotLoaded{}
|
||||
} = model
|
||||
) do
|
||||
model
|
||||
|> @repo.preload([:relationships, :reverse_relationships])
|
||||
end
|
||||
|
||||
def load_relationships(%Friends.Friend{} = friend), do: friend
|
||||
|
||||
def load_preloads(
|
||||
%Friends.Friend{
|
||||
relationships: %Ecto.Association.NotLoaded{},
|
||||
reverse_relationships: %Ecto.Association.NotLoaded{},
|
||||
user: %Ecto.Association.NotLoaded{},
|
||||
address: %Ecto.Association.NotLoaded{}
|
||||
} = model
|
||||
) do
|
||||
model
|
||||
|> @repo.preload([:user, :relationships, :reverse_relationships, :address])
|
||||
end
|
||||
|
||||
def load_preloads(friend), do: friend
|
||||
|
||||
def get_address(%Friend{} = friend) do
|
||||
if friend.address do
|
||||
{
|
||||
friend.address.latlon,
|
||||
friend.address.name
|
||||
}
|
||||
else
|
||||
"find"
|
||||
{nil, nil}
|
||||
end
|
||||
end
|
||||
|
||||
def create_birth_event(%Friend{id: id} = friend) do
|
||||
solo_relationship = Relationship.get_or_create(friend, friend)
|
||||
|
||||
Event.get_or_create(%{
|
||||
name: "Born",
|
||||
date: friend.born,
|
||||
solo: true,
|
||||
defining: true,
|
||||
relationship_id: solo_relationship.id
|
||||
})
|
||||
end
|
||||
|
||||
def create_relationship(friend1, friend2) do
|
||||
rel = Relationship.get_or_create(friend1, friend2)
|
||||
rel |> Relationship.members()
|
||||
end
|
||||
|
||||
def delete_relationship(friend1, friend2) do
|
||||
Relationship.delete(friend1, friend2)
|
||||
friend1.id |> Friend.get_by_id()
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
defmodule Friends.Friend.Search do
|
||||
alias Friends.Friend
|
||||
import Ecto.Query
|
||||
|
||||
@repo Friends.Repo
|
||||
|
||||
def autocomplete(str, friend) do
|
||||
@repo.all(
|
||||
from(
|
||||
f in Friend,
|
||||
where: ilike(f.name, ^"%#{str}%")
|
||||
)
|
||||
)
|
||||
|> remove_self(friend)
|
||||
|> remove_existing(friend)
|
||||
end
|
||||
|
||||
defp remove_self(list, friend) do
|
||||
list
|
||||
|> Enum.filter(fn result ->
|
||||
result.id != friend.id
|
||||
end)
|
||||
end
|
||||
|
||||
defp remove_existing(list, friend) do
|
||||
existing =
|
||||
friend
|
||||
|> Helpers.relations()
|
||||
|> Enum.map(& &1.id)
|
||||
|
||||
list
|
||||
|> Enum.filter(fn result ->
|
||||
result.id not in existing
|
||||
end)
|
||||
end
|
||||
|
||||
def parse_result(friend) do
|
||||
%{
|
||||
id: "friend-#{friend.id}",
|
||||
value: friend.id,
|
||||
name: friend.name
|
||||
}
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,42 @@
|
||||
defmodule Friends.Places.Place do
|
||||
use Ecto.Schema
|
||||
import Ecto.Query
|
||||
import Ecto.Changeset
|
||||
import Helpers
|
||||
|
||||
alias Friends.Places.{Place, Search}
|
||||
|
||||
@repo Friends.Repo
|
||||
|
||||
schema "places" do
|
||||
field(:name, :string)
|
||||
field(:type, :string)
|
||||
field(:latlon, {:array, :float})
|
||||
field(:zoom, :integer)
|
||||
|
||||
has_many(:events, Friends.Event)
|
||||
has_many(:friends, Friends.Friend, foreign_key: :address_id)
|
||||
end
|
||||
|
||||
def validate(place, params \\ %{}) do
|
||||
place
|
||||
|> cast(params, [:name, :type, :latlon, :zoom])
|
||||
|> unique_constraint(:name)
|
||||
|> validate_required(:name)
|
||||
end
|
||||
|
||||
def get_or_create(place) do
|
||||
case @repo.one(
|
||||
from(
|
||||
p in Friends.Places.Place,
|
||||
where: p.name == ^place.name
|
||||
)
|
||||
) do
|
||||
nil ->
|
||||
place
|
||||
|> Friends.Places.Place.validate()
|
||||
|> @repo.insert!()
|
||||
found -> found
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,63 @@
|
||||
defmodule Friends.Places.Search do
|
||||
import Ecto.Query
|
||||
@repo Friends.Repo
|
||||
|
||||
def api_key,
|
||||
do:
|
||||
"pk.eyJ1IjoicnlhbnBhbmR5YSIsImEiOiJja3psM2tlcDA1MXl1Mm9uZmo5bGxpNzdxIn0.TwBKpTTypcD5fWFc8XRyHg"
|
||||
|
||||
def viewbox(region) do
|
||||
[lat_min, lat_max, lon_min, lon_max] = region |> Enum.map(&String.to_float/1)
|
||||
|
||||
[
|
||||
lat_min - 1,
|
||||
lat_max + 1,
|
||||
lon_min - 1,
|
||||
lon_max + 1
|
||||
]
|
||||
end
|
||||
|
||||
def known_places(str) do
|
||||
@repo.all(
|
||||
from(
|
||||
p in Friends.Places.Place,
|
||||
where: ilike(p.name, ^"%#{str}%")
|
||||
)
|
||||
)
|
||||
|> Enum.map(
|
||||
&%{
|
||||
"center" => &1.latlon,
|
||||
"place_name" => &1.name,
|
||||
"id" => "known.#{&1.id}"
|
||||
}
|
||||
)
|
||||
end
|
||||
|
||||
def autocomplete(str, region \\ nil) do
|
||||
viewbox =
|
||||
if region do
|
||||
viewbox(autocomplete(region))
|
||||
end
|
||||
|
||||
url =
|
||||
"https://api.mapbox.com/geocoding/v5/mapbox.places/#{str}.json?proximity=ip&types=place%2Cpostcode%2Caddress&access_token=#{api_key}"
|
||||
|
||||
response = HTTPoison.get!(url)
|
||||
results = Poison.decode!(response.body)
|
||||
IO.inspect(results["features"])
|
||||
|
||||
known_places(str) ++ results["features"]
|
||||
end
|
||||
|
||||
def parse_features(%{
|
||||
"center" => lonlat,
|
||||
"place_name" => name,
|
||||
"id" => id
|
||||
}) do
|
||||
%{
|
||||
name: name,
|
||||
value: lonlat |> Enum.reverse() |> Poison.encode!(),
|
||||
id: id |> String.replace(".", "-")
|
||||
}
|
||||
end
|
||||
end
|
||||
@@ -1,9 +1,10 @@
|
||||
defmodule Friends.Relationship do
|
||||
use Ecto.Schema
|
||||
import Ecto.Query
|
||||
alias Friends.{Relationship,Event,Friend}
|
||||
alias Friends.{Relationship, Friend}
|
||||
|
||||
@repo Friends.Repo
|
||||
@default_type 3
|
||||
|
||||
schema "relationships" do
|
||||
field(:friend_id, :id)
|
||||
@@ -13,7 +14,7 @@ defmodule Friends.Relationship do
|
||||
has_many(:events, Friends.Event)
|
||||
end
|
||||
|
||||
@attrs [:friend_id, :relation_id]
|
||||
@attrs [:friend_id, :relation_id, :type]
|
||||
|
||||
def types(index) do
|
||||
types() |> elem(index)
|
||||
@@ -22,11 +23,12 @@ defmodule Friends.Relationship do
|
||||
def types do
|
||||
# Tuple: name of the type, associated color, and what that person "is" to the other
|
||||
{
|
||||
{:acquaintances, :info, nil},
|
||||
{:self, :hidden, :self},
|
||||
{:acquaintances, :info, :known},
|
||||
{:family, :primary, :relative},
|
||||
{:friends, :secondary, :friend},
|
||||
{:partners, :info, :partner},
|
||||
{:dating, :success, :date},
|
||||
{:dating, :success, :dating},
|
||||
{:engaged, :success, :fiancé},
|
||||
{:married, :success, :spouse},
|
||||
{:divorced, :error, :ex},
|
||||
@@ -35,6 +37,16 @@ defmodule Friends.Relationship do
|
||||
}
|
||||
end
|
||||
|
||||
def type_index(type) do
|
||||
types()
|
||||
|> Tuple.to_list()
|
||||
|> Enum.find_index(
|
||||
&(&1
|
||||
|> elem(0)
|
||||
|> to_string() == type)
|
||||
)
|
||||
end
|
||||
|
||||
def get_type(rel) do
|
||||
rel.type |> types |> elem(0)
|
||||
end
|
||||
@@ -55,9 +67,27 @@ defmodule Friends.Relationship do
|
||||
)
|
||||
end
|
||||
|
||||
def validate_type(%{changes: %{type: type}} = changeset) do
|
||||
if type |> is_integer() and type >= 0 and type < types() |> Tuple.to_list() |> length do
|
||||
changeset
|
||||
else
|
||||
changeset |> Ecto.Changeset.add_error(:type, "Invalid type")
|
||||
end
|
||||
end
|
||||
|
||||
def validate_type(changeset), do: changeset
|
||||
|
||||
def update(rel, params \\ %{}) do
|
||||
rel
|
||||
|> changeset(params)
|
||||
|> Map.put(:action, :update)
|
||||
|> @repo.update!()
|
||||
end
|
||||
|
||||
def changeset(struct, params \\ %{}) do
|
||||
struct
|
||||
|> Ecto.Changeset.cast(params, @attrs)
|
||||
|> validate_type
|
||||
|> Ecto.Changeset.unique_constraint(
|
||||
[:friend_id, :relation_id],
|
||||
name: :relationships_friend_id_relation_id_index
|
||||
@@ -68,28 +98,39 @@ defmodule Friends.Relationship do
|
||||
)
|
||||
end
|
||||
|
||||
def new(friend1, friend2, type \\ 0) do
|
||||
def all() do
|
||||
preloads = []
|
||||
@repo.all(from(r in Friends.Relationship, where: r.type != 0, preload: ^preloads))
|
||||
end
|
||||
|
||||
def new(friend1, friend2, type \\ @default_type) do
|
||||
id1 = friend1.id
|
||||
id2 = friend2.id
|
||||
{:ok, relationship} = @repo.insert(
|
||||
%Relationship{
|
||||
|
||||
rel_type = if id1 == id2, do: 0, else: type
|
||||
|
||||
relationship =
|
||||
@repo.insert!(%Relationship{
|
||||
friend_id: id1,
|
||||
relation_id: id2,
|
||||
type: type
|
||||
}
|
||||
)
|
||||
type: rel_type
|
||||
})
|
||||
|
||||
relationship
|
||||
end
|
||||
|
||||
def get(friend1, friend2) do
|
||||
id1 = friend1.id
|
||||
id2 = friend2.id
|
||||
rel = @repo.one(
|
||||
|
||||
rel =
|
||||
@repo.one(
|
||||
from(r in Relationship,
|
||||
where: r.friend_id == ^id1 and r.relation_id == ^id2,
|
||||
preload: [:events]
|
||||
)
|
||||
)
|
||||
|
||||
if rel == nil do
|
||||
@repo.one(
|
||||
from(r in Relationship,
|
||||
@@ -102,16 +143,41 @@ defmodule Friends.Relationship do
|
||||
end
|
||||
end
|
||||
|
||||
def get_or_new(a,b) do
|
||||
def get_or_create(a, b) do
|
||||
case get(a, b) do
|
||||
nil -> new(a,b)
|
||||
nil -> new(a, b)
|
||||
relationship -> relationship
|
||||
end
|
||||
end
|
||||
|
||||
def get_by_id(id) do
|
||||
case @repo.one(
|
||||
from(r in Relationship,
|
||||
where: r.id == ^id
|
||||
)
|
||||
) do
|
||||
nil -> nil
|
||||
rel -> rel |> load_preloads()
|
||||
end
|
||||
end
|
||||
|
||||
def delete(rel) do
|
||||
rel |> Friends.Repo.delete!()
|
||||
end
|
||||
|
||||
def delete(a, b) do
|
||||
get(a, b) |> delete
|
||||
end
|
||||
|
||||
def change_type(rel, type) do
|
||||
rel
|
||||
|> changeset(%{type: type})
|
||||
|> update()
|
||||
end
|
||||
|
||||
def get_by_slugs([slug1, slug2]) do
|
||||
friend1 = slug1 |> Friend.get_by_slug
|
||||
friend2 = slug2 |> Friend.get_by_slug
|
||||
friend1 = slug1 |> Friend.get_by_slug()
|
||||
friend2 = slug2 |> Friend.get_by_slug()
|
||||
get(friend1, friend2)
|
||||
end
|
||||
|
||||
@@ -124,10 +190,40 @@ defmodule Friends.Relationship do
|
||||
end
|
||||
|
||||
def age(relationship) do
|
||||
relationship.events
|
||||
|> Enum.map(fn(event) ->
|
||||
Date.diff(Date.utc_today, event.date)
|
||||
end) |> Enum.sort |> List.last |> div(365)
|
||||
case relationship.events do
|
||||
[] ->
|
||||
nil
|
||||
|
||||
e ->
|
||||
e
|
||||
|> Enum.map(fn event ->
|
||||
Date.diff(Date.utc_today(), event.date)
|
||||
end)
|
||||
|> Enum.sort()
|
||||
|> List.last()
|
||||
|> div(365)
|
||||
end
|
||||
end
|
||||
|
||||
def load_events(
|
||||
%Relationship{
|
||||
events: %Ecto.Association.NotLoaded{}
|
||||
} = model
|
||||
) do
|
||||
model
|
||||
|> @repo.preload([:events])
|
||||
end
|
||||
|
||||
def load_events(%Relationship{} = r), do: r
|
||||
|
||||
def load_preloads(
|
||||
%Relationship{
|
||||
events: %Ecto.Association.NotLoaded{}
|
||||
} = model
|
||||
) do
|
||||
model
|
||||
|> @repo.preload([:events])
|
||||
end
|
||||
|
||||
def load_preloads(%Relationship{} = r), do: r
|
||||
end
|
||||
|
||||
@@ -2,4 +2,13 @@ defmodule Friends.Repo do
|
||||
use Ecto.Repo,
|
||||
otp_app: :friends,
|
||||
adapter: Ecto.Adapters.Postgres
|
||||
|
||||
def commit!(changeset) do
|
||||
IO.inspect(changeset)
|
||||
|
||||
case changeset.action do
|
||||
:update -> update!(changeset)
|
||||
:insert -> insert!(changeset)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
+23
-111
@@ -24,6 +24,10 @@ defmodule FriendsWeb do
|
||||
import Plug.Conn
|
||||
import FriendsWeb.Gettext
|
||||
alias FriendsWeb.Router.Helpers, as: Routes
|
||||
|
||||
alias Friends.{Friend, Relationship}
|
||||
alias Friends.Accounts.User
|
||||
import Helpers
|
||||
end
|
||||
end
|
||||
|
||||
@@ -48,6 +52,15 @@ defmodule FriendsWeb do
|
||||
use Phoenix.LiveView,
|
||||
layout: {FriendsWeb.LayoutView, "live.html"}
|
||||
|
||||
alias FriendsWeb.Router.Helpers, as: Routes
|
||||
|
||||
import Helpers
|
||||
import Helpers.Names
|
||||
import FriendsWeb.LiveHelpers
|
||||
import FriendsWeb.Components
|
||||
|
||||
alias Friends.{Friend, Relationship, Places}
|
||||
|
||||
unquote(view_helpers())
|
||||
end
|
||||
end
|
||||
@@ -55,6 +68,14 @@ defmodule FriendsWeb do
|
||||
def live_component do
|
||||
quote do
|
||||
use Phoenix.LiveComponent
|
||||
import Helpers
|
||||
import FriendsWeb.LiveHelpers
|
||||
alias Friends.{Friend, Relationship, Places}
|
||||
alias FriendsWeb.Components.{Autocomplete, Map, Cards}
|
||||
alias FriendsWeb.Components
|
||||
alias FriendsWeb.Router.Helpers, as: Routes
|
||||
alias FriendsWeb.LiveViews
|
||||
alias Phoenix.LiveView.JS
|
||||
|
||||
unquote(view_helpers())
|
||||
end
|
||||
@@ -63,117 +84,8 @@ defmodule FriendsWeb do
|
||||
def component do
|
||||
quote do
|
||||
use Phoenix.Component
|
||||
|
||||
unquote(view_helpers())
|
||||
end
|
||||
end
|
||||
|
||||
def router do
|
||||
quote do
|
||||
use Phoenix.Router
|
||||
import Phoenix.Component
|
||||
import Plug.Conn
|
||||
import Phoenix.Controller
|
||||
import Phoenix.LiveView.Router
|
||||
end
|
||||
end
|
||||
|
||||
def channel do
|
||||
quote do
|
||||
use Phoenix.Channel
|
||||
import FriendsWeb.Gettext
|
||||
end
|
||||
end
|
||||
|
||||
defp view_helpers do
|
||||
quote do
|
||||
# Use all HTML functionality (forms, tags, etc)
|
||||
use Phoenix.HTML
|
||||
|
||||
# Import LiveView and .heex helpers (live_render, live_patch, <.form>, etc)
|
||||
import Phoenix.LiveView.Helpers
|
||||
|
||||
# Import basic rendering functionality (render, render_layout, etc)
|
||||
import Phoenix.View
|
||||
|
||||
import FriendsWeb.ErrorHelpers
|
||||
import FriendsWeb.Gettext
|
||||
alias FriendsWeb.Router.Helpers, as: Routes
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
When used, dispatch to the appropriate controller/view/etc.
|
||||
"""
|
||||
defmacro __using__(which) when is_atom(which) do
|
||||
apply(__MODULE__, which, [])
|
||||
end
|
||||
end
|
||||
defmodule FriendsWeb do
|
||||
@moduledoc """
|
||||
The entrypoint for defining your web interface, such
|
||||
as controllers, views, channels and so on.
|
||||
|
||||
This can be used in your application as:
|
||||
|
||||
use FriendsWeb, :controller
|
||||
use FriendsWeb, :view
|
||||
|
||||
The definitions below will be executed for every view,
|
||||
controller, etc, so keep them short and clean, focused
|
||||
on imports, uses and aliases.
|
||||
|
||||
Do NOT define functions inside the quoted expressions
|
||||
below. Instead, define any helper function in modules
|
||||
and import those modules here.
|
||||
"""
|
||||
|
||||
def controller do
|
||||
quote do
|
||||
use Phoenix.Controller, namespace: FriendsWeb
|
||||
|
||||
import Plug.Conn
|
||||
import FriendsWeb.Gettext
|
||||
alias FriendsWeb.Router.Helpers, as: Routes
|
||||
end
|
||||
end
|
||||
|
||||
def view do
|
||||
quote do
|
||||
use Phoenix.View,
|
||||
root: "lib/friends_web/templates",
|
||||
namespace: FriendsWeb
|
||||
|
||||
# Import convenience functions from controllers
|
||||
import Phoenix.Controller,
|
||||
only: [get_flash: 1, get_flash: 2, view_module: 1, view_template: 1]
|
||||
|
||||
import Phoenix.Component
|
||||
# Include shared imports and aliases for views
|
||||
unquote(view_helpers())
|
||||
end
|
||||
end
|
||||
|
||||
def live_view do
|
||||
quote do
|
||||
use Phoenix.LiveView,
|
||||
layout: {FriendsWeb.LayoutView, "live.html"}
|
||||
|
||||
unquote(view_helpers())
|
||||
end
|
||||
end
|
||||
|
||||
def live_component do
|
||||
quote do
|
||||
use Phoenix.LiveComponent
|
||||
|
||||
unquote(view_helpers())
|
||||
end
|
||||
end
|
||||
|
||||
def component do
|
||||
quote do
|
||||
use Phoenix.Component
|
||||
import Helpers
|
||||
import FriendsWeb.LiveHelpers
|
||||
|
||||
unquote(view_helpers())
|
||||
end
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
defmodule FriendsWeb.FriendsController do
|
||||
use FriendsWeb, :controller
|
||||
|
||||
def index(conn, _params) do
|
||||
conn
|
||||
|> assign(:all_friends, Friend.all())
|
||||
|> render("index.html")
|
||||
end
|
||||
end
|
||||
@@ -1,7 +1,21 @@
|
||||
defmodule FriendsWeb.PageController do
|
||||
use FriendsWeb, :controller
|
||||
alias Friends.{Friend, Repo, Accounts.User, Accounts}
|
||||
|
||||
import Helpers.Names
|
||||
|
||||
def index(conn, _params) do
|
||||
render(conn, "index.html")
|
||||
new_friend = Friend.new() |> Friend.changeset()
|
||||
|
||||
if(conn |> get_session(:linked)) do
|
||||
# If logged in and linked, redirect to friend_path :index
|
||||
conn |> redirect(to: FriendsWeb.Router.Helpers.friends_path(conn, :index))
|
||||
else
|
||||
# Otherwise, show the landing page
|
||||
conn
|
||||
|> assign(:new_friend, new_friend)
|
||||
|> assign(:friends, Friend.all())
|
||||
|> render("index.html")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
defmodule FriendsWeb.RelationshipsController do
|
||||
use FriendsWeb, :controller
|
||||
|
||||
def delete(id) do
|
||||
rel = Relationship.get_by_id(id)
|
||||
|
||||
IO.inspect("Deleting #{rel}")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,200 @@
|
||||
defmodule FriendsWeb.UserAuth do
|
||||
import Plug.Conn
|
||||
import Phoenix.Controller
|
||||
|
||||
alias Friends.Accounts
|
||||
alias FriendsWeb.Router.Helpers, as: Routes
|
||||
|
||||
# Make the remember me cookie valid for 60 days.
|
||||
# If you want bump or reduce this value, also change
|
||||
# the token expiry itself in UserToken.
|
||||
@max_age 60 * 60 * 24 * 60
|
||||
@remember_me_cookie "_friends_web_user_remember_me"
|
||||
@remember_me_options [sign: true, max_age: @max_age, same_site: "Lax"]
|
||||
|
||||
@doc """
|
||||
Logs the user in.
|
||||
|
||||
It renews the session ID and clears the whole session
|
||||
to avoid fixation attacks. See the renew_session
|
||||
function to customize this behaviour.
|
||||
|
||||
It also sets a `:live_socket_id` key in the session,
|
||||
so LiveView sessions are identified and automatically
|
||||
disconnected on log out. The line can be safely removed
|
||||
if you are not using LiveView.
|
||||
"""
|
||||
def log_in_user(conn, user, params \\ %{}) do
|
||||
token = Accounts.generate_user_session_token(user)
|
||||
user_return_to = get_session(conn, :user_return_to)
|
||||
|
||||
conn
|
||||
|> renew_session()
|
||||
|> put_session(:user_token, token)
|
||||
|> put_session(:live_socket_id, "users_sessions:#{Base.url_encode64(token)}")
|
||||
|> maybe_write_remember_me_cookie(token, params)
|
||||
|> redirect(to: user_return_to || signed_in_path(conn))
|
||||
end
|
||||
|
||||
defp maybe_write_remember_me_cookie(conn, token, %{"remember_me" => "true"}) do
|
||||
put_resp_cookie(conn, @remember_me_cookie, token, @remember_me_options)
|
||||
end
|
||||
|
||||
defp maybe_write_remember_me_cookie(conn, _token, _params) do
|
||||
conn
|
||||
end
|
||||
|
||||
# This function renews the session ID and erases the whole
|
||||
# session to avoid fixation attacks. If there is any data
|
||||
# in the session you may want to preserve after log in/log out,
|
||||
# you must explicitly fetch the session data before clearing
|
||||
# and then immediately set it after clearing, for example:
|
||||
#
|
||||
# defp renew_session(conn) do
|
||||
# preferred_locale = get_session(conn, :preferred_locale)
|
||||
#
|
||||
# conn
|
||||
# |> configure_session(renew: true)
|
||||
# |> clear_session()
|
||||
# |> put_session(:preferred_locale, preferred_locale)
|
||||
# end
|
||||
#
|
||||
defp renew_session(conn) do
|
||||
conn
|
||||
|> configure_session(renew: true)
|
||||
|> clear_session()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Logs the user out.
|
||||
|
||||
It clears all session data for safety. See renew_session.
|
||||
"""
|
||||
def log_out_user(conn) do
|
||||
user_token = get_session(conn, :user_token)
|
||||
user_token && Accounts.delete_session_token(user_token)
|
||||
|
||||
if live_socket_id = get_session(conn, :live_socket_id) do
|
||||
FriendsWeb.Endpoint.broadcast(live_socket_id, "disconnect", %{})
|
||||
end
|
||||
|
||||
conn
|
||||
|> renew_session()
|
||||
|> delete_resp_cookie(@remember_me_cookie)
|
||||
|> redirect(to: "/")
|
||||
end
|
||||
|
||||
@doc """
|
||||
Authenticates the user by looking into the session
|
||||
and remember me token.
|
||||
"""
|
||||
def fetch_current_user(conn, _opts) do
|
||||
{user_token, conn} = ensure_user_token(conn)
|
||||
user = user_token && Accounts.get_user_by_session_token(user_token)
|
||||
|
||||
assign(
|
||||
conn,
|
||||
:current_user,
|
||||
user
|
||||
|> Friends.Repo.preload(:profile)
|
||||
)
|
||||
end
|
||||
|
||||
defp ensure_user_token(conn) do
|
||||
if user_token = get_session(conn, :user_token) do
|
||||
{user_token, conn}
|
||||
else
|
||||
conn = fetch_cookies(conn, signed: [@remember_me_cookie])
|
||||
|
||||
if user_token = conn.cookies[@remember_me_cookie] do
|
||||
{user_token, put_session(conn, :user_token, user_token)}
|
||||
else
|
||||
{nil, conn}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Used for routes that require the user to not be authenticated.
|
||||
"""
|
||||
def redirect_if_user_is_authenticated(conn, _opts) do
|
||||
if conn.assigns[:current_user] do
|
||||
conn
|
||||
|> redirect(to: signed_in_path(conn))
|
||||
|> halt()
|
||||
else
|
||||
conn
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Used to detect or link a profile to a user.
|
||||
"""
|
||||
def capture_profile(conn, _opts) do
|
||||
current_user = conn.assigns[:current_user]
|
||||
|
||||
if current_user do
|
||||
# There's a user, but is there a profile?
|
||||
profile = current_user |> Map.get(:profile)
|
||||
|
||||
case profile do
|
||||
nil ->
|
||||
# No profile linked
|
||||
conn
|
||||
|> create_or_link_profile(current_user)
|
||||
|
||||
_profile ->
|
||||
# Profile already linked
|
||||
conn |> put_session(:linked, true)
|
||||
end
|
||||
else
|
||||
# Not logged in
|
||||
conn
|
||||
end
|
||||
end
|
||||
|
||||
defp create_or_link_profile(conn, user) do
|
||||
case user.email |> Friends.Friend.get_by_email() do
|
||||
# Find a profile and link it
|
||||
nil ->
|
||||
conn
|
||||
|> put_flash(:info, "You're logged in but we still need to make you a profile!")
|
||||
|> redirect(to: Routes.friends_edit_path(conn, :welcome))
|
||||
|> halt()
|
||||
|
||||
# Or make a new one
|
||||
_profile ->
|
||||
user
|
||||
|> Friends.Accounts.assign_profile()
|
||||
|
||||
conn
|
||||
|> put_session(:linked, true)
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Used for routes that require the user to be authenticated.
|
||||
|
||||
If you want to enforce the user email is confirmed before
|
||||
they use the application at all, here would be a good place.
|
||||
"""
|
||||
def require_authenticated_user(conn, _opts \\ nil) do
|
||||
if conn.assigns[:current_user] do
|
||||
conn
|
||||
else
|
||||
conn
|
||||
|> put_flash(:error, "You must log in to access this page.")
|
||||
|> maybe_store_return_to()
|
||||
|> redirect(to: Routes.user_session_path(conn, :new))
|
||||
|> halt()
|
||||
end
|
||||
end
|
||||
|
||||
defp maybe_store_return_to(%{method: "GET"} = conn) do
|
||||
put_session(conn, :user_return_to, current_path(conn))
|
||||
end
|
||||
|
||||
defp maybe_store_return_to(conn), do: conn
|
||||
|
||||
defp signed_in_path(_conn), do: "/"
|
||||
end
|
||||
@@ -0,0 +1,56 @@
|
||||
defmodule FriendsWeb.UserConfirmationController do
|
||||
use FriendsWeb, :controller
|
||||
|
||||
alias Friends.Accounts
|
||||
|
||||
def new(conn, _params) do
|
||||
render(conn, "new.html")
|
||||
end
|
||||
|
||||
def create(conn, %{"user" => %{"email" => email}}) do
|
||||
if user = Accounts.get_user_by_email(email) do
|
||||
Accounts.deliver_user_confirmation_instructions(
|
||||
user,
|
||||
&Routes.user_confirmation_url(conn, :edit, &1)
|
||||
)
|
||||
end
|
||||
|
||||
conn
|
||||
|> put_flash(
|
||||
:info,
|
||||
"If your email is in our system and it has not been confirmed yet, " <>
|
||||
"you will receive an email with instructions shortly."
|
||||
)
|
||||
|> redirect(to: "/")
|
||||
end
|
||||
|
||||
def edit(conn, %{"token" => token}) do
|
||||
render(conn, "edit.html", token: token)
|
||||
end
|
||||
|
||||
# Do not log in the user after confirmation to avoid a
|
||||
# leaked token giving the user access to the account.
|
||||
def update(conn, %{"token" => token}) do
|
||||
case Accounts.confirm_user(token) do
|
||||
{:ok, _} ->
|
||||
conn
|
||||
|> put_flash(:info, "User confirmed successfully.")
|
||||
|> redirect(to: "/")
|
||||
|
||||
:error ->
|
||||
# If there is a current user and the account was already confirmed,
|
||||
# then odds are that the confirmation link was already visited, either
|
||||
# by some automation or by the user themselves, so we redirect without
|
||||
# a warning message.
|
||||
case conn.assigns do
|
||||
%{current_user: %{confirmed_at: confirmed_at}} when not is_nil(confirmed_at) ->
|
||||
redirect(conn, to: "/")
|
||||
|
||||
%{} ->
|
||||
conn
|
||||
|> put_flash(:error, "User confirmation link is invalid or it has expired.")
|
||||
|> redirect(to: "/")
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,32 @@
|
||||
defmodule FriendsWeb.UserProfileController do
|
||||
use FriendsWeb, :controller
|
||||
|
||||
alias Friends.Accounts
|
||||
alias FriendsWeb.Router.Helpers, as: Routes
|
||||
|
||||
plug :assign_profile
|
||||
|
||||
|
||||
|
||||
@doc """
|
||||
Checks if the user has linked a profile yet,
|
||||
and redirects to the profile creation flow
|
||||
if not.
|
||||
"""
|
||||
def main(conn) do
|
||||
conn
|
||||
|> put_flash(:info, "test")
|
||||
end
|
||||
|
||||
defp assign_profile(conn, _opts) do
|
||||
user = conn.assigns.current_user
|
||||
|
||||
msg = case user.profile do
|
||||
nil -> "No profile!"
|
||||
profile -> "Yes profile! #{profile.name}"
|
||||
end
|
||||
|
||||
conn
|
||||
|> put_flash(:info, msg)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,30 @@
|
||||
defmodule FriendsWeb.UserRegistrationController do
|
||||
use FriendsWeb, :controller
|
||||
|
||||
alias Friends.Accounts
|
||||
alias Friends.Accounts.User
|
||||
alias FriendsWeb.UserAuth
|
||||
|
||||
def new(conn, _params) do
|
||||
changeset = Accounts.change_user_registration(%User{})
|
||||
render(conn, "new.html", changeset: changeset)
|
||||
end
|
||||
|
||||
def create(conn, %{"user" => user_params}) do
|
||||
case Accounts.register_user(user_params) do
|
||||
{:ok, user} ->
|
||||
{:ok, _} =
|
||||
Accounts.deliver_user_confirmation_instructions(
|
||||
user,
|
||||
&Routes.user_confirmation_url(conn, :edit, &1)
|
||||
)
|
||||
|
||||
conn
|
||||
|> put_flash(:info, "User created successfully.")
|
||||
|> UserAuth.log_in_user(user)
|
||||
|
||||
{:error, %Ecto.Changeset{} = changeset} ->
|
||||
render(conn, "new.html", changeset: changeset)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,58 @@
|
||||
defmodule FriendsWeb.UserResetPasswordController do
|
||||
use FriendsWeb, :controller
|
||||
|
||||
alias Friends.Accounts
|
||||
|
||||
plug :get_user_by_reset_password_token when action in [:edit, :update]
|
||||
|
||||
def new(conn, _params) do
|
||||
render(conn, "new.html")
|
||||
end
|
||||
|
||||
def create(conn, %{"user" => %{"email" => email}}) do
|
||||
if user = Accounts.get_user_by_email(email) do
|
||||
Accounts.deliver_user_reset_password_instructions(
|
||||
user,
|
||||
&Routes.user_reset_password_url(conn, :edit, &1)
|
||||
)
|
||||
end
|
||||
|
||||
conn
|
||||
|> put_flash(
|
||||
:info,
|
||||
"If your email is in our system, you will receive instructions to reset your password shortly."
|
||||
)
|
||||
|> redirect(to: "/")
|
||||
end
|
||||
|
||||
def edit(conn, _params) do
|
||||
render(conn, "edit.html", changeset: Accounts.change_user_password(conn.assigns.user))
|
||||
end
|
||||
|
||||
# Do not log in the user after reset password to avoid a
|
||||
# leaked token giving the user access to the account.
|
||||
def update(conn, %{"user" => user_params}) do
|
||||
case Accounts.reset_user_password(conn.assigns.user, user_params) do
|
||||
{:ok, _} ->
|
||||
conn
|
||||
|> put_flash(:info, "Password reset successfully.")
|
||||
|> redirect(to: Routes.user_session_path(conn, :new))
|
||||
|
||||
{:error, changeset} ->
|
||||
render(conn, "edit.html", changeset: changeset)
|
||||
end
|
||||
end
|
||||
|
||||
defp get_user_by_reset_password_token(conn, _opts) do
|
||||
%{"token" => token} = conn.params
|
||||
|
||||
if user = Accounts.get_user_by_reset_password_token(token) do
|
||||
conn |> assign(:user, user) |> assign(:token, token)
|
||||
else
|
||||
conn
|
||||
|> put_flash(:error, "Reset password link is invalid or it has expired.")
|
||||
|> redirect(to: "/")
|
||||
|> halt()
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,27 @@
|
||||
defmodule FriendsWeb.UserSessionController do
|
||||
use FriendsWeb, :controller
|
||||
|
||||
alias Friends.Accounts
|
||||
alias FriendsWeb.UserAuth
|
||||
|
||||
def new(conn, _params) do
|
||||
render(conn, "new.html", error_message: nil)
|
||||
end
|
||||
|
||||
def create(conn, %{"user" => user_params}) do
|
||||
%{"email" => email, "password" => password} = user_params
|
||||
|
||||
if user = Accounts.get_user_by_email_and_password(email, password) do
|
||||
UserAuth.log_in_user(conn, user, user_params)
|
||||
else
|
||||
# In order to prevent user enumeration attacks, don't disclose whether the email is registered.
|
||||
render(conn, "new.html", error_message: "Invalid email or password")
|
||||
end
|
||||
end
|
||||
|
||||
def delete(conn, _params) do
|
||||
conn
|
||||
|> put_flash(:info, "Logged out successfully.")
|
||||
|> UserAuth.log_out_user()
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,74 @@
|
||||
defmodule FriendsWeb.UserSettingsController do
|
||||
use FriendsWeb, :controller
|
||||
|
||||
alias Friends.Accounts
|
||||
alias FriendsWeb.UserAuth
|
||||
|
||||
plug :assign_email_and_password_changesets
|
||||
|
||||
def edit(conn, _params) do
|
||||
render(conn, "edit.html")
|
||||
end
|
||||
|
||||
def update(conn, %{"action" => "update_email"} = params) do
|
||||
%{"current_password" => password, "user" => user_params} = params
|
||||
user = conn.assigns.current_user
|
||||
|
||||
case Accounts.apply_user_email(user, password, user_params) do
|
||||
{:ok, applied_user} ->
|
||||
Accounts.deliver_update_email_instructions(
|
||||
applied_user,
|
||||
user.email,
|
||||
&Routes.user_settings_url(conn, :confirm_email, &1)
|
||||
)
|
||||
|
||||
conn
|
||||
|> put_flash(
|
||||
:info,
|
||||
"A link to confirm your email change has been sent to the new address."
|
||||
)
|
||||
|> redirect(to: Routes.user_settings_path(conn, :edit))
|
||||
|
||||
{:error, changeset} ->
|
||||
render(conn, "edit.html", email_changeset: changeset)
|
||||
end
|
||||
end
|
||||
|
||||
def update(conn, %{"action" => "update_password"} = params) do
|
||||
%{"current_password" => password, "user" => user_params} = params
|
||||
user = conn.assigns.current_user
|
||||
|
||||
case Accounts.update_user_password(user, password, user_params) do
|
||||
{:ok, user} ->
|
||||
conn
|
||||
|> put_flash(:info, "Password updated successfully.")
|
||||
|> put_session(:user_return_to, Routes.user_settings_path(conn, :edit))
|
||||
|> UserAuth.log_in_user(user)
|
||||
|
||||
{:error, changeset} ->
|
||||
render(conn, "edit.html", password_changeset: changeset)
|
||||
end
|
||||
end
|
||||
|
||||
def confirm_email(conn, %{"token" => token}) do
|
||||
case Accounts.update_user_email(conn.assigns.current_user, token) do
|
||||
:ok ->
|
||||
conn
|
||||
|> put_flash(:info, "Email changed successfully.")
|
||||
|> redirect(to: Routes.user_settings_path(conn, :edit))
|
||||
|
||||
:error ->
|
||||
conn
|
||||
|> put_flash(:error, "Email change link is invalid or it has expired.")
|
||||
|> redirect(to: Routes.user_settings_path(conn, :edit))
|
||||
end
|
||||
end
|
||||
|
||||
defp assign_email_and_password_changesets(conn, _opts) do
|
||||
user = conn.assigns.current_user
|
||||
|
||||
conn
|
||||
|> assign(:email_changeset, Accounts.change_user_email(user))
|
||||
|> assign(:password_changeset, Accounts.change_user_password(user))
|
||||
end
|
||||
end
|
||||
@@ -10,7 +10,8 @@ defmodule FriendsWeb.Endpoint do
|
||||
signing_salt: "jNBoklme"
|
||||
]
|
||||
|
||||
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
|
||||
socket "/live", Phoenix.LiveView.Socket,
|
||||
websocket: [connect_info: [:peer_data, session: @session_options]]
|
||||
|
||||
# Serve at "/" the static files from "priv/static" directory.
|
||||
#
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
defmodule FriendsWeb.Components.Autocomplete do
|
||||
use FriendsWeb, :live_component
|
||||
import Helpers
|
||||
|
||||
alias Phoenix.LiveView.JS
|
||||
|
||||
def bolden(string, substring) do
|
||||
String.replace(
|
||||
string,
|
||||
substring,
|
||||
"<b>#{substring}</b>"
|
||||
)
|
||||
|> Phoenix.HTML.raw()
|
||||
end
|
||||
|
||||
def search_results(assigns) do
|
||||
~H"""
|
||||
<div id="search-results" class="absolute w-full bottom-16 left-0">
|
||||
|
||||
<%= if @search_results do %>
|
||||
<ul tabindex="0" class="dropdown-content menu p-0 m-0 shadow bg-base-200 rounded-box overflow-auto">
|
||||
<%= for r <- @search_results do %>
|
||||
<li class="p-0 m-0">
|
||||
<.link id={r[:id]}
|
||||
phx_value={r[:value]}
|
||||
class="search_result"
|
||||
phx-hook="NewRelation"
|
||||
onMouseDown={"#{@select_fxn}('#{r[:value]}', '#{r[:name]}')"}>
|
||||
<%= r[:name] |> bolden(@search_query) %>
|
||||
</.link>
|
||||
</li>
|
||||
<% end %>
|
||||
</ul>
|
||||
<% end %>
|
||||
|
||||
</div>
|
||||
"""
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,43 @@
|
||||
defmodule FriendsWeb.Components.Cards do
|
||||
use FriendsWeb, :live_component
|
||||
|
||||
import Helpers.Names
|
||||
|
||||
def relationship_card(assigns) do
|
||||
~H"""
|
||||
<div id={"relation-#{@relation.id}"} class="relative overflow-visible card card-compact w-96 bg-base-100 shadow-xl" phx-hook="RelationshipCard" relationship-id={@relationship.id}>
|
||||
|
||||
|
||||
<%= if @editable do %>
|
||||
<!-- The button to open modal -->
|
||||
<label for={"delete-relationship-#{@relation.id}"} class="btn btn-error absolute top-2 right-2">delete</label>
|
||||
<% end %>
|
||||
|
||||
<figure class="p-0 m-0"><img class="py-0 my-0" src="https://placeimg.com/400/225/people" alt={@relation.id} /></figure>
|
||||
<div class="card-body">
|
||||
<div class="flex flex-row justify-between items-center">
|
||||
<h2 class="card-title py-0 my-0"><.link navigate={Routes.friends_show_path(FriendsWeb.Endpoint, :overview, @relation.slug)} class="no-underline font-bold hover:underline"><%=@relation.name%></.link></h2>
|
||||
<.link patch={Routes.relationship_show_path(FriendsWeb.Endpoint, :overview, @friend.slug, @relation.slug)}>(details)</.link>
|
||||
|
||||
</div>
|
||||
<Components.relationship_details editable={@editable} relationship={@relationship} />
|
||||
</div>
|
||||
</div>
|
||||
<input type="checkbox" id={"delete-relationship-#{@relation.id}"} class="modal-toggle" />
|
||||
<div class="modal modal-bottom sm:modal-middle">
|
||||
<div class="modal-box">
|
||||
<h3 class="font-bold text-lg mt-0 pt-0">Are you sure you want to delete <%=@friend |> first_name%>'s relationship with <%=@relation |> first_name%>?</h3>
|
||||
<p class="py-4">Unless these two people really don't know each other, you probably want to change the relationship type, e.g. from "dating" to "ex".</p>
|
||||
<div class="modal-action">
|
||||
<label for={"delete-relationship-#{@relation.id}"} class="btn btn-sm btn-ghost">Never mind</label>
|
||||
<label for={"delete-relationship-#{@relation.id}"} class="btn btn-sm btn-primary" onClick={"javascript:deleteRelation(#{@relationship.id})"}>Accept</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
end
|
||||
|
||||
def confirm_dialog(id) do
|
||||
JS.show(to: "#warning-relation-#{id}")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,110 @@
|
||||
defmodule FriendsWeb.Components do
|
||||
use FriendsWeb, :live_component
|
||||
|
||||
def header(assigns) do
|
||||
~H"""
|
||||
<div class="border-b-4 flex flex-row justify-between">
|
||||
<h1 class="mb-0 pl-2" style="height:48px; text-indent:5px"><%= @friend.name %></h1>
|
||||
</div>
|
||||
"""
|
||||
end
|
||||
|
||||
def menu(assigns) do
|
||||
~H"""
|
||||
<div class="hidden sm:tabs sm:mb-8">
|
||||
<%= for page <- [:overview, :timeline, :relationships] do %>
|
||||
<% is_active = if(page == @live_action) do "tab-active" end %>
|
||||
<.link patch={Routes.friends_show_path(FriendsWeb.Endpoint, page, @friend.slug)} class={"font-bold sm:tab-lg flex-grow no-underline tab tab-lifted #{is_active}"}>
|
||||
<%= page |> to_string |> :string.titlecase() %>
|
||||
</.link>
|
||||
<% end %>
|
||||
</div>
|
||||
"""
|
||||
end
|
||||
|
||||
@spec edit_menu(any) :: Phoenix.LiveView.Rendered.t()
|
||||
def edit_menu(assigns) do
|
||||
if assigns.live_action == :welcome,
|
||||
do: "",
|
||||
else: ~H"""
|
||||
<div class="hidden sm:tabs sm:mb-8">
|
||||
<%= for page <- [:overview, :timeline, :relationships] do %>
|
||||
<% is_active = if(page == @live_action) do "tab-active" end %>
|
||||
<.link patch={Routes.friends_edit_path(FriendsWeb.Endpoint, page, @friend.slug)} class={"font-bold sm:tab-lg flex-grow no-underline tab tab-lifted #{is_active}"}>
|
||||
<%= page |> to_string |> :string.titlecase() %>
|
||||
</.link>
|
||||
<% end %>
|
||||
</div>
|
||||
"""
|
||||
end
|
||||
|
||||
def relationship_details(assigns) do
|
||||
~H"""
|
||||
<div class="flex flex-row items-center gap-3">
|
||||
<div class="dropdown" id={"type-selector-#{@relationship.id}"}>
|
||||
<label tabindex="0" class={"hover:badge-ghost badge badge-#{@relationship |> Friends.Relationship.get_color} m-1 text-white"}>
|
||||
<%= @relationship |> Friends.Relationship.get_relation %>
|
||||
|
||||
<%= if @editable do %>
|
||||
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-down" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z"/> </svg>
|
||||
<% end %>
|
||||
</label>
|
||||
<Components.relationship_type_selector relationship={@relationship} />
|
||||
</div>
|
||||
|
||||
<span>since</span>
|
||||
|
||||
<%= if @relationship |> Relationship.age do %>
|
||||
<%=
|
||||
@relationship |> Relationship.age
|
||||
%>
|
||||
<% else %>
|
||||
<div class={"tooltip tooltip-#{@relationship |> Relationship.get_color}"} data-tip="add milestone dates on the detail page.">
|
||||
<a class="hover:cursor-help" style="text-decoration-style:dashed">(no date)</a>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
"""
|
||||
end
|
||||
|
||||
def relationship_type_selector(assigns) do
|
||||
~H"""
|
||||
<ul tabindex="0" class="absolute dropdown-content menu p-0 shadow bg-base-100 rounded-box w-52 justify-start">
|
||||
<%= Relationship.types()
|
||||
|> Tuple.to_list()
|
||||
|> Enum.map(fn(tuple) ->
|
||||
type = tuple |> elem(0)
|
||||
class = tuple |> elem(1) |> to_string
|
||||
|
||||
selected = (@relationship |> Relationship.get_type) == type
|
||||
|
||||
if class != "hidden" do
|
||||
if selected do
|
||||
"<li class='p-2 m-0 text-sm bg-slate-200 select-none' style='font-weight:normal;'>#{type}</li>"
|
||||
else
|
||||
"<li
|
||||
class='p-2 m-0 text-sm hover:bg-slate-400 hover:text-black hover:cursor-pointer'
|
||||
style='font-weight:normal;'
|
||||
onClick='#{relationship_type_function(@relationship.id, type)}'
|
||||
>
|
||||
#{type}
|
||||
</li>"
|
||||
end
|
||||
end
|
||||
|
||||
end) |> Enum.join
|
||||
|> raw
|
||||
%>
|
||||
</ul>
|
||||
"""
|
||||
end
|
||||
|
||||
def relationship_type_function(id, type) do
|
||||
"""
|
||||
relationType("#{id}", "#{type}")
|
||||
"""
|
||||
end
|
||||
|
||||
###
|
||||
end
|
||||
@@ -0,0 +1,9 @@
|
||||
defmodule FriendsWeb.Components.Map do
|
||||
use FriendsWeb, :live_component
|
||||
|
||||
def show(assigns) do
|
||||
~H"""
|
||||
<div id="map" phx-hook={"showMapbox"} latlon={@address_latlon}></div>
|
||||
"""
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,40 @@
|
||||
defmodule FriendsWeb.Components.SignUp do
|
||||
use FriendsWeb, :live_component
|
||||
import Helpers
|
||||
|
||||
def sign_up_form(assigns) do
|
||||
~H"""
|
||||
<.form
|
||||
for={@new_friend}
|
||||
let={f}
|
||||
phx_change= "validate"
|
||||
>
|
||||
|
||||
<div class="form-control w-full max-w-xs flex flex-row">
|
||||
<%= label f, :name, class: "label font-bold" %>
|
||||
<%= text_input f, :name, placeholder: "First Middle Last", class: "ml-2 flex-grow input input-bordered input-primary w-full max-w-xs", phx_debounce: "blur"%>
|
||||
</div>
|
||||
<div class="m-4 mt-0 pr-5 text-right max-w-xs"> <%= error_tag f, :name %></div>
|
||||
|
||||
<div class="form-control w-full max-w-xs flex flex-row">
|
||||
<%= label f, :email, class: "label font-bold" %>
|
||||
<%= text_input f, :email, placeholder: "my.friend@gmail.com", class: "ml-2 flex-grow input input-bordered input-primary w-full max-w-xs", phx_debounce: "blur"%>
|
||||
</div>
|
||||
<div class="m-4 mt-0 pr-5 text-right max-w-xs"> <%= error_tag f, :email %></div>
|
||||
|
||||
<div class="form-control w-full max-w-xs flex flex-row">
|
||||
<%= label f, :phone, class: "label font-bold" %>
|
||||
<%= text_input f, :phone, placeholder: "+1 234 5678", class: "ml-2 flex-grow input input-bordered input-primary w-full max-w-xs", phx_debounce: "blur"%>
|
||||
</div>
|
||||
<div class="m-4 mt-0 pr-5 text-right max-w-xs"> <%= error_tag f, :phone %></div>
|
||||
|
||||
|
||||
<div class="form-control w-full max-w-xs mt-10">
|
||||
<%= submit "Save", phx_disable_with: "Saving...", class: "btn" %>
|
||||
</div>
|
||||
|
||||
</.form>
|
||||
|
||||
"""
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,244 @@
|
||||
defmodule FriendsWeb.FriendsLive.Edit do
|
||||
use FriendsWeb, :live_view
|
||||
|
||||
# No slug means it's a new profile form
|
||||
def mount(%{}, token, socket) do
|
||||
friend = Friend.new()
|
||||
live_action = socket.assigns.live_action || :overview
|
||||
|
||||
{:ok,
|
||||
socket
|
||||
|> assign(:live_action, live_action)
|
||||
|> assign_current_user(token |> Map.get("user_token"))
|
||||
|> assign(:friend, friend)
|
||||
|> assign(:address_latlon, nil)
|
||||
|> assign(:search_results, nil)
|
||||
|> title("Welcome")
|
||||
|> assign(:changeset, %Friend{} |> Friend.changeset())}
|
||||
end
|
||||
|
||||
# Has a slug means it's an edit profile form
|
||||
def mount(%{"slug" => slug} = _attrs, token, socket) do
|
||||
live_action = socket.assigns.live_action || :overview
|
||||
|
||||
friend = Friend.get_by_slug(slug)
|
||||
editable = friend |> Friend.can_be_edited_by(socket.assigns[:current_user])
|
||||
|
||||
if(live_action) do
|
||||
{:ok,
|
||||
socket
|
||||
|> assign(:mode, :edit)
|
||||
|> assign(:live_action, live_action)
|
||||
|> assign_current_user(token |> Map.get("user_token"))
|
||||
|> assign(:friend, friend)
|
||||
|> assign(:editable, editable)
|
||||
|> assign(:action, Routes.friends_path(socket, :update))
|
||||
|> title(friend.name <> " - " <> (live_action |> titlecase))
|
||||
|> assign(:changeset, %Friend{} |> Friend.changeset())
|
||||
|> assign(:search_query, nil)
|
||||
|> assign(:search_results, nil)}
|
||||
else
|
||||
{:ok, socket |> redirect(to: Routes.friends_show_path(socket, :overview, friend.slug))}
|
||||
end
|
||||
end
|
||||
|
||||
# Overview form page
|
||||
def handle_params(
|
||||
%{"slug" => slug} = _attrs,
|
||||
_url,
|
||||
%{assigns: %{live_action: :overview}} = socket
|
||||
) do
|
||||
live_action = socket.assigns.live_action
|
||||
|
||||
friend = Friend.get_by_slug(slug)
|
||||
editable = friend |> Friend.can_be_edited_by(socket.assigns[:current_user])
|
||||
|
||||
{address_latlon, address_query} = friend |> Friend.get_address()
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:mode, :edit)
|
||||
|> assign_friend(friend)
|
||||
|> assign(:action, Routes.friends_path(socket, :update))
|
||||
|> assign(:live_action, live_action)
|
||||
|> assign(:search_query, address_query)
|
||||
|> assign(:address_latlon, address_latlon |> Poison.encode!())
|
||||
|> assign(:search_results, nil)
|
||||
|> title(friend.name <> " - " <> (live_action |> titlecase))
|
||||
|> assign(:editable, editable)}
|
||||
end
|
||||
|
||||
# Add a relationship
|
||||
def handle_params(
|
||||
%{"slug" => slug} = _attrs,
|
||||
_url,
|
||||
%{assigns: %{live_action: :relationships}} = socket
|
||||
) do
|
||||
live_action = socket.assigns.live_action
|
||||
|
||||
friend = Friend.get_by_slug(slug)
|
||||
editable = friend |> Friend.can_be_edited_by(socket.assigns[:current_user])
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:mode, :edit)
|
||||
|> assign_friend(friend)
|
||||
|> assign(:relationships, friend |> relations)
|
||||
|> assign(:live_action, live_action)
|
||||
|> assign(:search_query, nil)
|
||||
|> assign(:relation_id, nil)
|
||||
|> assign(:search_results, nil)
|
||||
|> assign(:editable, editable)
|
||||
|> title(friend.name <> " - " <> (live_action |> titlecase))
|
||||
|> push_navigate(
|
||||
to: Routes.friends_show_path(FriendsWeb.Endpoint, :relationships, friend.slug)
|
||||
)}
|
||||
end
|
||||
|
||||
# Timeline edit
|
||||
def handle_params(
|
||||
%{"slug" => slug} = _attrs,
|
||||
_url,
|
||||
%{assigns: %{live_action: :timeline}} = socket
|
||||
) do
|
||||
live_action = socket.assigns.live_action
|
||||
|
||||
friend = Friend.get_by_slug(slug)
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:mode, :edit)
|
||||
|> assign_friend(friend)
|
||||
|> assign(:live_action, live_action)
|
||||
|> assign(:search_query, nil)
|
||||
|> assign(:relation_id, nil)
|
||||
|> assign(:search_results, nil)
|
||||
|> title(friend.name <> " - " <> (live_action |> titlecase))}
|
||||
end
|
||||
|
||||
# Catch-all (aka, new friend form)
|
||||
def handle_params(_attrs, _token, socket) do
|
||||
friend = Friend.new()
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign_friend(friend)
|
||||
|> assign(:live_action, socket.assigns.live_action)
|
||||
|> assign(:address_query, nil)
|
||||
|> assign(:action, Routes.friends_path(socket, :update))
|
||||
|> title("Welcome")}
|
||||
end
|
||||
|
||||
# Validate overview form page
|
||||
def handle_event(
|
||||
"validate",
|
||||
%{"friend" => form_params},
|
||||
%{assigns: %{friend: friend, live_action: :overview}} = socket
|
||||
) do
|
||||
id = form_params["id"] |> parse_id
|
||||
name = form_params["name"]
|
||||
nickname = form_params["nickname"]
|
||||
born = form_params["born"]
|
||||
email = form_params["email"]
|
||||
phone = form_params["phone"] |> format_phone
|
||||
address_query = form_params["address_query"]
|
||||
address_latlon = form_params["address_latlon"]
|
||||
|
||||
new_params = %{
|
||||
id: id,
|
||||
name: name,
|
||||
nickname: nickname,
|
||||
slug: friend.slug,
|
||||
born: born,
|
||||
phone: phone,
|
||||
email: email
|
||||
}
|
||||
|
||||
changeset =
|
||||
%Friend{}
|
||||
|> Friend.changeset(new_params)
|
||||
|> Map.put(:action, :validate)
|
||||
|
||||
{
|
||||
:noreply,
|
||||
socket
|
||||
|> assign(:changeset, changeset)
|
||||
|> assign_friend(friend |> struct(new_params), changeset)
|
||||
|> assign(:address_query, address_query)
|
||||
|> assign(:address_latlon, address_latlon)
|
||||
}
|
||||
end
|
||||
|
||||
# Handle form saving
|
||||
def handle_event(
|
||||
"save",
|
||||
%{"friend" => form_params},
|
||||
%{assigns: %{changeset: _changeset}} = socket
|
||||
) do
|
||||
name = form_params["name"]
|
||||
nickname = form_params["nickname"]
|
||||
born = form_params["born"]
|
||||
email = form_params["email"]
|
||||
phone = form_params["phone"] |> format_phone
|
||||
slug = form_params["slug"] || name |> to_slug
|
||||
id = form_params["id"] || :new
|
||||
address_latlon = form_params["address_latlon"] |> Poison.decode!()
|
||||
address_query = form_params["search_query"]
|
||||
|
||||
address = %Friends.Places.Place{
|
||||
name: address_query,
|
||||
latlon: address_latlon
|
||||
}
|
||||
|
||||
new_address =
|
||||
case address.latlon do
|
||||
nil ->
|
||||
%{id: nil}
|
||||
|
||||
_ ->
|
||||
address
|
||||
|> Friends.Places.Place.get_or_create()
|
||||
end
|
||||
|
||||
new_params = %{
|
||||
id: id,
|
||||
name: name,
|
||||
nickname: nickname,
|
||||
slug: slug,
|
||||
born: born,
|
||||
phone: phone,
|
||||
email: email,
|
||||
address_id: new_address.id
|
||||
}
|
||||
|
||||
updated_friend = Friend.create_or_update(new_params)
|
||||
new_changeset = updated_friend |> Friend.changeset()
|
||||
|
||||
{
|
||||
:noreply,
|
||||
socket
|
||||
|> put_flash(:info, "Saved #{updated_friend |> first_name}!")
|
||||
|> assign(:new_friend, new_changeset)
|
||||
|> assign(:friend, updated_friend)
|
||||
|> push_navigate(to: "/friend/#{updated_friend.slug}")
|
||||
}
|
||||
end
|
||||
|
||||
def handle_event("address_search", %{"friend" => %{"search_query" => query}}, socket) do
|
||||
results = Places.Search.autocomplete(query) |> Enum.map(&Places.Search.parse_features/1)
|
||||
|
||||
if query == "" do
|
||||
{:noreply, socket |> assign(:search_results, nil)}
|
||||
else
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:search_results, results)
|
||||
|> assign(:search_query, query)
|
||||
|> assign(:select_fxn, "selectMapResult")}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event(_event, _unsigned_params, socket) do
|
||||
{:noreply, socket}
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,6 @@
|
||||
<section class="row">
|
||||
<article class="column prose">
|
||||
<%= edit_menu(assigns) %>
|
||||
<%= apply(FriendsWeb.LiveViews.Edit, @live_action, [assigns]) %>
|
||||
</article>
|
||||
</section>
|
||||
@@ -1,189 +1,23 @@
|
||||
defmodule FriendsWeb.FriendLive.Friend do
|
||||
defmodule FriendsWeb.FriendsLive.Friend do
|
||||
use FriendsWeb, :live_view
|
||||
use Phoenix.HTML
|
||||
import Helpers
|
||||
import Helpers.Names
|
||||
alias Friends.{Friend,Relationship}
|
||||
alias FriendsWeb.FriendLive.Components
|
||||
alias FriendsWeb.Router.Helpers, as: Routes
|
||||
|
||||
# Initialize variables on first load
|
||||
def mount(%{}, _token, socket) do
|
||||
{:ok, socket
|
||||
def mount(%{}, token, socket) do
|
||||
{:ok,
|
||||
socket
|
||||
|> title("New Friend")
|
||||
|> assign(:changeset, %Friend{} |> Friend.changeset)
|
||||
}
|
||||
end
|
||||
|
||||
# Show Friend
|
||||
def handle_params(%{"slug" => slug} = attrs, _token, socket) do
|
||||
friend = Friend.get_by_slug(slug)
|
||||
|
||||
page = if (attrs |> Map.get("page")) in ["overview", "calendar", "relationships"] do
|
||||
attrs["page"]
|
||||
else
|
||||
"overview"
|
||||
end
|
||||
|
||||
{:noreply, socket
|
||||
|> title(friend.name <> " - " <> (page |> :string.titlecase()))
|
||||
|> assign_friend(friend)
|
||||
|> page_view(page)
|
||||
|> assign(:action, Routes.friend_path(socket, :update, friend.id))
|
||||
}
|
||||
|> assign_current_user(token |> Map.get("user_token"))
|
||||
|> assign(:changeset, %Friend{} |> Friend.changeset())}
|
||||
end
|
||||
|
||||
# New Friend
|
||||
def handle_params(attrs, _token, socket) do
|
||||
friend = Friend.new
|
||||
{:noreply, socket
|
||||
|> title("New Friend")
|
||||
|> assign_friend(friend)
|
||||
|> page_view("overview")
|
||||
|> assign(:action,Routes.friend_path(socket, :create))
|
||||
}
|
||||
end
|
||||
|
||||
|
||||
# Handle form validation
|
||||
def handle_event("validate", %{"friend" => form_params}, %{assigns: %{friend: friend}} = socket) do
|
||||
|
||||
id = form_params["id"]
|
||||
name = form_params["name"]
|
||||
nickname = form_params["nickname"]
|
||||
born = form_params["born"]
|
||||
email = form_params["email"]
|
||||
phone = form_params["phone"] |> format_phone
|
||||
|
||||
new_params = %{
|
||||
id: id,
|
||||
name: name,
|
||||
nickname: nickname,
|
||||
slug: friend.slug,
|
||||
born: born,
|
||||
phone: phone,
|
||||
email: email
|
||||
}
|
||||
|
||||
changeset = %Friend{}
|
||||
|> Friend.changeset(new_params)
|
||||
|> Map.put(:action, :validate)
|
||||
|
||||
{
|
||||
:noreply, socket
|
||||
|> assign(:changeset, changeset)
|
||||
|> assign_friend(friend |> struct(new_params), changeset)
|
||||
}
|
||||
end
|
||||
|
||||
# Handle form saving
|
||||
def handle_event("save", %{"friend" => form_params},%{assigns: %{changeset: changeset}} = socket) do
|
||||
|
||||
name = form_params["name"]
|
||||
nickname = form_params["nickname"]
|
||||
born = form_params["born"]
|
||||
email = form_params["email"]
|
||||
phone = form_params["phone"] |> format_phone
|
||||
id = form_params["id"]
|
||||
|
||||
new_params = %{
|
||||
id: id,
|
||||
name: name,
|
||||
nickname: nickname,
|
||||
slug: name |> to_slug,
|
||||
born: born,
|
||||
phone: phone,
|
||||
email: email
|
||||
}
|
||||
|
||||
updated_friend = Friend.create_or_update(new_params)
|
||||
new_changeset = updated_friend |> Friend.changeset
|
||||
|
||||
{
|
||||
:noreply,
|
||||
socket
|
||||
|> put_flash(:info, "Saved #{updated_friend |> first_name}!")
|
||||
|> assign(:new_friend, new_changeset)
|
||||
|> assign(:friend, updated_friend)
|
||||
|> push_patch(to: "/friend/#{updated_friend.slug}")
|
||||
}
|
||||
end
|
||||
|
||||
# Handle deleting a friend
|
||||
def handle_event("delete", %{"friend_id" => friend_id}, socket) do
|
||||
|
||||
friend = Friend.get_by_id(friend_id)
|
||||
def handle_params(_attrs, _token, socket) do
|
||||
friend = Friend.new()
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> put_flash(:error, "Deleted '#{friend.name}'.")
|
||||
|> push_navigate(to: "/")
|
||||
}
|
||||
|
||||
|> title("New Friend")
|
||||
|> assign_friend(friend)
|
||||
|> assign(:action, Routes.friends_path(socket, :create))}
|
||||
end
|
||||
|
||||
# Set page title
|
||||
def title(socket, title) do
|
||||
socket |> assign(:page_title, title)
|
||||
end
|
||||
|
||||
# Set variables on page: friend, changeset, relationships
|
||||
def assign_friend(socket, friend) do
|
||||
socket
|
||||
|> assign(:friend, friend)
|
||||
|> assign(:changeset, friend |> Friend.changeset)
|
||||
|> assign(:relationships, friend.relationships)
|
||||
end
|
||||
|
||||
# Same thing, but this time we have a changeset we want to keep
|
||||
def assign_friend(socket, friend, changeset) do
|
||||
socket
|
||||
|> assign(:friend, friend)
|
||||
|> assign(:changeset, changeset)
|
||||
|> assign(:relationships, friend.relationships)
|
||||
end
|
||||
|
||||
# Set page_view variable
|
||||
def page_view(socket, page) do
|
||||
socket |> assign(:page_view, page)
|
||||
end
|
||||
|
||||
# Route to the right sub-template in Components/Components.ex
|
||||
def content(assigns) do
|
||||
~H"""
|
||||
<%= if @live_action != :new do %>
|
||||
<%= FriendsWeb.FriendLive.Friend.menu(assigns) %>
|
||||
<% end %>
|
||||
<%= cond do %>
|
||||
<% @live_action == :show -> %>
|
||||
<%= header(assigns) %>
|
||||
<%= @page_view |> Components.show_page(assigns) %>
|
||||
<% @live_action in [:edit, :new] -> %>
|
||||
<%= @page_view |> Components.form_page(assigns) %>
|
||||
<% end %>
|
||||
"""
|
||||
end
|
||||
|
||||
def header(assigns) do
|
||||
~H"""
|
||||
<div class="border-b-4 flex flex-row justify-between">
|
||||
<h1 class="mb-0 pl-2" style="height:48px; text-indent:5px"><%= @friend.name %></h1>
|
||||
</div>
|
||||
"""
|
||||
end
|
||||
|
||||
def menu(assigns) do
|
||||
~H"""
|
||||
<div class="hidden sm:tabs sm:mb-8">
|
||||
<%= for page <- ["overview", "calendar", "relationships"] do %>
|
||||
<% is_active = if(page == @page_view) do "tab-active" end %>
|
||||
<.link patch={"/friend/#{@friend.slug}?page=#{page}"} class={"font-bold sm:tab-lg flex-grow no-underline tab tab-lifted #{is_active}"}>
|
||||
<%= page |> :string.titlecase() %>
|
||||
</.link>
|
||||
<% end %>
|
||||
</div>
|
||||
|
||||
"""
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<section class="row">
|
||||
<article class="column prose">
|
||||
<FriendsWeb.FriendLive.Friend.content friend={@friend} page_view={@page_view} changeset={@changeset} action={@action} live_action={@live_action}/>
|
||||
<FriendsWeb.FriendsLive.Friend.content friend={@friend} page_view={@page_view} changeset={@changeset} action={@action} live_action={@live_action}/>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
defmodule FriendsWeb.FriendsLive do
|
||||
use FriendsWeb, :live_view
|
||||
|
||||
end
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
<section class="row md:flex md:flex-row justify-between">
|
||||
<article class="column prose p-4 w-full">
|
||||
<h2 class="text-l border-b-2">All Friends</h2>
|
||||
<ul class="text-xl ml-0 pl-0">
|
||||
<%= for friend <- @friends do %>
|
||||
<li class="w-full hover:bg-neutral hover:text-neutral-content rounded-xl list-none pl-0">
|
||||
<div class="flex justify-items-start p-4">
|
||||
<.link navigate={"/friend/#{friend.slug}"}><%= friend.name %></.link>
|
||||
<span class="px-4"><%= pluralize(friend |> relations |> length, "relation") %></span>
|
||||
</div>
|
||||
</li>
|
||||
<% end %>
|
||||
</ul>
|
||||
<div class="form-control flex flex-row my-8">
|
||||
<.link patch={"/friends/new"} class="btn btn-block md:btn-wide text-white">add friend</.link>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
@@ -0,0 +1,121 @@
|
||||
defmodule FriendsWeb.LiveViews.Edit do
|
||||
use FriendsWeb, :live_component
|
||||
|
||||
def welcome(assigns) do
|
||||
top = ~H"""
|
||||
<h1>Welcome!</h1>
|
||||
<p>Before we get started, we just need some basic info about you:</p>
|
||||
<%= overview(assigns) %>
|
||||
"""
|
||||
end
|
||||
|
||||
def overview(assigns) do
|
||||
~H"""
|
||||
<.form
|
||||
for={@changeset}
|
||||
let={f}
|
||||
action={@action}
|
||||
phx_change= "validate"
|
||||
phx_submit= "save"
|
||||
>
|
||||
<%= hidden_input f, :id, value: @friend.id %>
|
||||
<div class="border-b-4 flex flex-row">
|
||||
<%= text_input f, :name, placeholder: "Full Name",
|
||||
class: "m-0 p-0 pb-2 pl-2 input input-bordered border-dashed",
|
||||
style: "color: var(--tw-prose-headings);
|
||||
font-weight: 800;
|
||||
font-size: 2.25em;
|
||||
min-width: 50%;
|
||||
text-indent: 4px;
|
||||
line-height: 1.1111111;",
|
||||
value: @friend.name,
|
||||
phx_debounce: :blur %>
|
||||
<div class="min-w-fit flex place-items-center mx-4"><%= error_tag f, :name %></div>
|
||||
</div>
|
||||
|
||||
<Map.show address_latlon={@address_latlon} />
|
||||
<ul class="py-4 pl-0 h-1/2">
|
||||
<li class="flex flex-row gap-x-6">
|
||||
<strong class="md:text-xl w-20 md:w-28 shrink-0 text-right">Email:</strong>
|
||||
<div class="flex flex-col h-16">
|
||||
<%= text_input f, :email, class: "input input-primary input-sm md:input-md input-disabled", phx_debounce: "blur", value: @friend.email %>
|
||||
<div class="min-w-fit flex place-items-center mr-4"><%= error_tag f, :email %></div>
|
||||
</div>
|
||||
</li>
|
||||
<%= if @live_action != :welcome do %>
|
||||
<li class="flex flex-row gap-x-6 h-16">
|
||||
<strong class="md:text-xl w-20 md:w-28 shrink-0 text-right">Nickname:</strong>
|
||||
<div class=""><%= text_input f, :nickname, class: "input input-primary input-sm md:input-md", phx_debounce: "blur", value: @friend.nickname %></div>
|
||||
</li>
|
||||
<% end %>
|
||||
<li class="flex flex-row gap-x-6">
|
||||
<strong class="md:text-xl w-20 md:w-28 shrink-0 text-right">Birthday:</strong>
|
||||
<div class="flex flex-col h-16">
|
||||
<%= date_input f, :born, class: "input input-primary input-sm md:input-md", phx_debounce: "blur", value: @friend.born %>
|
||||
<div class="min-w-fit flex place-items-center mr-4"><%= error_tag f, :born %></div>
|
||||
</div>
|
||||
</li>
|
||||
<li class="flex flex-row gap-x-6">
|
||||
<strong class="md:text-xl w-20 md:w-28 shrink-0 text-right">Phone:</strong>
|
||||
<div class="flex flex-col h-16">
|
||||
<%= text_input f, :phone, class: "input input-primary input-sm md:input-md", phx_debounce: "blur", value: @friend.phone |> FriendsWeb.LiveHelpers.display_phone(@changeset) %>
|
||||
<div class="min-w-fit flex place-items-center mr-4"><%= error_tag f, :phone %></div>
|
||||
</div>
|
||||
</li>
|
||||
<li class="flex flex-row gap-x-6 relative">
|
||||
<strong class="md:text-xl w-20 md:w-28 shrink-0 text-right">Address:</strong>
|
||||
<div class="flex flex-col h-16">
|
||||
<%= text_input f, :search_query, value: @search_query,
|
||||
class: "input input-primary input-sm md:input-md",
|
||||
phx_debounce: "500",
|
||||
phx_change: :address_search,
|
||||
phx_click: JS.show(to: "#search-results"),
|
||||
phx_blur: JS.hide(to: "#search-results"),
|
||||
autocomplete: "name" %>
|
||||
<%= hidden_input f, :address_latlon, value: @address_latlon,
|
||||
id: "address-latlon", autocomplete: "latlon",
|
||||
phx_change: "validate"
|
||||
%>
|
||||
</div>
|
||||
<Autocomplete.search_results
|
||||
search_results={@search_results}
|
||||
search_query={@search_query}
|
||||
select_fxn="selectMapResult"
|
||||
/>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="form-control flex flex-row gap-x-4 md:justify-end mb-4 md:w-1/2">
|
||||
<%= if @live_action != :welcome do %>
|
||||
<div class="flex-1">
|
||||
<.link patch={Routes.friends_show_path(FriendsWeb.Endpoint, :overview, @friend.slug)} class="btn btn-block btn-outline">back</.link>
|
||||
</div>
|
||||
<% end %>
|
||||
<div class="flex-1">
|
||||
<%= if @changeset.valid? do %>
|
||||
<%= submit "Save", phx_disable_with: "Saving...", class: "btn btn-block" %>
|
||||
<% else %>
|
||||
<%= submit "Save", class: "btn btn-block btn-disabled" %>
|
||||
<% end %>
|
||||
</div>
|
||||
<%= if @live_action != :welcome and @current_user.profile.id == @friend.id do %>
|
||||
<div class="flex-1">
|
||||
<.link href={Routes.user_settings_path(FriendsWeb.Endpoint, :edit)} class="btn btn-block btn-error">Delete</.link>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
</.form>
|
||||
"""
|
||||
end
|
||||
|
||||
def relationships(assigns) do
|
||||
# Just for illustration; this will never run
|
||||
# as it's redirected via FriendsWeb.FriendsLive.Edit's
|
||||
# handle_params function
|
||||
FriendsWeb.LiveViews.Show.relationships(assigns)
|
||||
end
|
||||
|
||||
def timeline(assigns) do
|
||||
~H"""
|
||||
"""
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,115 @@
|
||||
defmodule FriendsWeb.LiveViews.Show do
|
||||
use FriendsWeb, :live_component
|
||||
alias FriendsWeb.Components.Cards
|
||||
|
||||
def main(assigns), do: overview(%{assigns | live_action: :overview})
|
||||
|
||||
def overview(assigns) do
|
||||
~H"""
|
||||
<%= if @address_latlon != "null" do %>
|
||||
<Map.show address_latlon={@address_latlon} />
|
||||
<% end %>
|
||||
<ul class="py-4 pl-0 md:text-xl h-1/2">
|
||||
<li class="flex flex-row mb-8 gap-6">
|
||||
<strong class="w-28 text-right">Nickname:</strong>
|
||||
<div class="">
|
||||
<%= if is_nil(@friend.nickname) do %>
|
||||
<span class="italic">none</span>
|
||||
<% else %>
|
||||
<%= @friend.nickname %>
|
||||
<% end %>
|
||||
</div>
|
||||
</li>
|
||||
<li class="flex flex-row mb-8 gap-6">
|
||||
<strong class="w-28 text-right">Birthday:</strong>
|
||||
<div class=""><%= @friend.born |> Calendar.strftime("%B %d, %Y") %>
|
||||
<br class="md:hidden"/>
|
||||
<span class="font-light">(<%= @friend |> Friend.age %> years old)</span>
|
||||
</div>
|
||||
</li>
|
||||
<li class="flex flex-row mb-8 gap-6">
|
||||
<strong class="w-28 text-right">Email:</strong>
|
||||
<div class=""><%= @friend.email %></div>
|
||||
</li>
|
||||
<li class="flex flex-row mb-8 gap-6">
|
||||
<strong class="w-28 text-right">Phone:</strong>
|
||||
<div class=""><%= @friend.phone %></div>
|
||||
</li>
|
||||
<li class="flex flex-row mb-8 gap-6">
|
||||
<strong class="w-28 text-right">Address:</strong>
|
||||
<%= if @address_latlon == "null" do %>
|
||||
<span class="italic">none</span>
|
||||
<% else %>
|
||||
<div class=""><%= @address %></div>
|
||||
<% end %>
|
||||
<input type="hidden" autocomplete="latlon" value={@address_latlon}/>
|
||||
</li>
|
||||
</ul>
|
||||
"""
|
||||
end
|
||||
|
||||
def relationships(assigns) do
|
||||
~H"""
|
||||
<div id="relationships" class="flex md:flex-row flex-col gap-8 p-8">
|
||||
<%= for relation <- @relationships do %>
|
||||
<% relationship = relation(@friend, relation) %>
|
||||
<Cards.relationship_card
|
||||
friend={@friend}
|
||||
relation={relation}
|
||||
relationship={relationship}
|
||||
editable={@editable}
|
||||
mode={@mode}
|
||||
/>
|
||||
<% end %>
|
||||
<%= if @relationships |> Enum.empty? do %>
|
||||
<div class="italic">No relationships on record yet.</div>
|
||||
<% end %>
|
||||
</div>
|
||||
<%= if @editable do %>
|
||||
<.form for={@changeset} let={f} class="border-t-4">
|
||||
<ul class="py-4 pl-0 h-1/2">
|
||||
<li class="flex flex-row gap-x-6 relative items-center">
|
||||
<strong class="md:text-xl basis-auto shrink-0 text-right">Type a name:</strong>
|
||||
<div class="flex flex-col relative">
|
||||
<%= text_input f, :search_query, value: @search_query,
|
||||
class: "input input-primary input-sm md:input-md",
|
||||
phx_debounce: "500",
|
||||
phx_change: :relation_search,
|
||||
phx_click: JS.show(to: "#search-results"),
|
||||
phx_blur: JS.hide(to: "#search-results"),
|
||||
autocomplete: "name" %>
|
||||
<%= hidden_input f, :relation_id, value: @relation_id,
|
||||
id: "relation-id", autocomplete: "relation-id",
|
||||
phx_change: "validate"
|
||||
%>
|
||||
<Autocomplete.search_results
|
||||
search_results={@search_results}
|
||||
search_query={@search_query}
|
||||
select_fxn="selectRelation"
|
||||
/>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</.form>
|
||||
<% end %>
|
||||
"""
|
||||
end
|
||||
|
||||
def timeline(assigns) do
|
||||
~H"""
|
||||
<div id="timeline" class="flex md:flex-row flex-col gap-8 p-8">
|
||||
<%= for event <- @friend |> Friends.Friend.get_events do %>
|
||||
<ul>
|
||||
<li>
|
||||
<b><%= event.name %></b> |
|
||||
<span><%= event.date |> format_date %></span>
|
||||
</li>
|
||||
</ul>
|
||||
<% end %>
|
||||
<%= if @friend |> Friends.Friend.get_events |> Enum.empty? do %>
|
||||
<div class="italic">No events on record yet.</div>
|
||||
<% end %>
|
||||
</div>
|
||||
"""
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,146 @@
|
||||
defmodule FriendsWeb.FriendsLive.Show do
|
||||
use FriendsWeb, :live_view
|
||||
|
||||
def mount(%{"slug" => slug}, token, socket) do
|
||||
live_action = socket.assigns.live_action || false
|
||||
|
||||
friend = Friend.get_by_slug(slug)
|
||||
editable = friend |> Friend.can_be_edited_by(socket.assigns[:current_user])
|
||||
|
||||
{latlon, address} = friend |> Friend.get_address()
|
||||
|
||||
if(live_action) do
|
||||
{:ok,
|
||||
socket
|
||||
|> assign(:mode, :show)
|
||||
|> assign(:live_action, live_action)
|
||||
|> assign_current_user(token |> Map.get("user_token"))
|
||||
|> assign(:friend, friend)
|
||||
|> assign(:address, address)
|
||||
|> assign(:address_latlon, latlon |> Poison.encode!())
|
||||
|> title(friend.name <> " - " <> (live_action |> titlecase))
|
||||
|> assign(:changeset, %Friend{} |> Friend.changeset())
|
||||
|> assign(:editable, editable)
|
||||
|> assign(:action, :moot)}
|
||||
else
|
||||
{:ok, socket |> redirect(to: Routes.friends_show_path(socket, :overview, friend.slug))}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_params(
|
||||
%{"slug" => slug},
|
||||
_url,
|
||||
%{assigns: %{live_action: :overview}} = socket
|
||||
) do
|
||||
friend = Friend.get_by_slug(slug)
|
||||
live_action = socket.assigns.live_action
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:mode, :show)
|
||||
|> title(friend.name <> " - " <> (live_action |> titlecase))
|
||||
|> assign_friend(friend)}
|
||||
end
|
||||
|
||||
def handle_params(
|
||||
%{"slug" => slug} = params,
|
||||
url,
|
||||
%{assigns: %{live_action: :relationships}} = socket
|
||||
) do
|
||||
live_action = socket.assigns.live_action
|
||||
|
||||
friend = Friend.get_by_slug(slug)
|
||||
editable = friend |> Friend.can_be_edited_by(socket.assigns[:current_user])
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:mode, :edit)
|
||||
|> assign_friend(friend)
|
||||
|> assign(:relationships, friend |> relations)
|
||||
|> assign(:live_action, live_action)
|
||||
|> assign(:search_query, nil)
|
||||
|> assign(:relation_id, nil)
|
||||
|> assign(:search_results, nil)
|
||||
|> assign(:editable, editable)
|
||||
|> title(friend.name <> " - " <> (live_action |> titlecase))}
|
||||
end
|
||||
|
||||
def handle_event(
|
||||
"relation_search",
|
||||
%{"friend" => %{"search_query" => query}},
|
||||
%{assigns: %{friend: friend}} = socket
|
||||
) do
|
||||
if query == "" do
|
||||
{:noreply, socket |> assign(:search_results, nil)}
|
||||
else
|
||||
results =
|
||||
(Friend.Search.autocomplete(query, friend) ++
|
||||
[Friend.new(%{name: query})])
|
||||
|> Enum.map(&Friend.Search.parse_result/1)
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:search_results, results)
|
||||
|> assign(:search_query, query)
|
||||
|> assign(:select_fxn, "selectRelation")}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event(
|
||||
"phx:select_relation",
|
||||
%{"id" => rel_id, "name" => rel_name},
|
||||
%{assigns: %{friend: friend, relationships: relationships}} = socket
|
||||
) do
|
||||
new_rel =
|
||||
case rel_id do
|
||||
"new" -> Friend.create(%{name: rel_name})
|
||||
_num -> Friend.get_by_id(rel_id |> String.to_integer())
|
||||
end
|
||||
|
||||
[updated_friend, updated_relation] = friend |> Friend.create_relationship(new_rel)
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign_friend(updated_friend)
|
||||
|> assign(:relationships, updated_friend |> relations)}
|
||||
end
|
||||
|
||||
def handle_event(
|
||||
"phx:delete_relation",
|
||||
%{"id" => rel_id},
|
||||
%{assigns: %{friend: friend, relationships: relationships}} = socket
|
||||
) do
|
||||
rel = Relationship.get_by_id(rel_id)
|
||||
|
||||
IO.inspect("Deleting #{rel.id}")
|
||||
|
||||
rel |> Relationship.delete()
|
||||
|
||||
updated_friend = Friend.get_by_id(friend.id)
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign_friend(updated_friend)
|
||||
|> assign(:relationships, updated_friend |> relations)}
|
||||
end
|
||||
|
||||
def handle_event(
|
||||
"phx:relation_type",
|
||||
%{"rel_id" => rel_id, "type" => type},
|
||||
%{assigns: %{friend: friend, relationships: relationships}} = socket
|
||||
) do
|
||||
rel = Relationship.get_by_id(rel_id)
|
||||
|
||||
IO.inspect("Changing type of relationship #{rel.id} to #{type}")
|
||||
|
||||
rel |> Relationship.change_type(type |> Relationship.type_index())
|
||||
|
||||
updated_friend = Friend.get_by_id(friend.id)
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign_friend(updated_friend)
|
||||
|> assign(:relationships, updated_friend |> relations)
|
||||
|> push_navigate(to: Routes.friends_show_path(socket, :relationships, friend.slug))}
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,13 @@
|
||||
<section class="row">
|
||||
<article class="column prose">
|
||||
<%= menu(assigns) %>
|
||||
<%= header(assigns) %>
|
||||
<%= apply(FriendsWeb.LiveViews.Show, @live_action, [assigns]) %>
|
||||
|
||||
<%= if @editable and @mode != :edit do %>
|
||||
<div class="form-control flex flex-row mb-4">
|
||||
<.link navigate={Routes.friends_edit_path(FriendsWeb.Endpoint, @live_action, @friend.slug)} class="btn btn-block md:btn-wide text-white"><%=@live_action |> get_edit_text%></.link>
|
||||
</div>
|
||||
<% end %>
|
||||
</article>
|
||||
</section>
|
||||
@@ -1,6 +1,8 @@
|
||||
defmodule FriendsWeb.Router do
|
||||
use FriendsWeb, :router
|
||||
|
||||
import FriendsWeb.UserAuth
|
||||
|
||||
pipeline :browser do
|
||||
plug :accepts, ["html"]
|
||||
plug :fetch_session
|
||||
@@ -8,20 +10,13 @@ defmodule FriendsWeb.Router do
|
||||
plug :put_root_layout, {FriendsWeb.LayoutView, :root}
|
||||
plug :protect_from_forgery
|
||||
plug :put_secure_browser_headers
|
||||
plug :fetch_current_user
|
||||
end
|
||||
|
||||
pipeline :api do
|
||||
plug :accepts, ["json"]
|
||||
end
|
||||
|
||||
scope "/", FriendsWeb.FriendsLive do
|
||||
pipe_through :browser
|
||||
|
||||
live "/", Index
|
||||
live "/friend/:slug", FriendsLive.Show
|
||||
|
||||
end
|
||||
|
||||
# Other scopes may use custom stacks.
|
||||
# scope "/api", FriendsWeb do
|
||||
# pipe_through :api
|
||||
@@ -55,4 +50,82 @@ defmodule FriendsWeb.Router do
|
||||
forward "/mailbox", Plug.Swoosh.MailboxPreview
|
||||
end
|
||||
end
|
||||
|
||||
## Authentication routes
|
||||
# Routes that only work if user not authenticated
|
||||
scope "/users", FriendsWeb do
|
||||
pipe_through [:browser, :redirect_if_user_is_authenticated]
|
||||
get "/register", UserRegistrationController, :new
|
||||
post "/register", UserRegistrationController, :create
|
||||
get "/log_in", UserSessionController, :new
|
||||
post "/log_in", UserSessionController, :create
|
||||
get "/reset_password", UserResetPasswordController, :new
|
||||
post "/reset_password", UserResetPasswordController, :create
|
||||
get "/reset_password/:token", UserResetPasswordController, :edit
|
||||
put "/reset_password/:token", UserResetPasswordController, :update
|
||||
end
|
||||
|
||||
# Confirmation and logout
|
||||
scope "/users", FriendsWeb do
|
||||
pipe_through [:browser]
|
||||
delete "/log_out", UserSessionController, :delete
|
||||
get "/confirm", UserConfirmationController, :new
|
||||
post "/confirm", UserConfirmationController, :create
|
||||
get "/confirm/:token", UserConfirmationController, :edit
|
||||
post "/confirm/:token", UserConfirmationController, :update
|
||||
|
||||
live "/welcome", FriendsLive.Edit, :welcome
|
||||
end
|
||||
|
||||
# Routes that require the user be authenticated:
|
||||
scope "/users/settings", FriendsWeb do
|
||||
pipe_through [:browser, :require_authenticated_user]
|
||||
get "/", UserSettingsController, :edit
|
||||
put "/", UserSettingsController, :update
|
||||
get "/confirm_email/:token", UserSettingsController, :confirm_email
|
||||
end
|
||||
|
||||
# THE ACTUAL GUTS OF THE APP
|
||||
scope "/", FriendsWeb do
|
||||
pipe_through [:browser, :capture_profile]
|
||||
get "/", PageController, :index
|
||||
end
|
||||
|
||||
# View-only modes (don't require being logged in and having a profile)
|
||||
scope "/friends", FriendsWeb do
|
||||
pipe_through [:browser]
|
||||
get "/", FriendsController, :index
|
||||
end
|
||||
|
||||
scope "/friend", FriendsWeb do
|
||||
pipe_through [:browser]
|
||||
live "/:slug", FriendsLive.Show
|
||||
live "/:slug/overview", FriendsLive.Show, :overview
|
||||
live "/:slug/timeline", FriendsLive.Show, :timeline
|
||||
live "/:slug/relationships", FriendsLive.Show, :relationships
|
||||
end
|
||||
|
||||
scope "/relationship", FriendsWeb do
|
||||
pipe_through [:browser]
|
||||
live "/:slug1/:slug2", RelationshipLive.Show, :overview
|
||||
end
|
||||
|
||||
# Edit modes (require being logged in and having a profile)
|
||||
scope "/edit/", FriendsWeb do
|
||||
pipe_through [:browser, :require_authenticated_user, :capture_profile]
|
||||
|
||||
post "/", FriendsController, :update
|
||||
|
||||
live "/:slug", FriendsLive.Edit
|
||||
live "/:slug/overview", FriendsLive.Edit, :overview
|
||||
live "/:slug/timeline", FriendsLive.Edit, :timeline
|
||||
live "/:slug/relationships", FriendsLive.Edit, :relationships
|
||||
end
|
||||
|
||||
# API
|
||||
scope "/api", FriendsWeb do
|
||||
pipe_through :api
|
||||
|
||||
delete "/relationship/:id", RelationshipsController, :delete
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
<h1>All Friends</h1>
|
||||
|
||||
<ul class="text-xl">
|
||||
<%= for f <- @all_friends do %>
|
||||
<li>
|
||||
<.link href={Routes.friends_show_path(@conn, :overview, f.slug)}><%= f.name %></.link>
|
||||
<%= if @current_user do %>
|
||||
<%= if f.id == @current_user.profile.id do %>
|
||||
(you)
|
||||
<% end %><% end %>
|
||||
</li>
|
||||
<% end %>
|
||||
</ul>
|
||||
|
||||
<%= if @current_user do %>
|
||||
<div class="m-4 mt-16">
|
||||
<.link href={Routes.friends_edit_path(@conn, :overview, :new)}>Add Friend</.link>
|
||||
</div>
|
||||
<% end %>
|
||||
@@ -0,0 +1,16 @@
|
||||
<%= if @current_user do %>
|
||||
<label tabindex="0" class="btn btn-ghost btn-circle avatar">
|
||||
<div class="w-10 rounded-full">
|
||||
<img src="https://placeimg.com/80/80/people" />
|
||||
</div>
|
||||
</label>
|
||||
<ul class="mt-3 p-2 shadow menu menu-compact dropdown-content bg-base-100 text-neutral rounded-box w-52">
|
||||
<li><%= @current_user.email %></li>
|
||||
<li><%= link "Settings", to: Routes.user_settings_path(@conn, :edit) %></li>
|
||||
<li><%= link "Log out", to: Routes.user_session_path(@conn, :delete), method: :delete %></li>
|
||||
</ul>
|
||||
<% else %>
|
||||
<%= link "Log in", to: Routes.user_session_path(@conn, :new), class: "btn" %>
|
||||
<%= link "Register", to: Routes.user_registration_path(@conn, :new), class: "btn btn-primary" %>
|
||||
<% end %>
|
||||
|
||||
@@ -1,5 +1,28 @@
|
||||
<main class="container">
|
||||
<div id="navbar" class="sticky top-0 z-40 bg-neutral text-neutral-content border-b-4 border-primary">
|
||||
<div class="lg:w-2/3 lg:mx-auto navbar">
|
||||
<div class="flex-1">
|
||||
<.link navigate={"/"} class="btn btn-ghost normal-case text-xl">Friends</.link>
|
||||
</div>
|
||||
<div class="dropdown dropdown-end">
|
||||
<%= render("_user_menu.html", conn: @conn, current_user: @current_user) %>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mx-auto w-full lg:w-3/4">
|
||||
<main class="container p-4 mb-10 md:p-8 prose">
|
||||
<p class="alert alert-info" role="alert"><%= get_flash(@conn, :info) %></p>
|
||||
<p class="alert alert-danger" role="alert"><%= get_flash(@conn, :error) %></p>
|
||||
<%= @inner_content %>
|
||||
</main>
|
||||
</main>
|
||||
</div>
|
||||
<div class="md:hidden btm-nav">
|
||||
<button class="text-neutral active">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" /></svg>
|
||||
</button>
|
||||
<button class="text-neutral">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
|
||||
</button>
|
||||
<button class="text-neutral">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" /></svg>
|
||||
</button>
|
||||
</div>
|
||||
@@ -3,27 +3,8 @@
|
||||
<div class="flex-1">
|
||||
<.link navigate={"/"} class="btn btn-ghost normal-case text-xl">Friends</.link>
|
||||
</div>
|
||||
<div class="flex-none gap-2">
|
||||
<div class="form-control hidden md:block">
|
||||
<input type="text" placeholder="Search" class="input input-bordered" />
|
||||
</div>
|
||||
<div class="dropdown dropdown-end">
|
||||
<label tabindex="0" class="btn btn-ghost btn-circle avatar">
|
||||
<div class="w-10 rounded-full">
|
||||
<img src="https://placeimg.com/80/80/people" />
|
||||
</div>
|
||||
</label>
|
||||
<ul tabindex="0" class="mt-3 p-2 shadow menu menu-compact dropdown-content bg-base-100 rounded-box w-52">
|
||||
<li>
|
||||
<a>
|
||||
Profile
|
||||
</a>
|
||||
</li>
|
||||
<li class="md:hidden"><a>Search</a></li>
|
||||
<li><a>Settings</a></li>
|
||||
<li><a>Logout</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<%= render("_user_menu.html", conn: @socket, current_user: @current_user) %>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-theme="pastel">
|
||||
<html lang="en" data-theme="cupcake"> <!-- pastel -->
|
||||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<div class="flex flex-col flex-col gap-2 items-center md:flex-row md:justify-center md:items-start">
|
||||
<div id="hero" class="prose md:w-1/2 md:pr-8 md:place-self-center">
|
||||
<h1>
|
||||
Friends App
|
||||
</h1>
|
||||
<p class="mb-6">
|
||||
<i>Friends</i> helps us remember the important
|
||||
dates in your life, keep track of any big life changes,
|
||||
and basically go back to the 2011 Facebook we all miss.
|
||||
</p>
|
||||
<div class="hidden md:block">
|
||||
<.friends_list friends={@friends} />
|
||||
</div>
|
||||
</div>
|
||||
<div id="sign-up" class="prose card md:w-fit bg-neutral-content text-neutral shadow-xl items-center">
|
||||
<div class="card-body">
|
||||
<h1 class="card-title border-b-2">
|
||||
Sign Up
|
||||
</h1>
|
||||
<.sign_up new_friend={@new_friend} />
|
||||
</div>
|
||||
</div>
|
||||
<div id="friends" class="prose w-full mb-8 md:hidden">
|
||||
<.friends_list friends={@friends} />
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,25 @@
|
||||
defmodule FriendsWeb.ProfileLive.Form do
|
||||
use FriendsWeb, :live_view
|
||||
import FriendsWeb.LiveHelpers
|
||||
|
||||
def mount(%{}, %{"user_token" => token}, socket) do
|
||||
{:ok,
|
||||
socket
|
||||
|> assign_current_user(token)
|
||||
|> title("Create a profile")}
|
||||
end
|
||||
|
||||
def show_form(%{step: 1} = assigns) do
|
||||
# First things first, are we linking to an existing user or no?
|
||||
|
||||
~H"""
|
||||
<b>Your email:</b> <%= @current_user.email %>
|
||||
"""
|
||||
end
|
||||
|
||||
def show_form(%{step: 2} = assigns) do
|
||||
~H"""
|
||||
Step 2
|
||||
"""
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,9 @@
|
||||
<div class="prose">
|
||||
<h1>Welcome!</h1>
|
||||
<p>You have made a user account, but we don't yet have a profile for you.</p>
|
||||
|
||||
<div id="profile-form">
|
||||
<.show_form step={1} current_user={@current_user} />
|
||||
</div>
|
||||
|
||||
</div>
|
||||
@@ -0,0 +1,12 @@
|
||||
<h1>Confirm account</h1>
|
||||
|
||||
<.form let={_f} for={:user} action={Routes.user_confirmation_path(@conn, :update, @token)}>
|
||||
<div>
|
||||
<%= submit "Confirm my account" %>
|
||||
</div>
|
||||
</.form>
|
||||
|
||||
<p>
|
||||
<%= link "Register", to: Routes.user_registration_path(@conn, :new) %> |
|
||||
<%= link "Log in", to: Routes.user_session_path(@conn, :new) %>
|
||||
</p>
|
||||
@@ -0,0 +1,15 @@
|
||||
<h1>Resend confirmation instructions</h1>
|
||||
|
||||
<.form let={f} for={:user} action={Routes.user_confirmation_path(@conn, :create)}>
|
||||
<%= label f, :email %>
|
||||
<%= email_input f, :email, required: true %>
|
||||
|
||||
<div>
|
||||
<%= submit "Resend confirmation instructions" %>
|
||||
</div>
|
||||
</.form>
|
||||
|
||||
<p>
|
||||
<%= link "Register", to: Routes.user_registration_path(@conn, :new) %> |
|
||||
<%= link "Log in", to: Routes.user_session_path(@conn, :new) %>
|
||||
</p>
|
||||
@@ -0,0 +1,30 @@
|
||||
<h1>Register</h1>
|
||||
|
||||
<.form let={f} for={@changeset} action={Routes.user_registration_path(@conn, :create)}>
|
||||
<%= if @changeset.action do %>
|
||||
<div class="alert alert-danger">
|
||||
Oops, something went wrong! Please check the errors below.
|
||||
</div>
|
||||
<% end %>
|
||||
<ul class="w-1/2 pl-0 flex flex-col gap-6">
|
||||
<li class="flex flex-row gap-4">
|
||||
<%= label f, :email, class: "w-1/3" %>
|
||||
<%= email_input f, :email, required: true %>
|
||||
<%= error_tag f, :email %>
|
||||
</li>
|
||||
<li class="flex flex-row gap-4">
|
||||
<%= label f, :password, class: "w-1/3" %>
|
||||
<%= password_input f, :password, required: true %>
|
||||
<%= error_tag f, :password %>
|
||||
</li>
|
||||
<li class="flex">
|
||||
<%= submit "Register", class: "btn btn-primary" %>
|
||||
</li>
|
||||
</ul>
|
||||
</.form>
|
||||
|
||||
|
||||
<p>
|
||||
<%= link "Log in", to: Routes.user_session_path(@conn, :new) %> |
|
||||
<%= link "Forgot your password?", to: Routes.user_reset_password_path(@conn, :new) %>
|
||||
</p>
|
||||
@@ -0,0 +1,26 @@
|
||||
<h1>Reset password</h1>
|
||||
|
||||
<.form let={f} for={@changeset} action={Routes.user_reset_password_path(@conn, :update, @token)}>
|
||||
<%= if @changeset.action do %>
|
||||
<div class="alert alert-danger">
|
||||
<p>Oops, something went wrong! Please check the errors below.</p>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
<%= label f, :password, "New password" %>
|
||||
<%= password_input f, :password, required: true %>
|
||||
<%= error_tag f, :password %>
|
||||
|
||||
<%= label f, :password_confirmation, "Confirm new password" %>
|
||||
<%= password_input f, :password_confirmation, required: true %>
|
||||
<%= error_tag f, :password_confirmation %>
|
||||
|
||||
<div>
|
||||
<%= submit "Reset password" %>
|
||||
</div>
|
||||
</.form>
|
||||
|
||||
<p>
|
||||
<%= link "Register", to: Routes.user_registration_path(@conn, :new) %> |
|
||||
<%= link "Log in", to: Routes.user_session_path(@conn, :new) %>
|
||||
</p>
|
||||
@@ -0,0 +1,15 @@
|
||||
<h1>Forgot your password?</h1>
|
||||
|
||||
<.form let={f} for={:user} action={Routes.user_reset_password_path(@conn, :create)}>
|
||||
<%= label f, :email %>
|
||||
<%= email_input f, :email, required: true %>
|
||||
|
||||
<div>
|
||||
<%= submit "Send instructions to reset password" %>
|
||||
</div>
|
||||
</.form>
|
||||
|
||||
<p>
|
||||
<%= link "Register", to: Routes.user_registration_path(@conn, :new) %> |
|
||||
<%= link "Log in", to: Routes.user_session_path(@conn, :new) %>
|
||||
</p>
|
||||
@@ -0,0 +1,31 @@
|
||||
<h1>Log in</h1>
|
||||
|
||||
<.form let={f} for={@conn} action={Routes.user_session_path(@conn, :create)} as={:user}>
|
||||
<%= if @error_message do %>
|
||||
<div class="alert alert-danger">
|
||||
<p><%= @error_message %></p>
|
||||
</div>
|
||||
<% end %>
|
||||
<ul class="w-1/2 pl-0 flex flex-col gap-6">
|
||||
<li class="flex flex-row gap-4">
|
||||
<%= label f, :email, class: "w-1/3" %>
|
||||
<%= email_input f, :email, required: true %>
|
||||
</li>
|
||||
<li class="flex flex-row gap-4">
|
||||
<%= label f, :password, class: "w-1/3" %>
|
||||
<%= password_input f, :password, required: true %>
|
||||
</li>
|
||||
<li class="flex flex-row gap-4">
|
||||
<%= label f, :remember_me, "Keep me logged in for 60 days", class: "w-fit" %>
|
||||
<%= checkbox f, :remember_me %>
|
||||
</li>
|
||||
<li class="flex">
|
||||
<%= submit "Log in", class: "btn btn-primary" %>
|
||||
</li>
|
||||
</ul>
|
||||
</.form>
|
||||
|
||||
<p>
|
||||
<%= link "Register", to: Routes.user_registration_path(@conn, :new) %> |
|
||||
<%= link "Forgot your password?", to: Routes.user_reset_password_path(@conn, :new) %>
|
||||
</p>
|
||||
@@ -0,0 +1,78 @@
|
||||
<h1>Settings</h1>
|
||||
|
||||
<div class="flex gap-16 flex-col md:flex-row justify-evenly">
|
||||
<.form
|
||||
let={f}
|
||||
for={@email_changeset}
|
||||
action={Routes.user_settings_path(@conn, :update)}
|
||||
id="update_email"
|
||||
class="w-max"
|
||||
>
|
||||
<%= if @email_changeset.action do %>
|
||||
<div class="alert alert-danger">
|
||||
<p>Oops, something went wrong! Please check the errors below.</p>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
<%= hidden_input f, :action, name: "action", value: "update_email" %>
|
||||
|
||||
|
||||
<h3>Change email</h3>
|
||||
<ul class="w-full pl-0 flex flex-col gap-6">
|
||||
|
||||
<li class="flex flex-row gap-4">
|
||||
<%= label f, :email, class: "w-1/3" %>
|
||||
<%= email_input f, :email, required: true %>
|
||||
<%= error_tag f, :email %>
|
||||
</li>
|
||||
<li class="flex flex-row gap-4">
|
||||
<%= label f, :current_password, for: "current_password_for_email", class: "w-1/3" %>
|
||||
<%= password_input f, :password, required: true %>
|
||||
<%= error_tag f, :current_password %>
|
||||
</li>
|
||||
<li class="flex place-self-stretch">
|
||||
<%= submit "Change email", class: "btn btn-primary" %>
|
||||
</li>
|
||||
</ul>
|
||||
</.form>
|
||||
|
||||
<.form
|
||||
let={f}
|
||||
for={@password_changeset}
|
||||
action={Routes.user_settings_path(@conn, :update)}
|
||||
id="update_password"
|
||||
class="w-max"
|
||||
>
|
||||
|
||||
<h3>Change password</h3>
|
||||
|
||||
<ul class="w-full pl-0 flex flex-col gap-6 md:h-full">
|
||||
<%= if @password_changeset.action do %>
|
||||
<div class="alert alert-danger">
|
||||
<p>Oops, something went wrong! Please check the errors below.</p>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
<%= hidden_input f, :action, name: "action", value: "update_password" %>
|
||||
|
||||
<li class="flex flex-row gap-4">
|
||||
<%= label f, :current_password, for: "current_password_for_password", class: "w-1/3" %>
|
||||
<%= password_input f, :current_password, required: true, name: "current_password", id: "current_password_for_password" %>
|
||||
<%= error_tag f, :current_password %>
|
||||
</li>
|
||||
<li class="flex flex-row gap-4">
|
||||
<%= label f, :password, "New password", class: "w-1/3" %>
|
||||
<%= password_input f, :password, required: true, class: "shrink-0" %>
|
||||
<%= error_tag f, :password %>
|
||||
</li>
|
||||
<li class="flex flex-row gap-4">
|
||||
<%= label f, :password_confirmation, "Confirm new password", class: "w-1/3" %>
|
||||
<%= password_input f, :password_confirmation, required: true %>
|
||||
<%= error_tag f, :password_confirmation %>
|
||||
</li>
|
||||
<li class="flex">
|
||||
<%= submit "Change password", class: "btn btn-primary" %>
|
||||
</li>
|
||||
</ul>
|
||||
</.form>
|
||||
</div>
|
||||
@@ -10,10 +10,8 @@ defmodule FriendsWeb.ErrorHelpers do
|
||||
"""
|
||||
def error_tag(form, field) do
|
||||
Enum.map(Keyword.get_values(form.errors, field), fn error ->
|
||||
content_tag(:span, translate_error(error),
|
||||
class: "invalid-feedback",
|
||||
phx_feedback_for: input_name(form, field)
|
||||
)
|
||||
field = field |> Atom.to_string() |> String.capitalize()
|
||||
content_tag(:span, "#{translate_error(error)}", class: "block mt-1 text-sm text-red-700")
|
||||
end)
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
defmodule FriendsWeb.FriendsView do
|
||||
use FriendsWeb, :view
|
||||
import Phoenix.Component
|
||||
import Helpers
|
||||
end
|
||||
@@ -0,0 +1,97 @@
|
||||
defmodule FriendsWeb.LiveHelpers do
|
||||
alias Friends.Friend
|
||||
use Phoenix.LiveComponent
|
||||
|
||||
def titlecase(atom) do
|
||||
atom |> to_string |> :string.titlecase()
|
||||
end
|
||||
|
||||
def parse_id("new"), do: "new"
|
||||
def parse_id(int), do: int |> String.to_integer()
|
||||
|
||||
def display_phone(phone, changeset) do
|
||||
if changeset.errors[:phone] do
|
||||
phone
|
||||
else
|
||||
display_phone(phone)
|
||||
end
|
||||
end
|
||||
|
||||
def display_phone(phone) do
|
||||
"""
|
||||
TODO: Actually implement this
|
||||
"""
|
||||
|
||||
has_plus = phone |> String.starts_with?("+")
|
||||
|
||||
case phone |> String.length() do
|
||||
10 ->
|
||||
country = "+1 "
|
||||
|
||||
[area, first, sec1, sec2] =
|
||||
phone |> to_charlist |> Enum.chunk_every(3) |> Enum.map(&(&1 |> to_string))
|
||||
|
||||
"#{country}(#{area}) #{first}-#{sec1}#{sec2}"
|
||||
|
||||
11 when has_plus ->
|
||||
phone
|
||||
|
||||
12 when has_plus ->
|
||||
phone
|
||||
end
|
||||
end
|
||||
|
||||
def get_edit_text(live_action) do
|
||||
case live_action do
|
||||
:timeline -> "add a moment"
|
||||
:relationships -> "add a relationship"
|
||||
_ -> "edit"
|
||||
end
|
||||
end
|
||||
|
||||
def format_date(date) do
|
||||
date
|
||||
|> Calendar.strftime("%b %d, %Y")
|
||||
end
|
||||
|
||||
def assign_current_user(socket, user_token) do
|
||||
user =
|
||||
case user_token do
|
||||
nil ->
|
||||
nil
|
||||
|
||||
_moot ->
|
||||
user_token
|
||||
|> Friends.Accounts.get_user_by_session_token()
|
||||
|> Friends.Repo.preload(:profile)
|
||||
end
|
||||
|
||||
socket
|
||||
|> assign(
|
||||
:current_user,
|
||||
user
|
||||
)
|
||||
end
|
||||
|
||||
# Set page title variable
|
||||
def title(socket, title) do
|
||||
socket
|
||||
|> assign(:page_title, title)
|
||||
end
|
||||
|
||||
# Set variables on page: friend, changeset, relationships
|
||||
def assign_friend(socket, friend) do
|
||||
socket
|
||||
|> assign(:friend, friend)
|
||||
|> assign(:editable, friend |> Friend.can_be_edited_by(socket.assigns[:current_user]))
|
||||
|> assign(:changeset, friend |> Friend.changeset())
|
||||
end
|
||||
|
||||
# Same thing, but this time we have a changeset we want to keep
|
||||
def assign_friend(socket, friend, changeset) do
|
||||
socket
|
||||
|> assign(:friend, friend)
|
||||
|> assign(:editable, friend |> Friend.can_be_edited_by(socket.assigns[:current_user]))
|
||||
|> assign(:changeset, changeset)
|
||||
end
|
||||
end
|
||||
@@ -1,3 +1,30 @@
|
||||
defmodule FriendsWeb.PageView do
|
||||
use FriendsWeb, :view
|
||||
import Phoenix.Component
|
||||
import Helpers
|
||||
|
||||
alias FriendsWeb.Components.SignUp, as: SignUp
|
||||
|
||||
def sign_up(assigns), do: SignUp.sign_up_form(assigns)
|
||||
|
||||
def friends_list(assigns) do
|
||||
~H"""
|
||||
<h3 class="mt-12 border-b-2">
|
||||
All Friends
|
||||
</h3>
|
||||
<ul>
|
||||
<%= for friend <- @friends do %>
|
||||
<li>
|
||||
<div id={"friend-#{friend.id}"} class="">
|
||||
<div class="">
|
||||
<h3 class="">
|
||||
<.link href={Routes.live_path(FriendsWeb.Endpoint, FriendsWeb.FriendsLive.Show, friend.slug)}><%= friend.name %></.link>
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
<% end %>
|
||||
</ul>
|
||||
"""
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
defmodule FriendsWeb.UserConfirmationView do
|
||||
use FriendsWeb, :view
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
defmodule UserProfileView do
|
||||
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
defmodule FriendsWeb.UserRegistrationView do
|
||||
use FriendsWeb, :view
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
defmodule FriendsWeb.UserResetPasswordView do
|
||||
use FriendsWeb, :view
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
defmodule FriendsWeb.UserSessionView do
|
||||
use FriendsWeb, :view
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
defmodule FriendsWeb.UserSettingsView do
|
||||
use FriendsWeb, :view
|
||||
end
|
||||
@@ -1,6 +1,4 @@
|
||||
defmodule Helpers do
|
||||
import Helpers.Names
|
||||
|
||||
def do!(thing) do
|
||||
case thing do
|
||||
{:ok, answer} -> answer
|
||||
@@ -8,28 +6,39 @@ defmodule Helpers do
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
def pluralize(qty, word) do
|
||||
plural = if qty == 1 do
|
||||
plural =
|
||||
if qty == 1 do
|
||||
"#{word}"
|
||||
else
|
||||
"#{word}s"
|
||||
end
|
||||
|
||||
"#{qty} #{plural}"
|
||||
end
|
||||
|
||||
def parse_date(str), do: str |> to_string |> Timex.parse("%Y-%m-%d", :strftime)
|
||||
|
||||
def valid_phone() do
|
||||
Regex.compile!("^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$")
|
||||
end
|
||||
|
||||
def format_phone(str) do
|
||||
str
|
||||
|> String.replace(" ", "") |> String.replace("-", "") |> String.replace(".", "")
|
||||
|> String.replace(" ", "")
|
||||
|> String.replace("-", "")
|
||||
|> String.replace(".", "")
|
||||
|> String.replace(~r/[\(\)]/, "")
|
||||
end
|
||||
|
||||
def to_slug(nil), do: nil
|
||||
|
||||
def to_slug(name) when is_binary(name) do
|
||||
name
|
||||
|> String.replace(" ", "-")
|
||||
|> String.downcase()
|
||||
end
|
||||
|
||||
def to_slug(obj), do: to_slug(obj.name)
|
||||
|
||||
def from_slug(name) do
|
||||
@@ -41,17 +50,20 @@ defmodule Helpers do
|
||||
end
|
||||
|
||||
def birthday(friend) do
|
||||
this_year = (Date.utc_today
|
||||
this_year =
|
||||
Date.utc_today()
|
||||
|> Calendar.strftime("%Y")
|
||||
|> String.to_integer)
|
||||
|> String.to_integer()
|
||||
|
||||
next_birthday = friend.born
|
||||
next_birthday =
|
||||
friend.born
|
||||
|> Calendar.strftime("%m-%d")
|
||||
|
||||
next_birthdate = "#{this_year}-#{next_birthday}"
|
||||
next_birthdate =
|
||||
"#{this_year}-#{next_birthday}"
|
||||
|> Date.from_iso8601!()
|
||||
|
||||
if next_birthdate |> Date.diff(Date.utc_today) < 0 do
|
||||
if next_birthdate |> Date.diff(Date.utc_today()) < 0 do
|
||||
"#{this_year + 1}-#{next_birthday}" |> Date.from_iso8601!()
|
||||
else
|
||||
next_birthdate
|
||||
@@ -59,20 +71,51 @@ defmodule Helpers do
|
||||
end
|
||||
|
||||
def time_until_birthday(friend) do
|
||||
birthday(friend) |> Date.diff(Date.utc_today)
|
||||
birthday(friend) |> Date.diff(Date.utc_today())
|
||||
end
|
||||
|
||||
def relations(friend) do
|
||||
def relations(friend, include_self \\ false) do
|
||||
list =
|
||||
[friend.relationships, friend.reverse_relationships]
|
||||
|> List.flatten()
|
||||
|> Enum.dedup()
|
||||
|
||||
if include_self, do: list, else: list |> Enum.filter(&(&1.id != friend.id))
|
||||
end
|
||||
|
||||
def relation(friend, friend2) do
|
||||
Friends.Relationship.get(friend, friend2)
|
||||
end
|
||||
|
||||
def events(relationship) do
|
||||
def events(%Friends.Relationship{} = relationship) do
|
||||
relationship.events
|
||||
end
|
||||
|
||||
def random_string(length) do
|
||||
:crypto.strong_rand_bytes(length)
|
||||
|> Base.url_encode64()
|
||||
|> binary_part(0, length)
|
||||
|> String.replace(~r/-/, "")
|
||||
end
|
||||
|
||||
def unique_friend_email, do: "user#{System.unique_integer()}@example.com"
|
||||
def valid_friend_name, do: "#{random_string(5)} Mc#{random_string(5)}"
|
||||
def valid_friend_phone, do: "+1 (917) 624 2939" |> Helpers.format_phone()
|
||||
def valid_friend_birthdate, do: ~D"1990-05-05"
|
||||
|
||||
def valid_friend_attributes(attrs \\ %{}) do
|
||||
Enum.into(attrs, %{
|
||||
id: nil,
|
||||
name: valid_friend_name(),
|
||||
phone: valid_friend_phone(),
|
||||
born: valid_friend_birthdate(),
|
||||
email: unique_friend_email()
|
||||
})
|
||||
end
|
||||
|
||||
def friend_fixture(attrs \\ %{}) do
|
||||
attrs
|
||||
|> valid_friend_attributes()
|
||||
|> Friends.Friend.create_or_update()
|
||||
end
|
||||
end
|
||||
|
||||
+5
-1
@@ -33,6 +33,7 @@ defmodule Friends.MixProject do
|
||||
# Type `mix help deps` for examples and options.
|
||||
defp deps do
|
||||
[
|
||||
{:bcrypt_elixir, "~> 3.0"},
|
||||
{:phoenix, "~> 1.6.14"},
|
||||
{:phoenix_ecto, "~> 4.4"},
|
||||
{:ecto_sql, "~> 3.6"},
|
||||
@@ -53,7 +54,10 @@ defmodule Friends.MixProject do
|
||||
{:tailwind, "~> 0.1.6", runtime: Mix.env() == :dev},
|
||||
{:earmark, "~> 1.4"},
|
||||
{:html_sanitize_ex, "~> 1.3"},
|
||||
{:yamerl, github: "yakaz/yamerl"}
|
||||
{:yamerl, github: "yakaz/yamerl"},
|
||||
{:iamvery, "~> 0.6"},
|
||||
{:httpoison, "~> 1.8"},
|
||||
{:poison, "~> 5.0"}
|
||||
]
|
||||
end
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
%{
|
||||
"bcrypt_elixir": {:hex, :bcrypt_elixir, "3.0.1", "9be815469e6bfefec40fa74658ecbbe6897acfb57614df1416eeccd4903f602c", [:make, :mix], [{:comeonin, "~> 5.3", [hex: :comeonin, repo: "hexpm", optional: false]}, {:elixir_make, "~> 0.6", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "486bb95efb645d1efc6794c1ddd776a186a9a713abf06f45708a6ce324fb96cf"},
|
||||
"castore": {:hex, :castore, "0.1.18", "deb5b9ab02400561b6f5708f3e7660fc35ca2d51bfc6a940d2f513f89c2975fc", [:mix], [], "hexpm", "61bbaf6452b782ef80b33cdb45701afbcf0a918a45ebe7e73f1130d661e66a06"},
|
||||
"certifi": {:hex, :certifi, "2.9.0", "6f2a475689dd47f19fb74334859d460a2dc4e3252a3324bd2111b8f0429e7e21", [:rebar3], [], "hexpm", "266da46bdb06d6c6d35fde799bcb28d36d985d424ad7c08b5bb48f5b5cdd4641"},
|
||||
"combine": {:hex, :combine, "0.10.0", "eff8224eeb56498a2af13011d142c5e7997a80c8f5b97c499f84c841032e429f", [:mix], [], "hexpm", "1b1dbc1790073076580d0d1d64e42eae2366583e7aecd455d1215b0d16f2451b"},
|
||||
"comeonin": {:hex, :comeonin, "5.3.3", "2c564dac95a35650e9b6acfe6d2952083d8a08e4a89b93a481acb552b325892e", [:mix], [], "hexpm", "3e38c9c2cb080828116597ca8807bb482618a315bfafd98c90bc22a821cc84df"},
|
||||
"connection": {:hex, :connection, "1.1.0", "ff2a49c4b75b6fb3e674bfc5536451607270aac754ffd1bdfe175abe4a6d7a68", [:mix], [], "hexpm", "722c1eb0a418fbe91ba7bd59a47e28008a189d47e37e0e7bb85585a016b2869c"},
|
||||
"cowboy": {:hex, :cowboy, "2.9.0", "865dd8b6607e14cf03282e10e934023a1bd8be6f6bacf921a7e2a96d800cd452", [:make, :rebar3], [{:cowlib, "2.11.0", [hex: :cowlib, repo: "hexpm", optional: false]}, {:ranch, "1.8.0", [hex: :ranch, repo: "hexpm", optional: false]}], "hexpm", "2c729f934b4e1aa149aff882f57c6372c15399a20d54f65c8d67bef583021bde"},
|
||||
"cowboy_telemetry": {:hex, :cowboy_telemetry, "0.4.0", "f239f68b588efa7707abce16a84d0d2acf3a0f50571f8bb7f56a15865aae820c", [:rebar3], [{:cowboy, "~> 2.7", [hex: :cowboy, repo: "hexpm", optional: false]}, {:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "7d98bac1ee4565d31b62d59f8823dfd8356a169e7fcbb83831b8a5397404c9de"},
|
||||
@@ -12,6 +14,7 @@
|
||||
"earmark_parser": {:hex, :earmark_parser, "1.4.29", "149d50dcb3a93d9f3d6f3ecf18c918fb5a2d3c001b5d3305c926cddfbd33355b", [:mix], [], "hexpm", "4902af1b3eb139016aed210888748db8070b8125c2342ce3dcae4f38dcc63503"},
|
||||
"ecto": {:hex, :ecto, "3.9.1", "67173b1687afeb68ce805ee7420b4261649d5e2deed8fe5550df23bab0bc4396", [:mix], [{:decimal, "~> 1.6 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "c80bb3d736648df790f7f92f81b36c922d9dd3203ca65be4ff01d067f54eb304"},
|
||||
"ecto_sql": {:hex, :ecto_sql, "3.9.0", "2bb21210a2a13317e098a420a8c1cc58b0c3421ab8e3acfa96417dab7817918c", [:mix], [{:db_connection, "~> 2.5 or ~> 2.4.1", [hex: :db_connection, repo: "hexpm", optional: false]}, {:ecto, "~> 3.9.0", [hex: :ecto, repo: "hexpm", optional: false]}, {:myxql, "~> 0.6.0", [hex: :myxql, repo: "hexpm", optional: true]}, {:postgrex, "~> 0.16.0 or ~> 1.0", [hex: :postgrex, repo: "hexpm", optional: true]}, {:tds, "~> 2.1.1 or ~> 2.2", [hex: :tds, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "a8f3f720073b8b1ac4c978be25fa7960ed7fd44997420c304a4a2e200b596453"},
|
||||
"elixir_make": {:hex, :elixir_make, "0.6.3", "bc07d53221216838d79e03a8019d0839786703129599e9619f4ab74c8c096eac", [:mix], [], "hexpm", "f5cbd651c5678bcaabdbb7857658ee106b12509cd976c2c2fca99688e1daf716"},
|
||||
"esbuild": {:hex, :esbuild, "0.5.0", "d5bb08ff049d7880ee3609ed5c4b864bd2f46445ea40b16b4acead724fb4c4a3", [:mix], [{:castore, ">= 0.0.0", [hex: :castore, repo: "hexpm", optional: false]}], "hexpm", "f183a0b332d963c4cfaf585477695ea59eef9a6f2204fdd0efa00e099694ffe5"},
|
||||
"file_system": {:hex, :file_system, "0.2.10", "fb082005a9cd1711c05b5248710f8826b02d7d1784e7c3451f9c1231d4fc162d", [:mix], [], "hexpm", "41195edbfb562a593726eda3b3e8b103a309b733ad25f3d642ba49696bf715dc"},
|
||||
"floki": {:hex, :floki, "0.33.1", "f20f1eb471e726342b45ccb68edb9486729e7df94da403936ea94a794f072781", [:mix], [{:html_entities, "~> 0.5.0", [hex: :html_entities, repo: "hexpm", optional: false]}], "hexpm", "461035fd125f13fdf30f243c85a0b1e50afbec876cbf1ceefe6fddd2e6d712c6"},
|
||||
@@ -19,6 +22,8 @@
|
||||
"hackney": {:hex, :hackney, "1.18.1", "f48bf88f521f2a229fc7bae88cf4f85adc9cd9bcf23b5dc8eb6a1788c662c4f6", [:rebar3], [{:certifi, "~>2.9.0", [hex: :certifi, repo: "hexpm", optional: false]}, {:idna, "~>6.1.0", [hex: :idna, repo: "hexpm", optional: false]}, {:metrics, "~>1.0.0", [hex: :metrics, repo: "hexpm", optional: false]}, {:mimerl, "~>1.1", [hex: :mimerl, repo: "hexpm", optional: false]}, {:parse_trans, "3.3.1", [hex: :parse_trans, repo: "hexpm", optional: false]}, {:ssl_verify_fun, "~>1.1.0", [hex: :ssl_verify_fun, repo: "hexpm", optional: false]}, {:unicode_util_compat, "~>0.7.0", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm", "a4ecdaff44297e9b5894ae499e9a070ea1888c84afdd1fd9b7b2bc384950128e"},
|
||||
"html_entities": {:hex, :html_entities, "0.5.2", "9e47e70598da7de2a9ff6af8758399251db6dbb7eebe2b013f2bbd2515895c3c", [:mix], [], "hexpm", "c53ba390403485615623b9531e97696f076ed415e8d8058b1dbaa28181f4fdcc"},
|
||||
"html_sanitize_ex": {:hex, :html_sanitize_ex, "1.4.2", "c479398b6de798c03eb5d04a0a9a9159d73508f83f6590a00b8eacba3619cf4c", [:mix], [{:mochiweb, "~> 2.15", [hex: :mochiweb, repo: "hexpm", optional: false]}], "hexpm", "aef6c28585d06a9109ad591507e508854c5559561f950bbaea773900dd369b0e"},
|
||||
"httpoison": {:hex, :httpoison, "1.8.2", "9eb9c63ae289296a544842ef816a85d881d4a31f518a0fec089aaa744beae290", [:mix], [{:hackney, "~> 1.17", [hex: :hackney, repo: "hexpm", optional: false]}], "hexpm", "2bb350d26972e30c96e2ca74a1aaf8293d61d0742ff17f01e0279fef11599921"},
|
||||
"iamvery": {:hex, :iamvery, "0.6.0", "6df5a753023cb4ea281f96f1c311d9af39e5e0d8328e2db5fa9923036ea3ddc0", [:mix], [], "hexpm", "6c408c7b1e4dc1c8736470f88a40177559b2dd898f27cf250574e87585f9a925"},
|
||||
"idna": {:hex, :idna, "6.1.1", "8a63070e9f7d0c62eb9d9fcb360a7de382448200fbbd1b106cc96d3d8099df8d", [:rebar3], [{:unicode_util_compat, "~>0.7.0", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm", "92376eb7894412ed19ac475e4a86f7b413c1b9fbb5bd16dccd57934157944cea"},
|
||||
"jason": {:hex, :jason, "1.4.0", "e855647bc964a44e2f67df589ccf49105ae039d4179db7f6271dfd3843dc27e6", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "79a3791085b2a0f743ca04cec0f7be26443738779d09302e01318f97bdb82121"},
|
||||
"metrics": {:hex, :metrics, "1.0.1", "25f094dea2cda98213cecc3aeff09e940299d950904393b2a29d191c346a8486", [:rebar3], [], "hexpm", "69b09adddc4f74a40716ae54d140f93beb0fb8978d8636eaded0c31b6f099f16"},
|
||||
@@ -37,6 +42,7 @@
|
||||
"plug": {:hex, :plug, "1.13.6", "187beb6b67c6cec50503e940f0434ea4692b19384d47e5fdfd701e93cadb4cc2", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "02b9c6b9955bce92c829f31d6284bf53c591ca63c4fb9ff81dfd0418667a34ff"},
|
||||
"plug_cowboy": {:hex, :plug_cowboy, "2.5.2", "62894ccd601cf9597e2c23911ff12798a8a18d237e9739f58a6b04e4988899fe", [:mix], [{:cowboy, "~> 2.7", [hex: :cowboy, repo: "hexpm", optional: false]}, {:cowboy_telemetry, "~> 0.3", [hex: :cowboy_telemetry, repo: "hexpm", optional: false]}, {:plug, "~> 1.7", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm", "ea6e87f774c8608d60c8d34022a7d073bd7680a0a013f049fc62bf35efea1044"},
|
||||
"plug_crypto": {:hex, :plug_crypto, "1.2.3", "8f77d13aeb32bfd9e654cb68f0af517b371fb34c56c9f2b58fe3df1235c1251a", [:mix], [], "hexpm", "b5672099c6ad5c202c45f5a403f21a3411247f164e4a8fab056e5cd8a290f4a2"},
|
||||
"poison": {:hex, :poison, "5.0.0", "d2b54589ab4157bbb82ec2050757779bfed724463a544b6e20d79855a9e43b24", [:mix], [{:decimal, "~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "11dc6117c501b80c62a7594f941d043982a1bd05a1184280c0d9166eb4d8d3fc"},
|
||||
"postgrex": {:hex, :postgrex, "0.16.5", "fcc4035cc90e23933c5d69a9cd686e329469446ef7abba2cf70f08e2c4b69810", [:mix], [{:connection, "~> 1.1", [hex: :connection, repo: "hexpm", optional: false]}, {:db_connection, "~> 2.1", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "edead639dc6e882618c01d8fc891214c481ab9a3788dfe38dd5e37fd1d5fb2e8"},
|
||||
"ranch": {:hex, :ranch, "1.8.0", "8c7a100a139fd57f17327b6413e4167ac559fbc04ca7448e9be9057311597a1d", [:make, :rebar3], [], "hexpm", "49fbcfd3682fab1f5d109351b61257676da1a2fdbe295904176d5e521a2ddfe5"},
|
||||
"ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.6", "cf344f5692c82d2cd7554f5ec8fd961548d4fd09e7d22f5b62482e5aeaebd4b0", [:make, :mix, :rebar3], [], "hexpm", "bdb0d2471f453c88ff3908e7686f86f9be327d065cc1ec16fa4540197ea04680"},
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
defmodule Friends.Repo.Migrations.CreateUsersAuthTables do
|
||||
use Ecto.Migration
|
||||
|
||||
def change do
|
||||
execute "CREATE EXTENSION IF NOT EXISTS citext", ""
|
||||
|
||||
create table(:users) do
|
||||
add :email, :citext, null: false
|
||||
add :hashed_password, :string, null: false
|
||||
add :confirmed_at, :naive_datetime
|
||||
timestamps()
|
||||
end
|
||||
|
||||
create unique_index(:users, [:email])
|
||||
|
||||
create table(:users_tokens) do
|
||||
add :user_id, references(:users, on_delete: :delete_all), null: false
|
||||
add :token, :binary, null: false
|
||||
add :context, :string, null: false
|
||||
add :sent_to, :string
|
||||
timestamps(updated_at: false)
|
||||
end
|
||||
|
||||
create index(:users_tokens, [:user_id])
|
||||
create unique_index(:users_tokens, [:context, :token])
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,9 @@
|
||||
defmodule Friends.Repo.Migrations.ProfileBelongsToUser do
|
||||
use Ecto.Migration
|
||||
|
||||
def change do
|
||||
alter table(:friends) do
|
||||
add :user_id, references(:users)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,9 @@
|
||||
defmodule Friends.Repo.Migrations.AddAddressesToFriends do
|
||||
use Ecto.Migration
|
||||
|
||||
def change do
|
||||
alter table(:friends) do
|
||||
add :address_id, references(:places)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,530 @@
|
||||
defmodule Friends.AccountsTest do
|
||||
use Friends.DataCase
|
||||
|
||||
alias Friends.Accounts
|
||||
|
||||
import Friends.{AccountsFixtures, FriendsFixtures}
|
||||
alias Friends.Accounts.{User, UserToken}
|
||||
|
||||
describe "get_user_by_email/1" do
|
||||
test "does not return the user if the email does not exist" do
|
||||
refute Accounts.get_user_by_email("unknown@example.com")
|
||||
end
|
||||
|
||||
test "returns the user if the email exists" do
|
||||
%{id: id} = user = user_fixture()
|
||||
assert %User{id: ^id} = Accounts.get_user_by_email(user.email)
|
||||
end
|
||||
end
|
||||
|
||||
describe "get_user_by_email_and_password/2" do
|
||||
test "does not return the user if the email does not exist" do
|
||||
refute Accounts.get_user_by_email_and_password("unknown@example.com", "hello world!")
|
||||
end
|
||||
|
||||
test "does not return the user if the password is not valid" do
|
||||
user = user_fixture()
|
||||
refute Accounts.get_user_by_email_and_password(user.email, "invalid")
|
||||
end
|
||||
|
||||
test "returns the user if the email and password are valid" do
|
||||
%{id: id} = user = user_fixture()
|
||||
|
||||
assert %User{id: ^id} =
|
||||
Accounts.get_user_by_email_and_password(user.email, valid_user_password())
|
||||
end
|
||||
end
|
||||
|
||||
describe "get_user!/1" do
|
||||
test "raises if id is invalid" do
|
||||
assert_raise Ecto.NoResultsError, fn ->
|
||||
Accounts.get_user!(-1)
|
||||
end
|
||||
end
|
||||
|
||||
test "returns the user with the given id" do
|
||||
%{id: id} = user = user_fixture()
|
||||
assert %User{id: ^id} = Accounts.get_user!(user.id)
|
||||
end
|
||||
end
|
||||
|
||||
describe "register_user/1" do
|
||||
test "requires email and password to be set" do
|
||||
{:error, changeset} = Accounts.register_user(%{})
|
||||
|
||||
assert %{
|
||||
password: ["can't be blank"],
|
||||
email: ["can't be blank"]
|
||||
} = errors_on(changeset)
|
||||
end
|
||||
|
||||
test "validates email and password when given" do
|
||||
{:error, changeset} = Accounts.register_user(%{email: "not valid", password: "not valid"})
|
||||
|
||||
assert %{
|
||||
email: ["must have the @ sign and no spaces"]
|
||||
} = errors_on(changeset)
|
||||
end
|
||||
|
||||
test "validates maximum values for email and password for security" do
|
||||
too_long = String.duplicate("db", 100)
|
||||
{:error, changeset} = Accounts.register_user(%{email: too_long, password: too_long})
|
||||
assert "should be at most 160 character(s)" in errors_on(changeset).email
|
||||
assert "should be at most 72 character(s)" in errors_on(changeset).password
|
||||
end
|
||||
|
||||
test "validates email uniqueness" do
|
||||
%{email: email} = user_fixture()
|
||||
{:error, changeset} = Accounts.register_user(%{email: email})
|
||||
assert "has already been taken" in errors_on(changeset).email
|
||||
|
||||
# Now try with the upper cased email too, to check that email case is ignored.
|
||||
{:error, changeset} = Accounts.register_user(%{email: String.upcase(email)})
|
||||
assert "has already been taken" in errors_on(changeset).email
|
||||
end
|
||||
|
||||
test "registers users with a hashed password" do
|
||||
email = unique_user_email()
|
||||
{:ok, user} = Accounts.register_user(valid_user_attributes(email: email))
|
||||
assert user.email == email
|
||||
assert is_binary(user.hashed_password)
|
||||
assert is_nil(user.confirmed_at)
|
||||
assert is_nil(user.password)
|
||||
end
|
||||
end
|
||||
|
||||
describe "change_user_registration/2" do
|
||||
test "returns a changeset" do
|
||||
assert %Ecto.Changeset{} = changeset = Accounts.change_user_registration(%User{})
|
||||
assert changeset.required == [:password, :email]
|
||||
end
|
||||
|
||||
test "allows fields to be set" do
|
||||
email = unique_user_email()
|
||||
password = valid_user_password()
|
||||
|
||||
changeset =
|
||||
Accounts.change_user_registration(
|
||||
%User{},
|
||||
valid_user_attributes(email: email, password: password)
|
||||
)
|
||||
|
||||
assert changeset.valid?
|
||||
assert get_change(changeset, :email) == email
|
||||
assert get_change(changeset, :password) == password
|
||||
assert is_nil(get_change(changeset, :hashed_password))
|
||||
end
|
||||
end
|
||||
|
||||
describe "change_user_email/2" do
|
||||
test "returns a user changeset" do
|
||||
assert %Ecto.Changeset{} = changeset = Accounts.change_user_email(%User{})
|
||||
assert changeset.required == [:email]
|
||||
end
|
||||
end
|
||||
|
||||
describe "apply_user_email/3" do
|
||||
setup do
|
||||
%{user: user_fixture()}
|
||||
end
|
||||
|
||||
test "requires email to change", %{user: user} do
|
||||
{:error, changeset} = Accounts.apply_user_email(user, valid_user_password(), %{})
|
||||
assert %{email: ["did not change"]} = errors_on(changeset)
|
||||
end
|
||||
|
||||
test "validates email", %{user: user} do
|
||||
{:error, changeset} =
|
||||
Accounts.apply_user_email(user, valid_user_password(), %{email: "not valid"})
|
||||
|
||||
assert %{email: ["must have the @ sign and no spaces"]} = errors_on(changeset)
|
||||
end
|
||||
|
||||
test "validates maximum value for email for security", %{user: user} do
|
||||
too_long = String.duplicate("db", 100)
|
||||
|
||||
{:error, changeset} =
|
||||
Accounts.apply_user_email(user, valid_user_password(), %{email: too_long})
|
||||
|
||||
assert "should be at most 160 character(s)" in errors_on(changeset).email
|
||||
end
|
||||
|
||||
test "validates email uniqueness", %{user: user} do
|
||||
%{email: email} = user_fixture()
|
||||
|
||||
{:error, changeset} =
|
||||
Accounts.apply_user_email(user, valid_user_password(), %{email: email})
|
||||
|
||||
assert "has already been taken" in errors_on(changeset).email
|
||||
end
|
||||
|
||||
test "validates current password", %{user: user} do
|
||||
{:error, changeset} =
|
||||
Accounts.apply_user_email(user, "invalid", %{email: unique_user_email()})
|
||||
|
||||
assert %{current_password: ["is not valid"]} = errors_on(changeset)
|
||||
end
|
||||
|
||||
test "applies the email without persisting it", %{user: user} do
|
||||
email = unique_user_email()
|
||||
{:ok, user} = Accounts.apply_user_email(user, valid_user_password(), %{email: email})
|
||||
assert user.email == email
|
||||
assert Accounts.get_user!(user.id).email != email
|
||||
end
|
||||
end
|
||||
|
||||
describe "deliver_update_email_instructions/3" do
|
||||
setup do
|
||||
%{user: user_fixture()}
|
||||
end
|
||||
|
||||
test "sends token through notification", %{user: user} do
|
||||
token =
|
||||
extract_user_token(fn url ->
|
||||
Accounts.deliver_update_email_instructions(user, "current@example.com", url)
|
||||
end)
|
||||
|
||||
{:ok, token} = Base.url_decode64(token, padding: false)
|
||||
assert user_token = Repo.get_by(UserToken, token: :crypto.hash(:sha256, token))
|
||||
assert user_token.user_id == user.id
|
||||
assert user_token.sent_to == user.email
|
||||
assert user_token.context == "change:current@example.com"
|
||||
end
|
||||
end
|
||||
|
||||
describe "update_user_email/2" do
|
||||
setup do
|
||||
user = user_fixture()
|
||||
email = unique_user_email()
|
||||
|
||||
token =
|
||||
extract_user_token(fn url ->
|
||||
Accounts.deliver_update_email_instructions(%{user | email: email}, user.email, url)
|
||||
end)
|
||||
|
||||
%{user: user, token: token, email: email}
|
||||
end
|
||||
|
||||
test "updates the email with a valid token", %{user: user, token: token, email: email} do
|
||||
assert Accounts.update_user_email(user, token) == :ok
|
||||
changed_user = Repo.get!(User, user.id)
|
||||
assert changed_user.email != user.email
|
||||
assert changed_user.email == email
|
||||
assert changed_user.confirmed_at
|
||||
assert changed_user.confirmed_at != user.confirmed_at
|
||||
refute Repo.get_by(UserToken, user_id: user.id)
|
||||
end
|
||||
|
||||
test "does not update email with invalid token", %{user: user} do
|
||||
assert Accounts.update_user_email(user, "oops") == :error
|
||||
assert Repo.get!(User, user.id).email == user.email
|
||||
assert Repo.get_by(UserToken, user_id: user.id)
|
||||
end
|
||||
|
||||
test "does not update email if user email changed", %{user: user, token: token} do
|
||||
assert Accounts.update_user_email(%{user | email: "current@example.com"}, token) == :error
|
||||
assert Repo.get!(User, user.id).email == user.email
|
||||
assert Repo.get_by(UserToken, user_id: user.id)
|
||||
end
|
||||
|
||||
test "does not update email if token expired", %{user: user, token: token} do
|
||||
{1, nil} = Repo.update_all(UserToken, set: [inserted_at: ~N[2020-01-01 00:00:00]])
|
||||
assert Accounts.update_user_email(user, token) == :error
|
||||
assert Repo.get!(User, user.id).email == user.email
|
||||
assert Repo.get_by(UserToken, user_id: user.id)
|
||||
end
|
||||
end
|
||||
|
||||
describe "change_user_password/2" do
|
||||
test "returns a user changeset" do
|
||||
assert %Ecto.Changeset{} = changeset = Accounts.change_user_password(%User{})
|
||||
assert changeset.required == [:password]
|
||||
end
|
||||
|
||||
test "allows fields to be set" do
|
||||
changeset =
|
||||
Accounts.change_user_password(%User{}, %{
|
||||
"password" => "new valid password"
|
||||
})
|
||||
|
||||
assert changeset.valid?
|
||||
assert get_change(changeset, :password) == "new valid password"
|
||||
assert is_nil(get_change(changeset, :hashed_password))
|
||||
end
|
||||
end
|
||||
|
||||
describe "update_user_password/3" do
|
||||
setup do
|
||||
%{user: user_fixture()}
|
||||
end
|
||||
|
||||
test "validates password", %{user: user} do
|
||||
{:error, changeset} =
|
||||
Accounts.update_user_password(user, valid_user_password(), %{
|
||||
password: "not valid",
|
||||
password_confirmation: "another"
|
||||
})
|
||||
|
||||
assert %{
|
||||
password_confirmation: ["does not match password"]
|
||||
} = errors_on(changeset)
|
||||
end
|
||||
|
||||
test "validates maximum values for password for security", %{user: user} do
|
||||
too_long = String.duplicate("db", 100)
|
||||
|
||||
{:error, changeset} =
|
||||
Accounts.update_user_password(user, valid_user_password(), %{password: too_long})
|
||||
|
||||
assert "should be at most 72 character(s)" in errors_on(changeset).password
|
||||
end
|
||||
|
||||
test "validates current password", %{user: user} do
|
||||
{:error, changeset} =
|
||||
Accounts.update_user_password(user, "invalid", %{password: valid_user_password()})
|
||||
|
||||
assert %{current_password: ["is not valid"]} = errors_on(changeset)
|
||||
end
|
||||
|
||||
test "updates the password", %{user: user} do
|
||||
{:ok, user} =
|
||||
Accounts.update_user_password(user, valid_user_password(), %{
|
||||
password: "new valid password"
|
||||
})
|
||||
|
||||
assert is_nil(user.password)
|
||||
assert Accounts.get_user_by_email_and_password(user.email, "new valid password")
|
||||
end
|
||||
|
||||
test "deletes all tokens for the given user", %{user: user} do
|
||||
_ = Accounts.generate_user_session_token(user)
|
||||
|
||||
{:ok, _} =
|
||||
Accounts.update_user_password(user, valid_user_password(), %{
|
||||
password: "new valid password"
|
||||
})
|
||||
|
||||
refute Repo.get_by(UserToken, user_id: user.id)
|
||||
end
|
||||
end
|
||||
|
||||
describe "generate_user_session_token/1" do
|
||||
setup do
|
||||
%{user: user_fixture()}
|
||||
end
|
||||
|
||||
test "generates a token", %{user: user} do
|
||||
token = Accounts.generate_user_session_token(user)
|
||||
assert user_token = Repo.get_by(UserToken, token: token)
|
||||
assert user_token.context == "session"
|
||||
|
||||
# Creating the same token for another user should fail
|
||||
assert_raise Ecto.ConstraintError, fn ->
|
||||
Repo.insert!(%UserToken{
|
||||
token: user_token.token,
|
||||
user_id: user_fixture().id,
|
||||
context: "session"
|
||||
})
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe "get_user_by_session_token/1" do
|
||||
setup do
|
||||
user = user_fixture()
|
||||
token = Accounts.generate_user_session_token(user)
|
||||
%{user: user, token: token}
|
||||
end
|
||||
|
||||
test "returns user by token", %{user: user, token: token} do
|
||||
assert session_user = Accounts.get_user_by_session_token(token)
|
||||
assert session_user.id == user.id
|
||||
end
|
||||
|
||||
test "does not return user for invalid token" do
|
||||
refute Accounts.get_user_by_session_token("oops")
|
||||
end
|
||||
|
||||
test "does not return user for expired token", %{token: token} do
|
||||
{1, nil} = Repo.update_all(UserToken, set: [inserted_at: ~N[2020-01-01 00:00:00]])
|
||||
refute Accounts.get_user_by_session_token(token)
|
||||
end
|
||||
end
|
||||
|
||||
describe "delete_session_token/1" do
|
||||
test "deletes the token" do
|
||||
user = user_fixture()
|
||||
token = Accounts.generate_user_session_token(user)
|
||||
assert Accounts.delete_session_token(token) == :ok
|
||||
refute Accounts.get_user_by_session_token(token)
|
||||
end
|
||||
end
|
||||
|
||||
describe "deliver_user_confirmation_instructions/2" do
|
||||
setup do
|
||||
%{user: user_fixture()}
|
||||
end
|
||||
|
||||
test "sends token through notification", %{user: user} do
|
||||
token =
|
||||
extract_user_token(fn url ->
|
||||
Accounts.deliver_user_confirmation_instructions(user, url)
|
||||
end)
|
||||
|
||||
{:ok, token} = Base.url_decode64(token, padding: false)
|
||||
assert user_token = Repo.get_by(UserToken, token: :crypto.hash(:sha256, token))
|
||||
assert user_token.user_id == user.id
|
||||
assert user_token.sent_to == user.email
|
||||
assert user_token.context == "confirm"
|
||||
end
|
||||
end
|
||||
|
||||
describe "confirm_user/1" do
|
||||
setup do
|
||||
user = user_fixture()
|
||||
|
||||
token =
|
||||
extract_user_token(fn url ->
|
||||
Accounts.deliver_user_confirmation_instructions(user, url)
|
||||
end)
|
||||
|
||||
%{user: user, token: token}
|
||||
end
|
||||
|
||||
test "confirms the email with a valid token", %{user: user, token: token} do
|
||||
assert {:ok, confirmed_user} = Accounts.confirm_user(token)
|
||||
assert confirmed_user.confirmed_at
|
||||
assert confirmed_user.confirmed_at != user.confirmed_at
|
||||
assert Repo.get!(User, user.id).confirmed_at
|
||||
refute Repo.get_by(UserToken, user_id: user.id)
|
||||
end
|
||||
|
||||
test "does not confirm with invalid token", %{user: user} do
|
||||
assert Accounts.confirm_user("oops") == :error
|
||||
refute Repo.get!(User, user.id).confirmed_at
|
||||
assert Repo.get_by(UserToken, user_id: user.id)
|
||||
end
|
||||
|
||||
test "does not confirm email if token expired", %{user: user, token: token} do
|
||||
{1, nil} = Repo.update_all(UserToken, set: [inserted_at: ~N[2020-01-01 00:00:00]])
|
||||
assert Accounts.confirm_user(token) == :error
|
||||
refute Repo.get!(User, user.id).confirmed_at
|
||||
assert Repo.get_by(UserToken, user_id: user.id)
|
||||
end
|
||||
end
|
||||
|
||||
describe "deliver_user_reset_password_instructions/2" do
|
||||
setup do
|
||||
%{user: user_fixture()}
|
||||
end
|
||||
|
||||
test "sends token through notification", %{user: user} do
|
||||
token =
|
||||
extract_user_token(fn url ->
|
||||
Accounts.deliver_user_reset_password_instructions(user, url)
|
||||
end)
|
||||
|
||||
{:ok, token} = Base.url_decode64(token, padding: false)
|
||||
assert user_token = Repo.get_by(UserToken, token: :crypto.hash(:sha256, token))
|
||||
assert user_token.user_id == user.id
|
||||
assert user_token.sent_to == user.email
|
||||
assert user_token.context == "reset_password"
|
||||
end
|
||||
end
|
||||
|
||||
describe "get_user_by_reset_password_token/1" do
|
||||
setup do
|
||||
user = user_fixture()
|
||||
|
||||
token =
|
||||
extract_user_token(fn url ->
|
||||
Accounts.deliver_user_reset_password_instructions(user, url)
|
||||
end)
|
||||
|
||||
%{user: user, token: token}
|
||||
end
|
||||
|
||||
test "returns the user with valid token", %{user: %{id: id}, token: token} do
|
||||
assert %User{id: ^id} = Accounts.get_user_by_reset_password_token(token)
|
||||
assert Repo.get_by(UserToken, user_id: id)
|
||||
end
|
||||
|
||||
test "does not return the user with invalid token", %{user: user} do
|
||||
refute Accounts.get_user_by_reset_password_token("oops")
|
||||
assert Repo.get_by(UserToken, user_id: user.id)
|
||||
end
|
||||
|
||||
test "does not return the user if token expired", %{user: user, token: token} do
|
||||
{1, nil} = Repo.update_all(UserToken, set: [inserted_at: ~N[2020-01-01 00:00:00]])
|
||||
refute Accounts.get_user_by_reset_password_token(token)
|
||||
assert Repo.get_by(UserToken, user_id: user.id)
|
||||
end
|
||||
end
|
||||
|
||||
describe "reset_user_password/2" do
|
||||
setup do
|
||||
%{user: user_fixture()}
|
||||
end
|
||||
|
||||
test "validates password", %{user: user} do
|
||||
{:error, changeset} =
|
||||
Accounts.reset_user_password(user, %{
|
||||
password: "not valid",
|
||||
password_confirmation: "another"
|
||||
})
|
||||
|
||||
assert %{
|
||||
password_confirmation: ["does not match password"]
|
||||
} = errors_on(changeset)
|
||||
end
|
||||
|
||||
test "validates maximum values for password for security", %{user: user} do
|
||||
too_long = String.duplicate("db", 100)
|
||||
{:error, changeset} = Accounts.reset_user_password(user, %{password: too_long})
|
||||
assert "should be at most 72 character(s)" in errors_on(changeset).password
|
||||
end
|
||||
|
||||
test "updates the password", %{user: user} do
|
||||
{:ok, updated_user} = Accounts.reset_user_password(user, %{password: "new valid password"})
|
||||
assert is_nil(updated_user.password)
|
||||
assert Accounts.get_user_by_email_and_password(user.email, "new valid password")
|
||||
end
|
||||
|
||||
test "deletes all tokens for the given user", %{user: user} do
|
||||
_ = Accounts.generate_user_session_token(user)
|
||||
{:ok, _} = Accounts.reset_user_password(user, %{password: "new valid password"})
|
||||
refute Repo.get_by(UserToken, user_id: user.id)
|
||||
end
|
||||
end
|
||||
|
||||
describe "inspect/2" do
|
||||
test "does not include password" do
|
||||
refute inspect(%User{password: "123456"}) =~ "password: \"123456\""
|
||||
end
|
||||
end
|
||||
|
||||
describe "assign_profile/1" do
|
||||
setup do
|
||||
user = user_fixture()
|
||||
%{
|
||||
user: user,
|
||||
friend: friend_fixture(%{email: user.email})
|
||||
}
|
||||
end
|
||||
|
||||
test "links a friend to a user", %{user: user, friend: friend} do
|
||||
assert user.profile == nil
|
||||
assert friend.user == nil
|
||||
|
||||
%{
|
||||
friend: new_friend,
|
||||
user: new_user
|
||||
} = user |> Friends.Accounts.assign_profile
|
||||
|
||||
assert new_user.profile.id == friend.id
|
||||
assert new_friend.user.id == user.id
|
||||
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
@@ -0,0 +1,126 @@
|
||||
defmodule Friends.FriendsTest do
|
||||
use Friends.DataCase
|
||||
|
||||
alias Friends.Friend
|
||||
|
||||
import Friends.{AccountsFixtures, FriendsFixtures}
|
||||
# alias Friends.Accounts.{User, UserToken}
|
||||
|
||||
describe "new/1" do
|
||||
test "no params" do
|
||||
f = Friend.new()
|
||||
assert f.id == :new
|
||||
end
|
||||
|
||||
test "with params" do
|
||||
attrs = valid_friend_attributes()
|
||||
f = attrs |> Friend.new()
|
||||
assert f.id == :new
|
||||
assert f.name == attrs |> Map.get(:name)
|
||||
end
|
||||
|
||||
test "has no loaded preloads" do
|
||||
f = Friend.new()
|
||||
assert %Ecto.Association.NotLoaded{} = f.user
|
||||
assert %Ecto.Association.NotLoaded{} = f.relationships
|
||||
assert %Ecto.Association.NotLoaded{} = f.reverse_relationships
|
||||
end
|
||||
end
|
||||
|
||||
describe "commit/1" do
|
||||
test "changes id" do
|
||||
f =
|
||||
valid_friend_attributes()
|
||||
|> Friend.create()
|
||||
|> Friend.commit()
|
||||
|
||||
assert f.id != :new
|
||||
end
|
||||
|
||||
test "generates slug" do
|
||||
f =
|
||||
valid_friend_attributes()
|
||||
|> Friend.create()
|
||||
|> Friend.commit()
|
||||
|
||||
assert f.slug != nil
|
||||
assert f.slug == f.name |> Helpers.to_slug()
|
||||
end
|
||||
end
|
||||
|
||||
describe "generate_slug/1" do
|
||||
test "a new friend has no slug" do
|
||||
f = valid_friend_attributes() |> Friend.new()
|
||||
assert f.slug == nil
|
||||
end
|
||||
|
||||
test "generate_slug generates a slug, returns a friend" do
|
||||
f = valid_friend_attributes() |> Friend.new() |> Friend.generate_slug()
|
||||
assert f.slug == f.name |> Helpers.to_slug()
|
||||
end
|
||||
|
||||
test "generate_slug generates a slug, returns a changeset" do
|
||||
c = valid_friend_attributes() |> Friend.create() |> Friend.generate_slug()
|
||||
f = c.data
|
||||
assert f.slug == f.name |> Helpers.to_slug()
|
||||
end
|
||||
end
|
||||
|
||||
describe "assign_user/1" do
|
||||
setup do
|
||||
friend = friend_fixture()
|
||||
|
||||
%{
|
||||
friend: friend,
|
||||
user: user_fixture(%{email: friend.email})
|
||||
}
|
||||
end
|
||||
|
||||
test "links a user to a friend", %{user: user, friend: friend} do
|
||||
assert user.profile == nil
|
||||
assert friend.user == nil
|
||||
|
||||
%{
|
||||
friend: new_friend,
|
||||
user: new_user
|
||||
} = friend |> Friends.Friend.assign_user()
|
||||
|
||||
assert new_user.profile.id == friend.id
|
||||
assert new_friend.user.id == user.id
|
||||
end
|
||||
end
|
||||
|
||||
describe "preloads" do
|
||||
setup do
|
||||
%{friend: Friend.new(%{id: 123})}
|
||||
end
|
||||
|
||||
test "default nothing loaded", %{friend: friend} do
|
||||
f = friend
|
||||
refute f.user |> Ecto.assoc_loaded?()
|
||||
refute f.relationships |> Ecto.assoc_loaded?()
|
||||
refute f.reverse_relationships |> Ecto.assoc_loaded?()
|
||||
end
|
||||
|
||||
test "load user", %{friend: friend} do
|
||||
f = friend |> Friend.load_user()
|
||||
assert f.user |> Ecto.assoc_loaded?()
|
||||
refute f.relationships |> Ecto.assoc_loaded?()
|
||||
refute f.reverse_relationships |> Ecto.assoc_loaded?()
|
||||
end
|
||||
|
||||
test "load relationships", %{friend: friend} do
|
||||
f = friend |> Friend.load_relationships()
|
||||
refute f.user |> Ecto.assoc_loaded?()
|
||||
assert f.relationships |> Ecto.assoc_loaded?()
|
||||
assert f.reverse_relationships |> Ecto.assoc_loaded?()
|
||||
end
|
||||
|
||||
test "load all", %{friend: friend} do
|
||||
f = friend |> Friend.load_preloads()
|
||||
assert f.user |> Ecto.assoc_loaded?()
|
||||
assert f.relationships |> Ecto.assoc_loaded?()
|
||||
assert f.reverse_relationships |> Ecto.assoc_loaded?()
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,39 @@
|
||||
defmodule Friends.HelpersTest do
|
||||
use Friends.DataCase
|
||||
|
||||
#alias Friends.Accounts
|
||||
|
||||
#import Friends.AccountsFixtures
|
||||
#alias Friends.Accounts.{User, UserToken}
|
||||
import Helpers
|
||||
|
||||
describe "format_phone/1" do
|
||||
test "regular US phone number, spaces" do
|
||||
str = "+1 203 848 8633"
|
||||
formatted_str = format_phone(str)
|
||||
assert formatted_str == "+12038488633"
|
||||
end
|
||||
test "regular US phone number, no spaces" do
|
||||
str = "+12038488633"
|
||||
formatted_str = format_phone(str)
|
||||
assert formatted_str == "+12038488633"
|
||||
end
|
||||
test "regular US phone number, dashes" do
|
||||
str = "+1-203-848-8633"
|
||||
formatted_str = format_phone(str)
|
||||
assert formatted_str == "+12038488633"
|
||||
end
|
||||
test "regular US phone number, usual formatting" do
|
||||
str = "+1 (203) 848-8633"
|
||||
formatted_str = format_phone(str)
|
||||
assert formatted_str == "+12038488633"
|
||||
end
|
||||
test "regular US phone number, no country code" do
|
||||
str = "(203) 848-8633"
|
||||
formatted_str = format_phone(str)
|
||||
assert formatted_str == "2038488633"
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
@@ -0,0 +1,63 @@
|
||||
defmodule Friends.RelationshipsTest do
|
||||
use Friends.DataCase
|
||||
import Friends.FriendsFixtures
|
||||
alias Friends.{Friend, Relationship}
|
||||
|
||||
setup do
|
||||
friend1 = friend_fixture()
|
||||
friend2 = friend_fixture()
|
||||
%{
|
||||
friend1: friend1,
|
||||
friend2: friend2,
|
||||
relationship: Relationship.new(
|
||||
friend1, friend2
|
||||
)
|
||||
}
|
||||
end
|
||||
|
||||
describe "init relationships" do
|
||||
test "defaults to nothing", %{friend1: friend1, friend2: friend2} do
|
||||
refute friend2 in friend1.relationships
|
||||
refute friend1 in friend2.relationships
|
||||
end
|
||||
end
|
||||
|
||||
describe "types" do
|
||||
test "defaults to friends", %{relationship: r} do
|
||||
assert (r.type |> Relationship.types) == {
|
||||
:friends, :secondary, :friend
|
||||
}
|
||||
|
||||
assert (r |> Relationship.get_type) == :friends
|
||||
assert (r |> Relationship.get_color) == :secondary
|
||||
assert (r |> Relationship.get_relation) == :friend
|
||||
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
describe "preloads" do
|
||||
setup do
|
||||
%{relationship: Relationship.new(
|
||||
friend_fixture(), friend_fixture())
|
||||
}
|
||||
end
|
||||
|
||||
test "default nothing loaded", %{relationship: relationship} do
|
||||
r = relationship
|
||||
refute r.events |> Ecto.assoc_loaded?
|
||||
end
|
||||
|
||||
test "load events", %{relationship: relationship} do
|
||||
r = relationship |> Relationship.load_events
|
||||
assert r.events |> Ecto.assoc_loaded?
|
||||
end
|
||||
|
||||
test "load all", %{relationship: relationship} do
|
||||
r = relationship |> Relationship.load_preloads
|
||||
assert r.events |> Ecto.assoc_loaded?
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
@@ -0,0 +1,31 @@
|
||||
defmodule FriendsWeb.FriendsControllerTest do
|
||||
use FriendsWeb.ConnCase, async: true
|
||||
import Friends.{AccountsFixtures, FriendsFixtures}
|
||||
|
||||
setup do
|
||||
%{
|
||||
user: _user,
|
||||
friend: _friend
|
||||
} = friend_fixture(%{email: user_fixture().email}) |> Friends.Friend.assign_user()
|
||||
end
|
||||
|
||||
describe "GET '/friends'" do
|
||||
test "shows the friends dashboard", %{conn: conn, friend: friend} do
|
||||
conn = get(conn, "/friends")
|
||||
assert html_response(conn, 200) =~ friend.name
|
||||
assert html_response(conn, 200) =~ "Log in"
|
||||
end
|
||||
|
||||
test "shows '(you)' if logged in", %{conn: conn, friend: friend, user: user} do
|
||||
conn = conn |> log_in_user(user) |> get("/friends")
|
||||
assert html_response(conn, 200) =~ friend.name
|
||||
assert html_response(conn, 200) =~ "(you)"
|
||||
assert html_response(conn, 200) =~ "Log out"
|
||||
end
|
||||
|
||||
test "shows option to add friend if logged in", %{conn: conn, friend: friend, user: user} do
|
||||
conn = conn |> log_in_user(user) |> get("/friends")
|
||||
assert html_response(conn, 200) =~ Routes.friends_edit_path(conn, :overview, :new)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,23 @@
|
||||
defmodule FriendsWeb.FriendsLiveTest do
|
||||
use FriendsWeb.ConnCase, async: true
|
||||
import Friends.{AccountsFixtures, FriendsFixtures}
|
||||
|
||||
setup do
|
||||
%{
|
||||
user: _user,
|
||||
friend: _friend
|
||||
} = friend_fixture(%{email: user_fixture().email}) |> Friends.Friend.assign_user()
|
||||
end
|
||||
|
||||
describe "GET '/friend/:slug'" do
|
||||
test "redirects if live_action not specified", %{conn: conn, friend: friend} do
|
||||
conn = conn |> get("/friend/#{friend.slug}/")
|
||||
assert redirected_to(conn) == Routes.friends_show_path(conn, :overview, friend.slug)
|
||||
end
|
||||
|
||||
test "shows the friend overview", %{conn: conn, friend: friend} do
|
||||
conn = conn |> get("/friend/#{friend.slug}/overview")
|
||||
assert html_response(conn, 200) =~ friend.name
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,8 +1,38 @@
|
||||
defmodule FriendsWeb.PageControllerTest do
|
||||
use FriendsWeb.ConnCase
|
||||
use FriendsWeb.ConnCase, async: true
|
||||
import Friends.{AccountsFixtures, FriendsFixtures}
|
||||
|
||||
test "GET /", %{conn: conn} do
|
||||
alias FriendsWeb.Router.Helpers, as: Routes
|
||||
|
||||
setup do
|
||||
%{user: user_fixture()}
|
||||
end
|
||||
|
||||
describe "GET '/'" do
|
||||
test "shows the landing page if not logged in", %{conn: conn} do
|
||||
conn = get(conn, "/")
|
||||
assert html_response(conn, 200) =~ "Welcome to Phoenix!"
|
||||
assert html_response(conn, 200) =~ "Friends App"
|
||||
assert html_response(conn, 200) =~ "Log in"
|
||||
assert html_response(conn, 200) =~ "Register"
|
||||
end
|
||||
|
||||
test "redirects to the new profile flow if logged in but has no profile", %{
|
||||
conn: conn,
|
||||
user: user
|
||||
} do
|
||||
_friend = friend_fixture(%{email: "random_email@invalid.biz"})
|
||||
conn = conn |> log_in_user(user) |> get("/")
|
||||
assert redirected_to(conn) == Routes.friends_edit_path(conn, :overview, :new)
|
||||
assert get_flash(conn, :info) =~ "profile!"
|
||||
end
|
||||
|
||||
test "redirects to the friends dashboard if logged in & has a profile", %{
|
||||
conn: conn,
|
||||
user: user
|
||||
} do
|
||||
_friend = friend_fixture(%{email: user.email})
|
||||
conn = conn |> log_in_user(user) |> get("/")
|
||||
assert redirected_to(conn) == Routes.friends_path(conn, :index)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
defmodule FriendsWeb.UserAuthTest do
|
||||
use FriendsWeb.ConnCase, async: true
|
||||
|
||||
alias Friends.Accounts
|
||||
alias FriendsWeb.UserAuth
|
||||
import Friends.AccountsFixtures
|
||||
|
||||
@remember_me_cookie "_friends_web_user_remember_me"
|
||||
|
||||
setup %{conn: conn} do
|
||||
conn =
|
||||
conn
|
||||
|> Map.replace!(:secret_key_base, FriendsWeb.Endpoint.config(:secret_key_base))
|
||||
|> init_test_session(%{})
|
||||
|
||||
%{user: user_fixture(), conn: conn}
|
||||
end
|
||||
|
||||
describe "log_in_user/3" do
|
||||
test "stores the user token in the session", %{conn: conn, user: user} do
|
||||
conn = UserAuth.log_in_user(conn, user)
|
||||
assert token = get_session(conn, :user_token)
|
||||
assert get_session(conn, :live_socket_id) == "users_sessions:#{Base.url_encode64(token)}"
|
||||
assert redirected_to(conn) == "/"
|
||||
assert Accounts.get_user_by_session_token(token)
|
||||
end
|
||||
|
||||
test "clears everything previously stored in the session", %{conn: conn, user: user} do
|
||||
conn = conn |> put_session(:to_be_removed, "value") |> UserAuth.log_in_user(user)
|
||||
refute get_session(conn, :to_be_removed)
|
||||
end
|
||||
|
||||
test "redirects to the configured path", %{conn: conn, user: user} do
|
||||
conn = conn |> put_session(:user_return_to, "/hello") |> UserAuth.log_in_user(user)
|
||||
assert redirected_to(conn) == "/hello"
|
||||
end
|
||||
|
||||
test "writes a cookie if remember_me is configured", %{conn: conn, user: user} do
|
||||
conn = conn |> fetch_cookies() |> UserAuth.log_in_user(user, %{"remember_me" => "true"})
|
||||
assert get_session(conn, :user_token) == conn.cookies[@remember_me_cookie]
|
||||
|
||||
assert %{value: signed_token, max_age: max_age} = conn.resp_cookies[@remember_me_cookie]
|
||||
assert signed_token != get_session(conn, :user_token)
|
||||
assert max_age == 5_184_000
|
||||
end
|
||||
end
|
||||
|
||||
describe "logout_user/1" do
|
||||
test "erases session and cookies", %{conn: conn, user: user} do
|
||||
user_token = Accounts.generate_user_session_token(user)
|
||||
|
||||
conn =
|
||||
conn
|
||||
|> put_session(:user_token, user_token)
|
||||
|> put_req_cookie(@remember_me_cookie, user_token)
|
||||
|> fetch_cookies()
|
||||
|> UserAuth.log_out_user()
|
||||
|
||||
refute get_session(conn, :user_token)
|
||||
refute conn.cookies[@remember_me_cookie]
|
||||
assert %{max_age: 0} = conn.resp_cookies[@remember_me_cookie]
|
||||
assert redirected_to(conn) == "/"
|
||||
refute Accounts.get_user_by_session_token(user_token)
|
||||
end
|
||||
|
||||
test "broadcasts to the given live_socket_id", %{conn: conn} do
|
||||
live_socket_id = "users_sessions:abcdef-token"
|
||||
FriendsWeb.Endpoint.subscribe(live_socket_id)
|
||||
|
||||
conn
|
||||
|> put_session(:live_socket_id, live_socket_id)
|
||||
|> UserAuth.log_out_user()
|
||||
|
||||
assert_receive %Phoenix.Socket.Broadcast{event: "disconnect", topic: ^live_socket_id}
|
||||
end
|
||||
|
||||
test "works even if user is already logged out", %{conn: conn} do
|
||||
conn = conn |> fetch_cookies() |> UserAuth.log_out_user()
|
||||
refute get_session(conn, :user_token)
|
||||
assert %{max_age: 0} = conn.resp_cookies[@remember_me_cookie]
|
||||
assert redirected_to(conn) == "/"
|
||||
end
|
||||
end
|
||||
|
||||
describe "fetch_current_user/2" do
|
||||
test "authenticates user from session", %{conn: conn, user: user} do
|
||||
user_token = Accounts.generate_user_session_token(user)
|
||||
conn = conn |> put_session(:user_token, user_token) |> UserAuth.fetch_current_user([])
|
||||
assert conn.assigns.current_user.id == user.id
|
||||
end
|
||||
|
||||
test "authenticates user from cookies", %{conn: conn, user: user} do
|
||||
logged_in_conn =
|
||||
conn |> fetch_cookies() |> UserAuth.log_in_user(user, %{"remember_me" => "true"})
|
||||
|
||||
user_token = logged_in_conn.cookies[@remember_me_cookie]
|
||||
%{value: signed_token} = logged_in_conn.resp_cookies[@remember_me_cookie]
|
||||
|
||||
conn =
|
||||
conn
|
||||
|> put_req_cookie(@remember_me_cookie, signed_token)
|
||||
|> UserAuth.fetch_current_user([])
|
||||
|
||||
assert get_session(conn, :user_token) == user_token
|
||||
assert conn.assigns.current_user.id == user.id
|
||||
end
|
||||
|
||||
test "does not authenticate if data is missing", %{conn: conn, user: user} do
|
||||
_ = Accounts.generate_user_session_token(user)
|
||||
conn = UserAuth.fetch_current_user(conn, [])
|
||||
refute get_session(conn, :user_token)
|
||||
refute conn.assigns.current_user
|
||||
end
|
||||
end
|
||||
|
||||
describe "redirect_if_user_is_authenticated/2" do
|
||||
test "redirects if user is authenticated", %{conn: conn, user: user} do
|
||||
conn = conn |> assign(:current_user, user) |> UserAuth.redirect_if_user_is_authenticated([])
|
||||
assert conn.halted
|
||||
assert redirected_to(conn) == "/"
|
||||
end
|
||||
|
||||
test "does not redirect if user is not authenticated", %{conn: conn} do
|
||||
conn = UserAuth.redirect_if_user_is_authenticated(conn, [])
|
||||
refute conn.halted
|
||||
refute conn.status
|
||||
end
|
||||
end
|
||||
|
||||
describe "require_authenticated_user/2" do
|
||||
test "redirects if user is not authenticated", %{conn: conn} do
|
||||
conn = conn |> fetch_flash() |> UserAuth.require_authenticated_user([])
|
||||
assert conn.halted
|
||||
assert redirected_to(conn) == Routes.user_session_path(conn, :new)
|
||||
assert get_flash(conn, :error) == "You must log in to access this page."
|
||||
end
|
||||
|
||||
test "stores the path to redirect to on GET", %{conn: conn} do
|
||||
halted_conn =
|
||||
%{conn | path_info: ["foo"], query_string: ""}
|
||||
|> fetch_flash()
|
||||
|> UserAuth.require_authenticated_user([])
|
||||
|
||||
assert halted_conn.halted
|
||||
assert get_session(halted_conn, :user_return_to) == "/foo"
|
||||
|
||||
halted_conn =
|
||||
%{conn | path_info: ["foo"], query_string: "bar=baz"}
|
||||
|> fetch_flash()
|
||||
|> UserAuth.require_authenticated_user([])
|
||||
|
||||
assert halted_conn.halted
|
||||
assert get_session(halted_conn, :user_return_to) == "/foo?bar=baz"
|
||||
|
||||
halted_conn =
|
||||
%{conn | path_info: ["foo"], query_string: "bar", method: "POST"}
|
||||
|> fetch_flash()
|
||||
|> UserAuth.require_authenticated_user([])
|
||||
|
||||
assert halted_conn.halted
|
||||
refute get_session(halted_conn, :user_return_to)
|
||||
end
|
||||
|
||||
test "does not redirect if user is authenticated", %{conn: conn, user: user} do
|
||||
conn = conn |> assign(:current_user, user) |> UserAuth.require_authenticated_user([])
|
||||
refute conn.halted
|
||||
refute conn.status
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,105 @@
|
||||
defmodule FriendsWeb.UserConfirmationControllerTest do
|
||||
use FriendsWeb.ConnCase, async: true
|
||||
|
||||
alias Friends.Accounts
|
||||
alias Friends.Repo
|
||||
import Friends.AccountsFixtures
|
||||
|
||||
setup do
|
||||
%{user: user_fixture()}
|
||||
end
|
||||
|
||||
describe "GET /users/confirm" do
|
||||
test "renders the resend confirmation page", %{conn: conn} do
|
||||
conn = get(conn, Routes.user_confirmation_path(conn, :new))
|
||||
response = html_response(conn, 200)
|
||||
assert response =~ "<h1>Resend confirmation instructions</h1>"
|
||||
end
|
||||
end
|
||||
|
||||
describe "POST /users/confirm" do
|
||||
@tag :capture_log
|
||||
test "sends a new confirmation token", %{conn: conn, user: user} do
|
||||
conn =
|
||||
post(conn, Routes.user_confirmation_path(conn, :create), %{
|
||||
"user" => %{"email" => user.email}
|
||||
})
|
||||
|
||||
assert redirected_to(conn) == "/"
|
||||
assert get_flash(conn, :info) =~ "If your email is in our system"
|
||||
assert Repo.get_by!(Accounts.UserToken, user_id: user.id).context == "confirm"
|
||||
end
|
||||
|
||||
test "does not send confirmation token if User is confirmed", %{conn: conn, user: user} do
|
||||
Repo.update!(Accounts.User.confirm_changeset(user))
|
||||
|
||||
conn =
|
||||
post(conn, Routes.user_confirmation_path(conn, :create), %{
|
||||
"user" => %{"email" => user.email}
|
||||
})
|
||||
|
||||
assert redirected_to(conn) == "/"
|
||||
assert get_flash(conn, :info) =~ "If your email is in our system"
|
||||
refute Repo.get_by(Accounts.UserToken, user_id: user.id)
|
||||
end
|
||||
|
||||
test "does not send confirmation token if email is invalid", %{conn: conn} do
|
||||
conn =
|
||||
post(conn, Routes.user_confirmation_path(conn, :create), %{
|
||||
"user" => %{"email" => "unknown@example.com"}
|
||||
})
|
||||
|
||||
assert redirected_to(conn) == "/"
|
||||
assert get_flash(conn, :info) =~ "If your email is in our system"
|
||||
assert Repo.all(Accounts.UserToken) == []
|
||||
end
|
||||
end
|
||||
|
||||
describe "GET /users/confirm/:token" do
|
||||
test "renders the confirmation page", %{conn: conn} do
|
||||
conn = get(conn, Routes.user_confirmation_path(conn, :edit, "some-token"))
|
||||
response = html_response(conn, 200)
|
||||
assert response =~ "<h1>Confirm account</h1>"
|
||||
|
||||
form_action = Routes.user_confirmation_path(conn, :update, "some-token")
|
||||
assert response =~ "action=\"#{form_action}\""
|
||||
end
|
||||
end
|
||||
|
||||
describe "POST /users/confirm/:token" do
|
||||
test "confirms the given token once", %{conn: conn, user: user} do
|
||||
token =
|
||||
extract_user_token(fn url ->
|
||||
Accounts.deliver_user_confirmation_instructions(user, url)
|
||||
end)
|
||||
|
||||
conn = post(conn, Routes.user_confirmation_path(conn, :update, token))
|
||||
assert redirected_to(conn) == "/"
|
||||
assert get_flash(conn, :info) =~ "User confirmed successfully"
|
||||
assert Accounts.get_user!(user.id).confirmed_at
|
||||
refute get_session(conn, :user_token)
|
||||
assert Repo.all(Accounts.UserToken) == []
|
||||
|
||||
# When not logged in
|
||||
conn = post(conn, Routes.user_confirmation_path(conn, :update, token))
|
||||
assert redirected_to(conn) == "/"
|
||||
assert get_flash(conn, :error) =~ "User confirmation link is invalid or it has expired"
|
||||
|
||||
# When logged in
|
||||
conn =
|
||||
build_conn()
|
||||
|> log_in_user(user)
|
||||
|> post(Routes.user_confirmation_path(conn, :update, token))
|
||||
|
||||
assert redirected_to(conn) == "/"
|
||||
refute get_flash(conn, :error)
|
||||
end
|
||||
|
||||
test "does not confirm email with invalid token", %{conn: conn, user: user} do
|
||||
conn = post(conn, Routes.user_confirmation_path(conn, :update, "oops"))
|
||||
assert redirected_to(conn) == "/"
|
||||
assert get_flash(conn, :error) =~ "User confirmation link is invalid or it has expired"
|
||||
refute Accounts.get_user!(user.id).confirmed_at
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,56 @@
|
||||
defmodule FriendsWeb.UserRegistrationControllerTest do
|
||||
use FriendsWeb.ConnCase, async: true
|
||||
|
||||
import Friends.AccountsFixtures
|
||||
|
||||
describe "GET /users/register" do
|
||||
test "renders registration page", %{conn: conn} do
|
||||
conn = get(conn, Routes.user_registration_path(conn, :new))
|
||||
response = html_response(conn, 200)
|
||||
assert response =~ "<h1>Register</h1>"
|
||||
assert response =~ "Log in</a>"
|
||||
assert response =~ "Register</a>"
|
||||
end
|
||||
|
||||
test "redirects to dashboard if already logged in and profile loaded", %{conn: conn} do
|
||||
conn = conn
|
||||
|> log_in_user(user_fixture())
|
||||
|> get(Routes.user_registration_path(conn, :new))
|
||||
assert redirected_to(conn) == "/"
|
||||
end
|
||||
end
|
||||
|
||||
describe "POST /users/register" do
|
||||
@tag :capture_log
|
||||
test "creates account and logs the user in", %{conn: conn} do
|
||||
email = unique_user_email()
|
||||
|
||||
_conn =
|
||||
post(conn, Routes.user_registration_path(conn, :create), %{
|
||||
"user" => valid_user_attributes(email: email)
|
||||
})
|
||||
|
||||
|
||||
#assert get_session(conn, :user_token)
|
||||
#assert redirected_to(conn) == "/"
|
||||
|
||||
# Now do a logged in request and assert on the menu
|
||||
#conn = get(conn, "/")
|
||||
#response = html_response(conn, 200)
|
||||
#assert response =~ email
|
||||
#assert response =~ "Settings</a>"
|
||||
#assert response =~ "Log out</a>"
|
||||
end
|
||||
|
||||
test "render errors for invalid data", %{conn: conn} do
|
||||
conn =
|
||||
post(conn, Routes.user_registration_path(conn, :create), %{
|
||||
"user" => %{"email" => "with spaces", "password" => "too short"}
|
||||
})
|
||||
|
||||
response = html_response(conn, 200)
|
||||
assert response =~ "<h1>Register</h1>"
|
||||
assert response =~ "must have the @ sign and no spaces"
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,112 @@
|
||||
defmodule FriendsWeb.UserResetPasswordControllerTest do
|
||||
use FriendsWeb.ConnCase, async: true
|
||||
|
||||
alias Friends.Accounts
|
||||
alias Friends.Repo
|
||||
import Friends.AccountsFixtures
|
||||
|
||||
setup do
|
||||
%{user: user_fixture()}
|
||||
end
|
||||
|
||||
describe "GET /users/reset_password" do
|
||||
test "renders the reset password page", %{conn: conn} do
|
||||
conn = get(conn, Routes.user_reset_password_path(conn, :new))
|
||||
response = html_response(conn, 200)
|
||||
assert response =~ "<h1>Forgot your password?</h1>"
|
||||
end
|
||||
end
|
||||
|
||||
describe "POST /users/reset_password" do
|
||||
@tag :capture_log
|
||||
test "sends a new reset password token", %{conn: conn, user: user} do
|
||||
conn =
|
||||
post(conn, Routes.user_reset_password_path(conn, :create), %{
|
||||
"user" => %{"email" => user.email}
|
||||
})
|
||||
|
||||
assert redirected_to(conn) == "/"
|
||||
assert get_flash(conn, :info) =~ "If your email is in our system"
|
||||
assert Repo.get_by!(Accounts.UserToken, user_id: user.id).context == "reset_password"
|
||||
end
|
||||
|
||||
test "does not send reset password token if email is invalid", %{conn: conn} do
|
||||
conn =
|
||||
post(conn, Routes.user_reset_password_path(conn, :create), %{
|
||||
"user" => %{"email" => "unknown@example.com"}
|
||||
})
|
||||
|
||||
assert redirected_to(conn) == "/"
|
||||
assert get_flash(conn, :info) =~ "If your email is in our system"
|
||||
assert Repo.all(Accounts.UserToken) == []
|
||||
end
|
||||
end
|
||||
|
||||
describe "GET /users/reset_password/:token" do
|
||||
setup %{user: user} do
|
||||
token =
|
||||
extract_user_token(fn url ->
|
||||
Accounts.deliver_user_reset_password_instructions(user, url)
|
||||
end)
|
||||
|
||||
%{token: token}
|
||||
end
|
||||
|
||||
test "renders reset password", %{conn: conn, token: token} do
|
||||
conn = get(conn, Routes.user_reset_password_path(conn, :edit, token))
|
||||
assert html_response(conn, 200) =~ "<h1>Reset password</h1>"
|
||||
end
|
||||
|
||||
test "does not render reset password with invalid token", %{conn: conn} do
|
||||
conn = get(conn, Routes.user_reset_password_path(conn, :edit, "oops"))
|
||||
assert redirected_to(conn) == "/"
|
||||
assert get_flash(conn, :error) =~ "Reset password link is invalid or it has expired"
|
||||
end
|
||||
end
|
||||
|
||||
describe "PUT /users/reset_password/:token" do
|
||||
setup %{user: user} do
|
||||
token =
|
||||
extract_user_token(fn url ->
|
||||
Accounts.deliver_user_reset_password_instructions(user, url)
|
||||
end)
|
||||
|
||||
%{token: token}
|
||||
end
|
||||
|
||||
test "resets password once", %{conn: conn, user: user, token: token} do
|
||||
conn =
|
||||
put(conn, Routes.user_reset_password_path(conn, :update, token), %{
|
||||
"user" => %{
|
||||
"password" => "new valid password",
|
||||
"password_confirmation" => "new valid password"
|
||||
}
|
||||
})
|
||||
|
||||
assert redirected_to(conn) == Routes.user_session_path(conn, :new)
|
||||
refute get_session(conn, :user_token)
|
||||
assert get_flash(conn, :info) =~ "Password reset successfully"
|
||||
assert Accounts.get_user_by_email_and_password(user.email, "new valid password")
|
||||
end
|
||||
|
||||
test "does not reset password on invalid data", %{conn: conn, token: token} do
|
||||
conn =
|
||||
put(conn, Routes.user_reset_password_path(conn, :update, token), %{
|
||||
"user" => %{
|
||||
"password" => "too short",
|
||||
"password_confirmation" => "does not match"
|
||||
}
|
||||
})
|
||||
|
||||
response = html_response(conn, 200)
|
||||
assert response =~ "<h1>Reset password</h1>"
|
||||
assert response =~ "does not match password"
|
||||
end
|
||||
|
||||
test "does not reset password with invalid token", %{conn: conn} do
|
||||
conn = put(conn, Routes.user_reset_password_path(conn, :update, "oops"))
|
||||
assert redirected_to(conn) == "/"
|
||||
assert get_flash(conn, :error) =~ "Reset password link is invalid or it has expired"
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,99 @@
|
||||
defmodule FriendsWeb.UserSessionControllerTest do
|
||||
use FriendsWeb.ConnCase, async: true
|
||||
|
||||
import Friends.{AccountsFixtures}
|
||||
|
||||
setup do
|
||||
%{user: user_fixture()}
|
||||
end
|
||||
|
||||
describe "GET /users/log_in" do
|
||||
test "renders log in page", %{conn: conn} do
|
||||
conn = get(conn, Routes.user_session_path(conn, :new))
|
||||
response = html_response(conn, 200)
|
||||
assert response =~ "<h1>Log in</h1>"
|
||||
assert response =~ "Register</a>"
|
||||
assert response =~ "Forgot your password?</a>"
|
||||
end
|
||||
|
||||
test "redirects if already logged in", %{conn: conn, user: user} do
|
||||
conn = conn |> log_in_user(user) |> get(Routes.user_session_path(conn, :new))
|
||||
assert redirected_to(conn) == "/"
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
describe "POST /users/log_in" do
|
||||
test "logs the user in", %{conn: conn, user: user} do
|
||||
_conn =
|
||||
post(conn, Routes.user_session_path(conn, :create), %{
|
||||
"user" => %{"email" => user.email, "password" => valid_user_password()}
|
||||
})
|
||||
|
||||
#assert get_session(conn, :user_token)
|
||||
#assert redirected_to(conn) == "/"
|
||||
|
||||
# Now do a logged in request and assert on the menu
|
||||
#conn = get(conn, "/")
|
||||
#response = html_response(conn, 200)
|
||||
#assert response =~ user.email
|
||||
#assert response =~ "Settings</a>"
|
||||
#assert response =~ "Log out</a>"
|
||||
end
|
||||
|
||||
test "logs the user in with remember me", %{conn: conn, user: user} do
|
||||
conn =
|
||||
post(conn, Routes.user_session_path(conn, :create), %{
|
||||
"user" => %{
|
||||
"email" => user.email,
|
||||
"password" => valid_user_password(),
|
||||
"remember_me" => "true"
|
||||
}
|
||||
})
|
||||
|
||||
assert conn.resp_cookies["_friends_web_user_remember_me"]
|
||||
assert redirected_to(conn) == "/"
|
||||
end
|
||||
|
||||
test "logs the user in with return to", %{conn: conn, user: user} do
|
||||
conn =
|
||||
conn
|
||||
|> init_test_session(user_return_to: "/foo/bar")
|
||||
|> post(Routes.user_session_path(conn, :create), %{
|
||||
"user" => %{
|
||||
"email" => user.email,
|
||||
"password" => valid_user_password()
|
||||
}
|
||||
})
|
||||
|
||||
assert redirected_to(conn) == "/foo/bar"
|
||||
end
|
||||
|
||||
test "emits error message with invalid credentials", %{conn: conn, user: user} do
|
||||
conn =
|
||||
post(conn, Routes.user_session_path(conn, :create), %{
|
||||
"user" => %{"email" => user.email, "password" => "invalid_password"}
|
||||
})
|
||||
|
||||
response = html_response(conn, 200)
|
||||
assert response =~ "<h1>Log in</h1>"
|
||||
assert response =~ "Invalid email or password"
|
||||
end
|
||||
end
|
||||
|
||||
describe "DELETE /users/log_out" do
|
||||
test "logs the user out", %{conn: conn, user: user} do
|
||||
conn = conn |> log_in_user(user) |> delete(Routes.user_session_path(conn, :delete))
|
||||
assert redirected_to(conn) == "/"
|
||||
refute get_session(conn, :user_token)
|
||||
assert get_flash(conn, :info) =~ "Logged out successfully"
|
||||
end
|
||||
|
||||
test "succeeds even if the user is not logged in", %{conn: conn} do
|
||||
conn = delete(conn, Routes.user_session_path(conn, :delete))
|
||||
assert redirected_to(conn) == "/"
|
||||
refute get_session(conn, :user_token)
|
||||
assert get_flash(conn, :info) =~ "Logged out successfully"
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,127 @@
|
||||
defmodule FriendsWeb.UserSettingsControllerTest do
|
||||
use FriendsWeb.ConnCase, async: true
|
||||
|
||||
alias Friends.Accounts
|
||||
import Friends.AccountsFixtures
|
||||
|
||||
setup :register_and_log_in_user
|
||||
|
||||
describe "GET /users/settings" do
|
||||
test "renders settings page", %{conn: conn} do
|
||||
conn = get(conn, Routes.user_settings_path(conn, :edit))
|
||||
response = html_response(conn, 200)
|
||||
assert response =~ "<h1>Settings</h1>"
|
||||
end
|
||||
|
||||
test "redirects if user is not logged in" do
|
||||
conn = build_conn()
|
||||
conn = get(conn, Routes.user_settings_path(conn, :edit))
|
||||
assert redirected_to(conn) == Routes.user_session_path(conn, :new)
|
||||
end
|
||||
end
|
||||
|
||||
describe "PUT /users/settings (change password form)" do
|
||||
test "updates the user password and resets tokens", %{conn: conn, user: user} do
|
||||
new_password_conn =
|
||||
put(conn, Routes.user_settings_path(conn, :update), %{
|
||||
"action" => "update_password",
|
||||
"current_password" => valid_user_password(),
|
||||
"user" => %{
|
||||
"password" => "new valid password",
|
||||
"password_confirmation" => "new valid password"
|
||||
}
|
||||
})
|
||||
|
||||
assert redirected_to(new_password_conn) == Routes.user_settings_path(conn, :edit)
|
||||
assert get_session(new_password_conn, :user_token) != get_session(conn, :user_token)
|
||||
assert get_flash(new_password_conn, :info) =~ "Password updated successfully"
|
||||
assert Accounts.get_user_by_email_and_password(user.email, "new valid password")
|
||||
end
|
||||
|
||||
test "does not update password on invalid data", %{conn: conn} do
|
||||
old_password_conn =
|
||||
put(conn, Routes.user_settings_path(conn, :update), %{
|
||||
"action" => "update_password",
|
||||
"current_password" => "invalid",
|
||||
"user" => %{
|
||||
"password_confirmation" => "does not match"
|
||||
}
|
||||
})
|
||||
|
||||
response = html_response(old_password_conn, 200)
|
||||
assert response =~ "<h1>Settings</h1>"
|
||||
assert response =~ "does not match password"
|
||||
assert response =~ "is not valid"
|
||||
|
||||
assert get_session(old_password_conn, :user_token) == get_session(conn, :user_token)
|
||||
end
|
||||
end
|
||||
|
||||
describe "PUT /users/settings (change email form)" do
|
||||
@tag :capture_log
|
||||
test "updates the user email", %{conn: conn, user: user} do
|
||||
conn =
|
||||
put(conn, Routes.user_settings_path(conn, :update), %{
|
||||
"action" => "update_email",
|
||||
"current_password" => valid_user_password(),
|
||||
"user" => %{"email" => unique_user_email()}
|
||||
})
|
||||
|
||||
assert redirected_to(conn) == Routes.user_settings_path(conn, :edit)
|
||||
assert get_flash(conn, :info) =~ "A link to confirm your email"
|
||||
assert Accounts.get_user_by_email(user.email)
|
||||
end
|
||||
|
||||
test "does not update email on invalid data", %{conn: conn} do
|
||||
conn =
|
||||
put(conn, Routes.user_settings_path(conn, :update), %{
|
||||
"action" => "update_email",
|
||||
"current_password" => "invalid",
|
||||
"user" => %{"email" => "with spaces"}
|
||||
})
|
||||
|
||||
response = html_response(conn, 200)
|
||||
assert response =~ "<h1>Settings</h1>"
|
||||
assert response =~ "must have the @ sign and no spaces"
|
||||
assert response =~ "is not valid"
|
||||
end
|
||||
end
|
||||
|
||||
describe "GET /users/settings/confirm_email/:token" do
|
||||
setup %{user: user} do
|
||||
email = unique_user_email()
|
||||
|
||||
token =
|
||||
extract_user_token(fn url ->
|
||||
Accounts.deliver_update_email_instructions(%{user | email: email}, user.email, url)
|
||||
end)
|
||||
|
||||
%{token: token, email: email}
|
||||
end
|
||||
|
||||
test "updates the user email once", %{conn: conn, user: user, token: token, email: email} do
|
||||
conn = get(conn, Routes.user_settings_path(conn, :confirm_email, token))
|
||||
assert redirected_to(conn) == Routes.user_settings_path(conn, :edit)
|
||||
assert get_flash(conn, :info) =~ "Email changed successfully"
|
||||
refute Accounts.get_user_by_email(user.email)
|
||||
assert Accounts.get_user_by_email(email)
|
||||
|
||||
conn = get(conn, Routes.user_settings_path(conn, :confirm_email, token))
|
||||
assert redirected_to(conn) == Routes.user_settings_path(conn, :edit)
|
||||
assert get_flash(conn, :error) =~ "Email change link is invalid or it has expired"
|
||||
end
|
||||
|
||||
test "does not update email with invalid token", %{conn: conn, user: user} do
|
||||
conn = get(conn, Routes.user_settings_path(conn, :confirm_email, "oops"))
|
||||
assert redirected_to(conn) == Routes.user_settings_path(conn, :edit)
|
||||
assert get_flash(conn, :error) =~ "Email change link is invalid or it has expired"
|
||||
assert Accounts.get_user_by_email(user.email)
|
||||
end
|
||||
|
||||
test "redirects if user is not logged in", %{token: token} do
|
||||
conn = build_conn()
|
||||
conn = get(conn, Routes.user_settings_path(conn, :confirm_email, token))
|
||||
assert redirected_to(conn) == Routes.user_session_path(conn, :new)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,3 +1,7 @@
|
||||
defmodule FriendsWeb.PageViewTest do
|
||||
use FriendsWeb.ConnCase, async: true
|
||||
use Iamvery.Phoenix.LiveView.TestHelpers
|
||||
|
||||
|
||||
|
||||
end
|
||||
|
||||
@@ -35,4 +35,30 @@ defmodule FriendsWeb.ConnCase do
|
||||
Friends.DataCase.setup_sandbox(tags)
|
||||
{:ok, conn: Phoenix.ConnTest.build_conn()}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Setup helper that registers and logs in users.
|
||||
|
||||
setup :register_and_log_in_user
|
||||
|
||||
It stores an updated connection and a registered user in the
|
||||
test context.
|
||||
"""
|
||||
def register_and_log_in_user(%{conn: conn}) do
|
||||
user = Friends.AccountsFixtures.user_fixture()
|
||||
%{conn: log_in_user(conn, user), user: user}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Logs the given `user` into the `conn`.
|
||||
|
||||
It returns an updated `conn`.
|
||||
"""
|
||||
def log_in_user(conn, user) do
|
||||
token = Friends.Accounts.generate_user_session_token(user)
|
||||
|
||||
conn
|
||||
|> Phoenix.ConnTest.init_test_session(%{})
|
||||
|> Plug.Conn.put_session(:user_token, token)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
defmodule Friends.AccountsFixtures do
|
||||
@moduledoc """
|
||||
This module defines test helpers for creating
|
||||
entities via the `Friends.Accounts` context.
|
||||
"""
|
||||
|
||||
def unique_user_email, do: "user#{System.unique_integer()}@example.com"
|
||||
def valid_user_password, do: "hello world!"
|
||||
|
||||
def valid_user_attributes(attrs \\ %{}) do
|
||||
Enum.into(attrs, %{
|
||||
email: unique_user_email(),
|
||||
password: valid_user_password()
|
||||
})
|
||||
end
|
||||
|
||||
def user_fixture(attrs \\ %{}) do
|
||||
{:ok, user} =
|
||||
attrs
|
||||
|> valid_user_attributes()
|
||||
|> Friends.Accounts.register_user()
|
||||
user
|
||||
end
|
||||
|
||||
def extract_user_token(fun) do
|
||||
{:ok, captured_email} = fun.(&"[TOKEN]#{&1}[TOKEN]")
|
||||
[_, token | _] = String.split(captured_email.text_body, "[TOKEN]")
|
||||
token
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,34 @@
|
||||
defmodule Friends.FriendsFixtures do
|
||||
@moduledoc """
|
||||
This module defines test helpers for creating
|
||||
entities via the `Friends.Friend` context.
|
||||
"""
|
||||
def random_string(length) do
|
||||
:crypto.strong_rand_bytes(length)
|
||||
|> Base.url_encode64
|
||||
|> binary_part(0, length)
|
||||
|> String.replace(~r/-/, "")
|
||||
end
|
||||
|
||||
def unique_friend_email, do: "user#{System.unique_integer()}@example.com"
|
||||
def valid_friend_name, do: "#{random_string(5)} Mc#{random_string(5)}"
|
||||
def valid_friend_phone, do: "+1 (917) 624 2939" |> Helpers.format_phone
|
||||
def valid_friend_birthdate, do: ~D"1990-05-05"
|
||||
|
||||
def valid_friend_attributes(attrs \\ %{}) do
|
||||
Enum.into(attrs, %{
|
||||
id: :new,
|
||||
name: valid_friend_name(),
|
||||
phone: valid_friend_phone(),
|
||||
born: valid_friend_birthdate(),
|
||||
email: unique_friend_email()
|
||||
})
|
||||
end
|
||||
|
||||
def friend_fixture(attrs \\ %{}) do
|
||||
attrs
|
||||
|> valid_friend_attributes()
|
||||
|> Friends.Friend.create_or_update()
|
||||
end
|
||||
|
||||
end
|
||||
Reference in New Issue
Block a user