├── assets
├── css
│ └── app.css
├── static
│ ├── favicon.ico
│ ├── images
│ │ └── phoenix.png
│ └── robots.txt
├── package.json
├── js
│ ├── app.js
│ └── socket.js
└── brunch-config.js
├── test
├── test_helper.exs
├── coherence_demo_web
│ ├── views
│ │ ├── page_view_test.exs
│ │ ├── layout_view_test.exs
│ │ └── error_view_test.exs
│ └── controllers
│ │ ├── page_controller_test.exs
│ │ └── post_controller_test.exs
├── support
│ ├── channel_case.ex
│ ├── conn_case.ex
│ └── data_case.ex
└── coherence_demo
│ └── blogs
│ └── blogs_test.exs
├── lib
├── coherence_demo_web
│ ├── views
│ │ ├── page_view.ex
│ │ ├── post_view.ex
│ │ ├── layout_view.ex
│ │ ├── coherence
│ │ │ ├── coherence_view.ex
│ │ │ ├── email_view.ex
│ │ │ ├── layout_view.ex
│ │ │ ├── session_view.ex
│ │ │ ├── unlock_view.ex
│ │ │ ├── invitation_view.ex
│ │ │ ├── password_view.ex
│ │ │ ├── confirmation_view.ex
│ │ │ ├── registration_view.ex
│ │ │ └── coherence_view_helpers.ex
│ │ ├── user_view.ex
│ │ ├── error_view.ex
│ │ └── error_helpers.ex
│ ├── controllers
│ │ ├── page_controller.ex
│ │ ├── coherence
│ │ │ └── redirects.ex
│ │ ├── post_controller.ex
│ │ └── user_controller.ex
│ ├── templates
│ │ ├── post
│ │ │ ├── new.html.eex
│ │ │ ├── edit.html.eex
│ │ │ ├── show.html.eex
│ │ │ ├── form.html.eex
│ │ │ └── index.html.eex
│ │ ├── coherence
│ │ │ ├── layout
│ │ │ │ └── email.html.eex
│ │ │ ├── registration
│ │ │ │ ├── edit.html.eex
│ │ │ │ ├── new.html.eex
│ │ │ │ ├── show.html.eex
│ │ │ │ └── form.html.eex
│ │ │ ├── email
│ │ │ │ ├── confirmation.html.eex
│ │ │ │ ├── invitation.html.eex
│ │ │ │ ├── unlock.html.eex
│ │ │ │ └── password.html.eex
│ │ │ ├── password
│ │ │ │ ├── new.html.eex
│ │ │ │ └── edit.html.eex
│ │ │ ├── confirmation
│ │ │ │ └── new.html.eex
│ │ │ ├── unlock
│ │ │ │ └── new.html.eex
│ │ │ ├── invitation
│ │ │ │ ├── new.html.eex
│ │ │ │ └── edit.html.eex
│ │ │ └── session
│ │ │ │ └── new.html.eex
│ │ ├── user
│ │ │ ├── new.html.eex
│ │ │ ├── edit.html.eex
│ │ │ ├── index.html.eex
│ │ │ ├── show.html.eex
│ │ │ └── form.html.eex
│ │ ├── page
│ │ │ └── index.html.eex
│ │ └── layout
│ │ │ └── app.html.eex
│ ├── emails
│ │ └── coherence
│ │ │ ├── coherence_mailer.ex
│ │ │ └── user_email.ex
│ ├── gettext.ex
│ ├── channels
│ │ └── user_socket.ex
│ ├── coherence_web.ex
│ ├── router.ex
│ ├── endpoint.ex
│ └── coherence_messages.ex
├── coherence_demo.ex
├── coherence_demo
│ ├── repo.ex
│ ├── blogs
│ │ ├── post.ex
│ │ └── blogs.ex
│ ├── coherence
│ │ ├── user.ex
│ │ ├── invitation.ex
│ │ ├── rememberable.ex
│ │ └── schemas.ex
│ └── application.ex
└── coherence_demo_web.ex
├── priv
├── repo
│ ├── seeds.exs
│ └── migrations
│ │ ├── 20170803154232_create_posts.exs
│ │ ├── 20170803154909_create_coherence_invitable.exs
│ │ ├── 20170803154910_create_coherence_rememberable.exs
│ │ └── 20170803154908_create_coherence_user.exs
└── gettext
│ ├── en
│ └── LC_MESSAGES
│ │ └── errors.po
│ └── errors.pot
├── config
├── test.exs
├── config.exs
├── dev.exs
└── prod.exs
├── .gitignore
├── README.md
├── mix.exs
└── mix.lock
/assets/css/app.css:
--------------------------------------------------------------------------------
1 | /* This file is for your main application css. */
--------------------------------------------------------------------------------
/assets/static/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/smpallen99/coherence_demo/master/assets/static/favicon.ico
--------------------------------------------------------------------------------
/test/test_helper.exs:
--------------------------------------------------------------------------------
1 | ExUnit.start()
2 |
3 | Ecto.Adapters.SQL.Sandbox.mode(CoherenceDemo.Repo, :manual)
4 |
5 |
--------------------------------------------------------------------------------
/assets/static/images/phoenix.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/smpallen99/coherence_demo/master/assets/static/images/phoenix.png
--------------------------------------------------------------------------------
/lib/coherence_demo_web/views/page_view.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.PageView do
2 | use CoherenceDemoWeb, :view
3 | end
4 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/views/post_view.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.PostView do
2 | use CoherenceDemoWeb, :view
3 | end
4 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/views/layout_view.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.LayoutView do
2 | use CoherenceDemoWeb, :view
3 | end
4 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/views/coherence/coherence_view.ex:
--------------------------------------------------------------------------------
1 | defmodule Coherence.CoherenceView do
2 | use CoherenceDemoWeb.Coherence, :view
3 | end
4 |
--------------------------------------------------------------------------------
/test/coherence_demo_web/views/page_view_test.exs:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.PageViewTest do
2 | use CoherenceDemoWeb.ConnCase, async: true
3 | end
4 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/views/coherence/email_view.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.Coherence.EmailView do
2 | use CoherenceDemoWeb.Coherence, :view
3 | end
4 |
--------------------------------------------------------------------------------
/test/coherence_demo_web/views/layout_view_test.exs:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.LayoutViewTest do
2 | use CoherenceDemoWeb.ConnCase, async: true
3 | end
4 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/views/coherence/layout_view.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.Coherence.LayoutView do
2 | use CoherenceDemoWeb.Coherence, :view
3 | end
4 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/views/coherence/session_view.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.Coherence.SessionView do
2 | use CoherenceDemoWeb.Coherence, :view
3 | end
4 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/views/coherence/unlock_view.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.Coherence.UnlockView do
2 | use CoherenceDemoWeb.Coherence, :view
3 | end
4 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/views/coherence/invitation_view.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.Coherence.InvitationView do
2 | use CoherenceDemoWeb.Coherence, :view
3 | end
4 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/views/coherence/password_view.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.Coherence.PasswordView do
2 | use CoherenceDemoWeb.Coherence, :view
3 | end
4 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/views/coherence/confirmation_view.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.Coherence.ConfirmationView do
2 | use CoherenceDemoWeb.Coherence, :view
3 | end
4 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/views/coherence/registration_view.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.Coherence.RegistrationView do
2 | use CoherenceDemoWeb.Coherence, :view
3 | end
4 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/views/user_view.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.UserView do
2 | use CoherenceDemoWeb, :view
3 | alias CoherenceDemo.Coherence.User
4 |
5 | end
6 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/controllers/page_controller.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.PageController do
2 | use CoherenceDemoWeb, :controller
3 |
4 | def index(conn, _params) do
5 | render conn, "index.html"
6 | end
7 | end
8 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/post/new.html.eex:
--------------------------------------------------------------------------------
1 |
New Post
2 |
3 | <%= render "form.html", Map.put(assigns, :action, post_path(@conn, :create)) %>
4 |
5 | <%= link "Back", to: post_path(@conn, :index) %>
6 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/emails/coherence/coherence_mailer.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.Coherence.Mailer do
2 | @moduledoc false
3 | if Coherence.Config.mailer?() do
4 | use Swoosh.Mailer, otp_app: :coherence
5 | end
6 | end
7 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/post/edit.html.eex:
--------------------------------------------------------------------------------
1 | Edit Post
2 |
3 | <%= render "form.html", Map.put(assigns, :action, post_path(@conn, :update, @post)) %>
4 |
5 | <%= link "Back", to: post_path(@conn, :index) %>
6 |
--------------------------------------------------------------------------------
/assets/static/robots.txt:
--------------------------------------------------------------------------------
1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file
2 | #
3 | # To ban all spiders from the entire site uncomment the next two lines:
4 | # User-agent: *
5 | # Disallow: /
6 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/coherence/layout/email.html.eex:
--------------------------------------------------------------------------------
1 |
2 |
3 | <%= @email.subject %>
4 |
5 |
6 | <%= render @view_module, @view_template, assigns %>
7 |
8 |
9 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/user/new.html.eex:
--------------------------------------------------------------------------------
1 | New user
2 |
3 | <%= render "form.html", changeset: @changeset,
4 | action: user_path(@conn, :create) %>
5 |
6 | <%= link "Back", to: user_path(@conn, :index) %>
7 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/user/edit.html.eex:
--------------------------------------------------------------------------------
1 | Edit user
2 |
3 | <%= render "form.html", changeset: @changeset,
4 | action: user_path(@conn, :update, @user) %>
5 |
6 | <%= link "Back", to: user_path(@conn, :index) %>
7 |
--------------------------------------------------------------------------------
/test/coherence_demo_web/controllers/page_controller_test.exs:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.PageControllerTest do
2 | use CoherenceDemoWeb.ConnCase
3 |
4 | test "GET /", %{conn: conn} do
5 | conn = get conn, "/"
6 | assert html_response(conn, 200) =~ "Welcome to Phoenix!"
7 | end
8 | end
9 |
--------------------------------------------------------------------------------
/lib/coherence_demo.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemo do
2 | @moduledoc """
3 | CoherenceDemo keeps the contexts that define your domain
4 | and business logic.
5 |
6 | Contexts are also responsible for managing your data, regardless
7 | if it comes from the database, an external API or others.
8 | """
9 | end
10 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/coherence/registration/edit.html.eex:
--------------------------------------------------------------------------------
1 | <%= dgettext "coherence", "Edit Account" %>
2 |
3 | <%= render "form.html", changeset: @changeset,
4 | label: dgettext("coherence", "Update"), required: [],
5 | action: registration_path(@conn, :update) %>
6 |
--------------------------------------------------------------------------------
/priv/repo/seeds.exs:
--------------------------------------------------------------------------------
1 | CoherenceDemo.Repo.delete_all CoherenceDemo.Coherence.User
2 |
3 | CoherenceDemo.Coherence.User.changeset(%CoherenceDemo.Coherence.User{}, %{name: "Demo User", email: "demouser@example.com", password: "secret", password_confirmation: "secret"})
4 | |> CoherenceDemo.Repo.insert!
5 | |> Coherence.Controller.confirm!
6 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/coherence/registration/new.html.eex:
--------------------------------------------------------------------------------
1 | <%= dgettext "coherence", "Register Account" %>
2 |
3 | <%= render "form.html", changeset: @changeset,
4 | label: dgettext("coherence", "Register"), required: [required: ""],
5 | action: registration_path(@conn, :create) %>
6 |
--------------------------------------------------------------------------------
/lib/coherence_demo/repo.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemo.Repo do
2 | use Ecto.Repo, otp_app: :coherence_demo
3 |
4 | @doc """
5 | Dynamically loads the repository url from the
6 | DATABASE_URL environment variable.
7 | """
8 | def init(_, opts) do
9 | {:ok, Keyword.put(opts, :url, System.get_env("DATABASE_URL"))}
10 | end
11 | end
12 |
--------------------------------------------------------------------------------
/priv/repo/migrations/20170803154232_create_posts.exs:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemo.Repo.Migrations.CreatePosts do
2 | use Ecto.Migration
3 |
4 | def change do
5 | create table(:posts, primary_key: false) do
6 | add :id, :binary_id, primary_key: true
7 | add :title, :string
8 | add :body, :text
9 |
10 | timestamps()
11 | end
12 |
13 | end
14 | end
15 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/post/show.html.eex:
--------------------------------------------------------------------------------
1 | Show Post
2 |
3 |
4 |
5 |
6 | Title:
7 | <%= @post.title %>
8 |
9 |
10 |
11 | Body:
12 | <%= @post.body %>
13 |
14 |
15 |
16 |
17 | <%= link "Edit", to: post_path(@conn, :edit, @post) %>
18 | <%= link "Back", to: post_path(@conn, :index) %>
19 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/coherence/email/confirmation.html.eex:
--------------------------------------------------------------------------------
1 |
2 |
<%= dgettext "coherence", "Hello %{name}!", name: @name %>
3 |
4 | <%= dgettext "coherence", "Your new account is almost ready. Click the link below to confirm you new account." %>
5 |
6 |
7 | <%= dgettext "coherence", "Confirm my Account" %>
8 |
9 |
<%= dgettext "coherence", "Thank you!" %>
10 |
11 |
12 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/coherence/email/invitation.html.eex:
--------------------------------------------------------------------------------
1 |
2 |
<%= dgettext "coherence", "Hello %{name}!", name: @name %>
3 |
4 | <%= dgettext "coherence", "You have been invited to create an Account. Use the link below to create an account." %>
5 |
6 |
7 | <%= dgettext "coherence", "Create my Account" %>
8 |
9 |
<%= dgettext "coherence", "Thank you!" %>
10 |
11 |
12 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/coherence/email/unlock.html.eex:
--------------------------------------------------------------------------------
1 |
2 |
<%= dgettext "coherence", "Hello %{name}!", name: @name %>
3 |
4 | <%= dgettext "coherence", "You requested unlock instructions for your locked account. Please click the link below to unlock your account." %>
5 |
6 |
7 | <%= dgettext "coherence", "Unlock my Account" %>
8 |
9 |
<%= dgettext "coherence", "Thank you!" %>
10 |
11 |
12 |
--------------------------------------------------------------------------------
/assets/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "repository": {},
3 | "license": "MIT",
4 | "scripts": {
5 | "deploy": "brunch build --production",
6 | "watch": "brunch watch --stdin"
7 | },
8 | "dependencies": {
9 | "phoenix": "file:../deps/phoenix",
10 | "phoenix_html": "file:../deps/phoenix_html"
11 | },
12 | "devDependencies": {
13 | "babel-brunch": "6.1.1",
14 | "brunch": "2.10.9",
15 | "clean-css-brunch": "2.10.0",
16 | "uglify-js-brunch": "2.10.0"
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/views/error_view.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.ErrorView do
2 | use CoherenceDemoWeb, :view
3 |
4 | def render("404.html", _assigns) do
5 | "Page not found"
6 | end
7 |
8 | def render("500.html", _assigns) do
9 | "Internal server error"
10 | end
11 |
12 | # In case no render clause matches or no
13 | # template is found, let's render it as 500
14 | def template_not_found(_template, assigns) do
15 | render "500.html", assigns
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/priv/repo/migrations/20170803154909_create_coherence_invitable.exs:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemo.Repo.Migrations.CreateCoherenceInvitable do
2 | use Ecto.Migration
3 | def change do
4 | create table(:invitations, primary_key: false) do
5 | add :id, :binary_id, primary_key: true
6 |
7 | add :name, :string
8 | add :email, :string
9 | add :token, :string
10 | timestamps()
11 | end
12 | create unique_index(:invitations, [:email])
13 | create index(:invitations, [:token])
14 |
15 | end
16 | end
17 |
--------------------------------------------------------------------------------
/lib/coherence_demo/blogs/post.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemo.Blogs.Post do
2 | use Ecto.Schema
3 | import Ecto.Changeset
4 | alias CoherenceDemo.Blogs.Post
5 |
6 |
7 | @primary_key {:id, :binary_id, autogenerate: true}
8 | @foreign_key_type :binary_id
9 | schema "posts" do
10 | field :body, :string
11 | field :title, :string
12 |
13 | timestamps()
14 | end
15 |
16 | @doc false
17 | def changeset(%Post{} = post, attrs) do
18 | post
19 | |> cast(attrs, [:title, :body])
20 | |> validate_required([:title, :body])
21 | end
22 | end
23 |
--------------------------------------------------------------------------------
/config/test.exs:
--------------------------------------------------------------------------------
1 | use Mix.Config
2 |
3 | # We don't run a server during test. If one is required,
4 | # you can enable the server option below.
5 | config :coherence_demo, CoherenceDemoWeb.Endpoint,
6 | http: [port: 4001],
7 | server: false
8 |
9 | # Print only warnings and errors during test
10 | config :logger, level: :warn
11 |
12 | # Configure your database
13 | config :coherence_demo, CoherenceDemo.Repo,
14 | adapter: Ecto.Adapters.Postgres,
15 | username: "postgres",
16 | password: "postgres",
17 | database: "coherence_demo_test",
18 | hostname: "localhost",
19 | pool: Ecto.Adapters.SQL.Sandbox
20 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/coherence/email/password.html.eex:
--------------------------------------------------------------------------------
1 |
2 |
<%= dgettext "coherence", "Hello %{name}!", name: @name %>
3 |
4 | <%= dgettext "coherence", "Someone has requested a link to change your password, and you can do this through the link below." %>
5 |
6 |
7 | <%= dgettext "coherence", "Change my password" %>
8 |
9 |
10 | <%= dgettext "coherence", "If you didn't request this, please ignore this email." %>
11 |
12 |
13 | <%= dgettext "coherence", "Your password won't change until you access the link above and create a new one." %>
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/page/index.html.eex:
--------------------------------------------------------------------------------
1 |
2 |
<%= gettext "Welcome to %{name}!", name: "Coherence" %>
3 |
An full-featured authentication package
4 |
5 |
6 |
22 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/coherence/password/new.html.eex:
--------------------------------------------------------------------------------
1 |
2 |
3 | <%= dgettext "coherence", "Send reset password link" %>
4 |
5 | <%= form_for @changeset, password_path(@conn, :create), [as: :password], fn f -> %>
6 |
7 |
8 | <%= required_label f, :email, class: "control-label" %>
9 | <%= text_input f, :email, class: "form-control", required: "" %>
10 | <%= error_tag f, :email %>
11 |
12 |
13 |
14 | <%= submit dgettext("coherence", "Reset Password"), class: "btn btn-primary" %>
15 | <%= link dgettext("coherence", "Cancel"), to: Coherence.Config.logged_out_url("/"), class: "btn" %>
16 |
17 | <% end %>
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # App artifacts
2 | /_build
3 | /db
4 | /deps
5 | /*.ez
6 |
7 | # Generated on crash by the VM
8 | erl_crash.dump
9 |
10 | # Generated on crash by NPM
11 | npm-debug.log
12 |
13 | # Static artifacts
14 | /assets/node_modules
15 |
16 | # Since we are building assets from assets/,
17 | # we ignore priv/static. You may want to comment
18 | # this depending on your deployment strategy.
19 | /priv/static/
20 |
21 | # Files matching config/*.secret.exs pattern contain sensitive
22 | # data and you should not commit them into version control.
23 | #
24 | # Alternatively, you may comment the line below and commit the
25 | # secrets files as long as you replace their contents by environment
26 | # variables.
27 | /config/*.secret.exs
--------------------------------------------------------------------------------
/test/coherence_demo_web/views/error_view_test.exs:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.ErrorViewTest do
2 | use CoherenceDemoWeb.ConnCase, async: true
3 |
4 | # Bring render/3 and render_to_string/3 for testing custom views
5 | import Phoenix.View
6 |
7 | test "renders 404.html" do
8 | assert render_to_string(CoherenceDemoWeb.ErrorView, "404.html", []) ==
9 | "Page not found"
10 | end
11 |
12 | test "render 500.html" do
13 | assert render_to_string(CoherenceDemoWeb.ErrorView, "500.html", []) ==
14 | "Internal server error"
15 | end
16 |
17 | test "render any other" do
18 | assert render_to_string(CoherenceDemoWeb.ErrorView, "505.html", []) ==
19 | "Internal server error"
20 | end
21 | end
22 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/coherence/confirmation/new.html.eex:
--------------------------------------------------------------------------------
1 |
2 |
3 | <%= dgettext "coherence", "Resend Confirmation Instructions" %>
4 |
5 | <%= form_for @changeset, confirmation_path(@conn, :create), [as: :confirmation], fn f -> %>
6 |
7 |
8 | <%= required_label f, dgettext("coherence", "Email"), class: "control-label" %>
9 | <%= text_input f, :email, class: "form-control", required: "" %>
10 | <%= error_tag f, :email %>
11 |
12 |
13 |
14 | <%= submit dgettext("coherence", "Resend Email"), class: "btn btn-primary" %>
15 | <%= link dgettext("coherence", "Cancel"), to: Coherence.Config.logged_out_url("/"), class: "btn" %>
16 |
17 | <% end %>
18 |
--------------------------------------------------------------------------------
/assets/js/app.js:
--------------------------------------------------------------------------------
1 | // Brunch automatically concatenates all files in your
2 | // watched paths. Those paths can be configured at
3 | // config.paths.watched in "brunch-config.js".
4 | //
5 | // However, those files will only be executed if
6 | // explicitly imported. The only exception are files
7 | // in vendor, which are never wrapped in imports and
8 | // therefore are always executed.
9 |
10 | // Import dependencies
11 | //
12 | // If you no longer want to use a dependency, remember
13 | // to also remove its path from "config.paths.watched".
14 | import "phoenix_html"
15 |
16 | // Import local files
17 | //
18 | // Local files can be imported directly using relative
19 | // paths "./socket" or full ones "web/static/js/socket".
20 |
21 | // import socket from "./socket"
22 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/post/form.html.eex:
--------------------------------------------------------------------------------
1 | <%= form_for @changeset, @action, fn f -> %>
2 | <%= if @changeset.action do %>
3 |
4 |
Oops, something went wrong! Please check the errors below.
5 |
6 | <% end %>
7 |
8 |
9 | <%= label f, :title, class: "control-label" %>
10 | <%= text_input f, :title, class: "form-control" %>
11 | <%= error_tag f, :title %>
12 |
13 |
14 |
15 | <%= label f, :body, class: "control-label" %>
16 | <%= textarea f, :body, class: "form-control" %>
17 | <%= error_tag f, :body %>
18 |
19 |
20 |
21 | <%= submit "Submit", class: "btn btn-primary" %>
22 |
23 | <% end %>
24 |
--------------------------------------------------------------------------------
/priv/repo/migrations/20170803154910_create_coherence_rememberable.exs:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemo.Repo.Migrations.CreateCoherenceRememberable do
2 | use Ecto.Migration
3 | def change do
4 | create table(:rememberables, primary_key: false) do
5 | add :id, :binary_id, primary_key: true
6 |
7 | add :series_hash, :string
8 | add :token_hash, :string
9 | add :token_created_at, :utc_datetime
10 | add :user_id, references(:users, on_delete: :delete_all, type: :binary_id)
11 |
12 | timestamps()
13 | end
14 | create index(:rememberables, [:user_id])
15 | create index(:rememberables, [:series_hash])
16 | create index(:rememberables, [:token_hash])
17 | create unique_index(:rememberables, [:user_id, :series_hash, :token_hash])
18 |
19 | end
20 | end
21 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/gettext.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.Gettext do
2 | @moduledoc """
3 | A module providing Internationalization with a gettext-based API.
4 |
5 | By using [Gettext](https://hexdocs.pm/gettext),
6 | your module gains a set of macros for translations, for example:
7 |
8 | import CoherenceDemoWeb.Gettext
9 |
10 | # Simple translation
11 | gettext "Here is the string to translate"
12 |
13 | # Plural translation
14 | ngettext "Here is the string to translate",
15 | "Here are the strings to translate",
16 | 3
17 |
18 | # Domain-based translation
19 | dgettext "errors", "Here is the error message to translate"
20 |
21 | See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
22 | """
23 | use Gettext, otp_app: :coherence_demo
24 | end
25 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/coherence/registration/show.html.eex:
--------------------------------------------------------------------------------
1 | <%= dgettext "coherence", "Show account" %>
2 |
3 |
4 | <%= dgettext "coherence", "Name:" %>
5 | <%= @user.name %>
6 |
7 | <%= unless (login_field = Coherence.Config.login_field) == :email do %>
8 |
9 | <%= humanize login_field %>
10 | <%= Map.get(@user, login_field) %>
11 |
12 | <% end %>
13 |
14 |
15 | <%= dgettext "coherence", "Email:" %>
16 | <%= @user.email %>
17 |
18 |
19 |
20 |
21 | <%= link dgettext("coherence", "Edit"), to: registration_path(@conn, :edit) %> |
22 | <%= link dgettext("coherence", "Delete"),
23 | to: registration_path(@conn, :delete),
24 | method: :delete,
25 | data: [confirm: dgettext("coherence", "Are you sure?")] %>
26 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/coherence/unlock/new.html.eex:
--------------------------------------------------------------------------------
1 |
2 |
3 | <%= form_for @conn, unlock_path(@conn, :create), [as: :unlock], fn f -> %>
4 |
5 |
6 | <%= required_label f, dgettext("coherence", "Email"), class: "control-label" %>
7 | <%= text_input f, :email, class: "form-control", required: "" %>
8 | <%= error_tag f, :email %>
9 |
10 |
11 |
12 | <%= required_label f, dgettext("coherence", "Password"), class: "control-label" %>
13 | <%= password_input f, :password, class: "form-control", required: "" %>
14 | <%= error_tag f, :password %>
15 |
16 |
17 |
18 | <%= submit dgettext("coherence", "Send Instructions"), class: "btn btn-primary" %>
19 | <%= link dgettext("coherence", "Cancel"), to: Coherence.Config.logged_out_url("/"), class: "btn" %>
20 |
21 |
22 | <% end %>
23 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/post/index.html.eex:
--------------------------------------------------------------------------------
1 | Listing Posts
2 |
3 |
4 |
5 |
6 | Title
7 | Body
8 |
9 |
10 |
11 |
12 |
13 | <%= for post <- @posts do %>
14 |
15 | <%= post.title %>
16 | <%= post.body %>
17 |
18 |
19 | <%= link "Show", to: post_path(@conn, :show, post), class: "btn btn-default btn-xs" %>
20 | <%= link "Edit", to: post_path(@conn, :edit, post), class: "btn btn-default btn-xs" %>
21 | <%= link "Delete", to: post_path(@conn, :delete, post), method: :delete, data: [confirm: "Are you sure?"], class: "btn btn-danger btn-xs" %>
22 |
23 |
24 | <% end %>
25 |
26 |
27 |
28 | <%= link "New Post", to: post_path(@conn, :new) %>
29 |
--------------------------------------------------------------------------------
/lib/coherence_demo/coherence/user.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemo.Coherence.User do
2 | @moduledoc false
3 | use Ecto.Schema
4 | use Coherence.Schema
5 |
6 |
7 | @primary_key {:id, :binary_id, autogenerate: true}
8 | @foreign_key_type :binary_id
9 |
10 |
11 | schema "users" do
12 | field :name, :string
13 | field :email, :string
14 | coherence_schema()
15 |
16 | timestamps()
17 | end
18 |
19 | def changeset(model, params \\ %{}) do
20 | model
21 | |> cast(params, [:name, :email] ++ coherence_fields())
22 | |> validate_required([:name, :email])
23 | |> validate_format(:email, ~r/@/)
24 | |> unique_constraint(:email)
25 | |> validate_coherence(params)
26 | end
27 |
28 | def changeset(model, params, :password) do
29 | model
30 | |> cast(params, ~w(password password_confirmation reset_password_token reset_password_sent_at))
31 | |> validate_coherence_password_reset(params)
32 | end
33 | end
34 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/coherence/password/edit.html.eex:
--------------------------------------------------------------------------------
1 |
2 |
3 | <%= dgettext "coherence", "Create a New Password" %>
4 |
5 | <%= form_for @changeset, password_path(@conn, :update, @changeset.data), [as: :password], fn f -> %>
6 |
7 | <%= hidden_input f, :reset_password_token %>
8 |
9 |
10 | <%= required_label f, dgettext("coherence", "Password"), class: "control-label" %>
11 | <%= password_input f, :password, class: "form-control", required: "" %>
12 | <%= error_tag f, :password %>
13 |
14 |
15 |
16 | <%= required_label f, dgettext("coherence", "Password Confirmation"), class: "control-label" %>
17 | <%= password_input f, :password_confirmation, class: "form-control", required: "" %>
18 | <%= error_tag f, :password_confirmation %>
19 |
20 |
21 |
22 | <%= submit dgettext("coherence", "Update Password"), class: "btn btn-primary" %>
23 | <%= link dgettext("coherence", "Cancel"), to: Coherence.Config.logged_out_url("/"), class: "btn" %>
24 |
25 | <% end %>
26 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/user/index.html.eex:
--------------------------------------------------------------------------------
1 | Listing users
2 |
3 |
4 |
5 |
6 | Name
7 | Email
8 | Locked?
9 | Confirmed?
10 | Sign in count
11 |
12 |
13 |
14 |
15 |
16 | <%= for user <- @users do %>
17 |
18 | <%= user.name %>
19 | <%= user.email %>
20 | <%= User.locked? user %>
21 | <%= User.confirmed? user %>
22 | <%= user.sign_in_count %>
23 |
24 |
25 | <%= link "Show", to: user_path(@conn, :show, user), class: "btn btn-default btn-xs" %>
26 | <%= link "Edit", to: user_path(@conn, :edit, user), class: "btn btn-default btn-xs" %>
27 | <%= link "Delete", to: user_path(@conn, :delete, user), method: :delete, data: [confirm: "Are you sure?"], class: "btn btn-danger btn-xs" %>
28 |
29 |
30 | <% end %>
31 |
32 |
33 |
34 | <%= link "New user", to: user_path(@conn, :new) %>
35 |
--------------------------------------------------------------------------------
/test/support/channel_case.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.ChannelCase do
2 | @moduledoc """
3 | This module defines the test case to be used by
4 | channel tests.
5 |
6 | Such tests rely on `Phoenix.ChannelTest` and also
7 | import other functionality to make it easier
8 | to build common datastructures and query the data layer.
9 |
10 | Finally, if the test case interacts with the database,
11 | it cannot be async. For this reason, every test runs
12 | inside a transaction which is reset at the beginning
13 | of the test unless the test case is marked as async.
14 | """
15 |
16 | use ExUnit.CaseTemplate
17 |
18 | using do
19 | quote do
20 | # Import conveniences for testing with channels
21 | use Phoenix.ChannelTest
22 |
23 | # The default endpoint for testing
24 | @endpoint CoherenceDemoWeb.Endpoint
25 | end
26 | end
27 |
28 |
29 | setup tags do
30 | :ok = Ecto.Adapters.SQL.Sandbox.checkout(CoherenceDemo.Repo)
31 | unless tags[:async] do
32 | Ecto.Adapters.SQL.Sandbox.mode(CoherenceDemo.Repo, {:shared, self()})
33 | end
34 | :ok
35 | end
36 |
37 | end
38 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/user/show.html.eex:
--------------------------------------------------------------------------------
1 | Show user
2 |
3 |
4 |
5 |
6 | Name:
7 | <%= @user.name %>
8 |
9 |
10 |
11 | Email:
12 | <%= @user.email %>
13 |
14 |
15 |
16 | Locked?
17 | <%= if User.locked? @user do %>
18 | Yes -
19 | <%= link "Unlock User!", to: user_path(@conn, :unlock, @user.id), "method": :put %>
20 | <% else %>
21 | No
22 | <% end %>
23 |
24 |
25 |
26 | Confirmed?
27 | <%= if User.confirmed? @user do %>
28 | Yes
29 | <% else %>
30 | No -
31 | <%= link "Confirm User!", to: user_path(@conn, :confirm, @user.id), "method": :put %>
32 | <% end %>
33 |
34 |
35 |
36 | Active?
37 | <%= if @user.active do %>
38 | Yes
39 | <% else %>
40 | No
41 | <% end %>
42 |
43 |
44 |
45 | Sign in count:
46 | <%= @user.sign_in_count %>
47 |
48 |
49 |
50 |
51 | <%= link "Edit", to: user_path(@conn, :edit, @user) %> |
52 | <%= link "Back", to: user_path(@conn, :index) %>
53 |
--------------------------------------------------------------------------------
/lib/coherence_demo/application.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemo.Application do
2 | use Application
3 |
4 | # See https://hexdocs.pm/elixir/Application.html
5 | # for more information on OTP Applications
6 | def start(_type, _args) do
7 | import Supervisor.Spec
8 |
9 | # Define workers and child supervisors to be supervised
10 | children = [
11 | # Start the Ecto repository
12 | supervisor(CoherenceDemo.Repo, []),
13 | # Start the endpoint when the application starts
14 | supervisor(CoherenceDemoWeb.Endpoint, []),
15 | # Start your own worker by calling: CoherenceDemo.Worker.start_link(arg1, arg2, arg3)
16 | # worker(CoherenceDemo.Worker, [arg1, arg2, arg3]),
17 | ]
18 |
19 | # See https://hexdocs.pm/elixir/Supervisor.html
20 | # for other strategies and supported options
21 | opts = [strategy: :one_for_one, name: CoherenceDemo.Supervisor]
22 | Supervisor.start_link(children, opts)
23 | end
24 |
25 | # Tell Phoenix to update the endpoint configuration
26 | # whenever the application is updated.
27 | def config_change(changed, _new, removed) do
28 | CoherenceDemoWeb.Endpoint.config_change(changed, removed)
29 | :ok
30 | end
31 | end
32 |
--------------------------------------------------------------------------------
/lib/coherence_demo/coherence/invitation.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemo.Coherence.Invitation do
2 | @moduledoc """
3 | Schema to support inviting a someone to create an account.
4 | """
5 | use Ecto.Schema
6 | import Ecto.Changeset
7 |
8 |
9 | @primary_key {:id, :binary_id, autogenerate: true}
10 | @foreign_key_type :binary_id
11 |
12 |
13 | schema "invitations" do
14 | field :name, :string
15 | field :email, :string
16 | field :token, :string
17 |
18 | timestamps()
19 | end
20 |
21 | @doc """
22 | Creates a changeset based on the `model` and `params`.
23 |
24 | If no params are provided, an invalid changeset is returned
25 | with no validation performed.
26 | """
27 | @spec changeset(Ecto.Schema.t, Map.t) :: Ecto.Changeset.t
28 | def changeset(model, params \\ %{}) do
29 | model
30 | |> cast(params, ~w(name email token))
31 | |> validate_required([:name, :email])
32 | |> unique_constraint(:email)
33 | |> validate_format(:email, ~r/@/)
34 | end
35 |
36 | @doc """
37 | Creates a changeset for a new schema
38 | """
39 | @spec new_changeset(Map.t) :: Ecto.Changeset.t
40 | def new_changeset(params \\ %{}) do
41 | changeset %__MODULE__{}, params
42 | end
43 | end
44 |
--------------------------------------------------------------------------------
/test/support/conn_case.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.ConnCase do
2 | @moduledoc """
3 | This module defines the test case to be used by
4 | tests that require setting up a connection.
5 |
6 | Such tests rely on `Phoenix.ConnTest` and also
7 | import other functionality to make it easier
8 | to build common datastructures and query the data layer.
9 |
10 | Finally, if the test case interacts with the database,
11 | it cannot be async. For this reason, every test runs
12 | inside a transaction which is reset at the beginning
13 | of the test unless the test case is marked as async.
14 | """
15 |
16 | use ExUnit.CaseTemplate
17 |
18 | using do
19 | quote do
20 | # Import conveniences for testing with connections
21 | use Phoenix.ConnTest
22 | import CoherenceDemoWeb.Router.Helpers
23 |
24 | # The default endpoint for testing
25 | @endpoint CoherenceDemoWeb.Endpoint
26 | end
27 | end
28 |
29 |
30 | setup tags do
31 | :ok = Ecto.Adapters.SQL.Sandbox.checkout(CoherenceDemo.Repo)
32 | unless tags[:async] do
33 | Ecto.Adapters.SQL.Sandbox.mode(CoherenceDemo.Repo, {:shared, self()})
34 | end
35 | {:ok, conn: Phoenix.ConnTest.build_conn()}
36 | end
37 |
38 | end
39 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/user/form.html.eex:
--------------------------------------------------------------------------------
1 | <%= form_for @changeset, @action, fn f -> %>
2 | <%= if @changeset.action do %>
3 |
4 |
Oops, something went wrong! Please check the errors below.
5 |
6 | <% end %>
7 |
8 |
9 | <%= label f, :name, class: "control-label" %>
10 | <%= text_input f, :name, class: "form-control" %>
11 | <%= error_tag f, :name %>
12 |
13 |
14 |
15 | <%= label f, :email, class: "control-label" %>
16 | <%= text_input f, :email, class: "form-control" %>
17 | <%= error_tag f, :email %>
18 |
19 |
20 |
21 | <%= label f, :password, class: "control-label" %>
22 | <%= password_input f, :password, class: "form-control" %>
23 | <%= error_tag f, :password %>
24 |
25 |
26 |
27 | <%= label f, :password_confirmation, class: "control-label" %>
28 | <%= password_input f, :password_confirmation, class: "form-control" %>
29 | <%= error_tag f, :password_confirmation %>
30 |
31 |
32 |
33 | <%= submit "Submit", class: "btn btn-primary" %>
34 |
35 | <% end %>
36 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/coherence/invitation/new.html.eex:
--------------------------------------------------------------------------------
1 | <%= form_for @changeset, invitation_path(@conn, :create), [as: :invitation], fn f -> %>
2 | <%= if @changeset.action do %>
3 |
4 |
<%= dgettext "coherence", "Oops, something went wrong! Please check the errors below." %>
5 |
6 | <% end %>
7 |
8 | <%= required_label f, dgettext("coherence", "Name"), class: "control-label" %>
9 | <%= text_input f, :name, class: "form-control", required: "" %>
10 | <%= error_tag f, :name %>
11 |
12 |
13 |
14 | <%= required_label f, dgettext("coherence", "Email"), class: "control-label" %>
15 | <%= text_input f, :email, class: "form-control", required: "" %>
16 | <%= error_tag f, :email %>
17 |
18 |
19 |
20 | <%= submit dgettext("coherence", "Send Invitation"), class: "btn btn-primary" %>
21 | <%= link dgettext("coherence", "Cancel"), to: Coherence.Config.logged_out_url("/"), class: "btn" %>
22 | <%= if invitation = @conn.assigns[:invitation] do %>
23 | <%= link dgettext("coherence", "Resend Invitation!"), to: invitation_path(@conn, :resend, invitation.id), class: "btn" %>
24 | <% end %>
25 |
26 | <% end %>
27 |
--------------------------------------------------------------------------------
/priv/repo/migrations/20170803154908_create_coherence_user.exs:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemo.Repo.Migrations.CreateCoherenceUser do
2 | use Ecto.Migration
3 | def change do
4 | create table(:users, primary_key: false) do
5 | add :id, :binary_id, primary_key: true
6 |
7 | add :name, :string
8 | add :email, :string
9 | # rememberable
10 | add :remember_created_at, :utc_datetime
11 | # unlockable_with_token
12 | add :unlock_token, :string
13 | # recoverable
14 | add :reset_password_token, :string
15 | add :reset_password_sent_at, :utc_datetime
16 | # lockable
17 | add :failed_attempts, :integer, default: 0
18 | add :locked_at, :utc_datetime
19 | # trackable
20 | add :sign_in_count, :integer, default: 0
21 | add :current_sign_in_at, :utc_datetime
22 | add :last_sign_in_at, :utc_datetime
23 | add :current_sign_in_ip, :string
24 | add :last_sign_in_ip, :string
25 | # confirmable
26 | add :confirmation_token, :string
27 | add :confirmed_at, :utc_datetime
28 | add :confirmation_sent_at, :utc_datetime
29 | # authenticatable
30 | add :password_hash, :string
31 | add :active, :boolean, null: false, default: true
32 |
33 | timestamps()
34 | end
35 | create unique_index(:users, [:email])
36 |
37 | end
38 | end
39 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/channels/user_socket.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.UserSocket do
2 | use Phoenix.Socket
3 |
4 | ## Channels
5 | # channel "room:*", CoherenceDemoWeb.RoomChannel
6 |
7 | ## Transports
8 | transport :websocket, Phoenix.Transports.WebSocket
9 | # transport :longpoll, Phoenix.Transports.LongPoll
10 |
11 | # Socket params are passed from the client and can
12 | # be used to verify and authenticate a user. After
13 | # verification, you can put default assigns into
14 | # the socket that will be set for all channels, ie
15 | #
16 | # {:ok, assign(socket, :user_id, verified_user_id)}
17 | #
18 | # To deny connection, return `:error`.
19 | #
20 | # See `Phoenix.Token` documentation for examples in
21 | # performing token verification on connect.
22 | def connect(_params, socket) do
23 | {:ok, socket}
24 | end
25 |
26 | # Socket id's are topics that allow you to identify all sockets for a given user:
27 | #
28 | # def id(socket), do: "user_socket:#{socket.assigns.user_id}"
29 | #
30 | # Would allow you to broadcast a "disconnect" event and terminate
31 | # all active sockets and channels for a given user:
32 | #
33 | # CoherenceDemoWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
34 | #
35 | # Returning `nil` makes this socket anonymous.
36 | def id(_socket), do: nil
37 | end
38 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/coherence_web.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.Coherence do
2 | @moduledoc false
3 |
4 | def view do
5 | quote do
6 | use Phoenix.View, root: "lib/coherence_demo_web/templates"
7 | # Import convenience functions from controllers
8 |
9 | import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1]
10 |
11 | # Use all HTML functionality (forms, tags, etc)
12 | use Phoenix.HTML
13 |
14 | import CoherenceDemoWeb.Router.Helpers
15 | import CoherenceDemoWeb.ErrorHelpers
16 | import CoherenceDemoWeb.Gettext
17 | import CoherenceDemoWeb.Coherence.ViewHelpers
18 | end
19 | end
20 |
21 | def controller do
22 | quote do
23 | use Phoenix.Controller, except: [layout_view: 2]
24 | use Coherence.Config
25 | use Timex
26 |
27 | import Ecto
28 | import Ecto.Query
29 | import Plug.Conn
30 | import CoherenceDemoWeb.Router.Helpers
31 | import CoherenceDemoWeb.Gettext
32 | import Coherence.Controller
33 |
34 | alias Coherence.Config
35 | alias Coherence.Controller
36 |
37 | require Redirects
38 | end
39 | end
40 |
41 | @doc """
42 | When used, dispatch to the appropriate controller/view/etc.
43 | """
44 | defmacro __using__(which) when is_atom(which) do
45 | apply(__MODULE__, which, [])
46 | end
47 | end
48 |
--------------------------------------------------------------------------------
/lib/coherence_demo/coherence/rememberable.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemo.Coherence.Rememberable do
2 | @moduledoc false
3 | use Ecto.Schema
4 |
5 | import Ecto.Changeset
6 | import Ecto.Query
7 |
8 | alias Coherence.Config
9 |
10 |
11 | @primary_key {:id, :binary_id, autogenerate: true}
12 | @foreign_key_type :binary_id
13 |
14 |
15 | schema "rememberables" do
16 | field :series_hash, :string
17 | field :token_hash, :string
18 | field :token_created_at, Timex.Ecto.DateTime
19 | belongs_to :user, Module.concat(Config.module, Config.user_schema), type: :binary_id
20 |
21 | timestamps()
22 | end
23 |
24 | use Coherence.Rememberable
25 |
26 | @doc """
27 | Creates a changeset based on the `model` and `params`.
28 |
29 | If no params are provided, an invalid changeset is returned
30 | with no validation performed.
31 | """
32 | @spec changeset(Ecto.Schema.t, Map.t) :: Ecto.Changeset.t
33 | def changeset(model, params \\ %{}) do
34 | model
35 | |> cast(params, ~w(series_hash token_hash token_created_at user_id))
36 | |> validate_required(~w(series_hash token_hash token_created_at user_id)a)
37 | end
38 |
39 | @doc """
40 | Creates a changeset for a new schema
41 | """
42 | @spec new_changeset(Map.t) :: Ecto.Changeset.t
43 | def new_changeset(params \\ %{}) do
44 | changeset %Rememberable{}, params
45 | end
46 |
47 | end
48 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # CoherenceDemo
2 |
3 | A Coherence Demo project illustrating how to use [Coherence](https://github.com/smpallen99/coherence).
4 |
5 | This project demonstrates some of the features of Coherence on a very simple project.
6 |
7 | > Updated for Phoenix 1.3
8 |
9 | ## Installation
10 |
11 | ```bash
12 | $ git clone https://github.com/smpallen99/coherence_demo.git
13 | $ cd coherence_demo
14 | $ mix do deps.get, deps.compile
15 | $ mix ecto.setup
16 | $ cd assets && npm install
17 | $ iex -S mix phx.server
18 | ```
19 |
20 | Visit http://localhost:4008/ in your browser
21 |
22 | Default login created with `mix ecto.setup` is demouser@example.com / secret
23 |
24 | Note, you will need to setup an sendgrid API key in config/config.exs to get the outgoing emails to work
25 |
26 | ## How was this project created
27 |
28 | ```bash
29 | $ mix phx.new coherence_demo --binary-id
30 | $ cd coherence_demo
31 | $ mix ecto.setup
32 |
33 | # edit mix.exs and add coherence deps
34 | $ mix coherence.install --full --invitable --registerable --rememberable --confirmable --user-active-field
35 |
36 | # edit web/router.ex and add the coherence routes per the instructions
37 | # edit priv/repo/seeds.exs -- add User seeds
38 | # edit web/templates/layout/app.html.eex -- add some nav stuff
39 |
40 | # added the `user_controller`, view, and templates manually
41 | # added some custom routes for the lock/unlock/etc behaviour
42 |
43 | $mix ecto.setup
44 | ```
45 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/views/error_helpers.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.ErrorHelpers do
2 | @moduledoc """
3 | Conveniences for translating and building error messages.
4 | """
5 |
6 | use Phoenix.HTML
7 |
8 | @doc """
9 | Generates tag for inlined form input errors.
10 | """
11 | def error_tag(form, field) do
12 | Enum.map(Keyword.get_values(form.errors, field), fn (error) ->
13 | content_tag :span, translate_error(error), class: "help-block"
14 | end)
15 | end
16 |
17 | @doc """
18 | Translates an error message using gettext.
19 | """
20 | def translate_error({msg, opts}) do
21 | # Because error messages were defined within Ecto, we must
22 | # call the Gettext module passing our Gettext backend. We
23 | # also use the "errors" domain as translations are placed
24 | # in the errors.po file.
25 | # Ecto will pass the :count keyword if the error message is
26 | # meant to be pluralized.
27 | # On your own code and templates, depending on whether you
28 | # need the message to be pluralized or not, this could be
29 | # written simply as:
30 | #
31 | # dngettext "errors", "1 file", "%{count} files", count
32 | # dgettext "errors", "is invalid"
33 | #
34 | if count = opts[:count] do
35 | Gettext.dngettext(CoherenceDemoWeb.Gettext, "errors", msg, msg, count, opts)
36 | else
37 | Gettext.dgettext(CoherenceDemoWeb.Gettext, "errors", msg, opts)
38 | end
39 | end
40 | end
41 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/router.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.Router do
2 | use CoherenceDemoWeb, :router
3 | use Coherence.Router
4 |
5 | pipeline :browser do
6 | plug :accepts, ["html"]
7 | plug :fetch_session
8 | plug :fetch_flash
9 | plug :protect_from_forgery
10 | plug :put_secure_browser_headers
11 | plug Coherence.Authentication.Session
12 | end
13 |
14 | pipeline :protected do
15 | plug :accepts, ["html"]
16 | plug :fetch_session
17 | plug :fetch_flash
18 | plug :protect_from_forgery
19 | plug :put_secure_browser_headers
20 | plug Coherence.Authentication.Session, protected: true # Add this
21 | end
22 |
23 | pipeline :api do
24 | plug :accepts, ["json"]
25 | end
26 |
27 | # Add this block
28 | scope "/" do
29 | pipe_through :browser
30 | coherence_routes()
31 | end
32 |
33 | # Add this block
34 | scope "/" do
35 | pipe_through :protected
36 | coherence_routes :protected
37 | end
38 |
39 | scope "/", CoherenceDemoWeb do
40 | pipe_through :browser # Use the default browser stack
41 |
42 | get "/", PageController, :index
43 | end
44 |
45 | scope "/", CoherenceDemoWeb do
46 | pipe_through :protected # Use the default browser stack
47 |
48 | resources "/posts", PostController
49 | resources "/users", UserController
50 | put "/lock/:id", UserController, :lock
51 | put "/unlock/:id", UserController, :unlock
52 | put "/confirm/:id", UserController, :confirm
53 | end
54 |
55 | # Other scopes may use custom stacks.
56 | # scope "/api", CoherenceDemoWeb do
57 | # pipe_through :api
58 | # end
59 | end
60 |
--------------------------------------------------------------------------------
/test/support/data_case.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemo.DataCase do
2 | @moduledoc """
3 | This module defines the setup for tests requiring
4 | access to the application's data layer.
5 |
6 | You may define functions here to be used as helpers in
7 | your tests.
8 |
9 | Finally, if the test case interacts with the database,
10 | it cannot be async. For this reason, every test runs
11 | inside a transaction which is reset at the beginning
12 | of the test unless the test case is marked as async.
13 | """
14 |
15 | use ExUnit.CaseTemplate
16 |
17 | using do
18 | quote do
19 | alias CoherenceDemo.Repo
20 |
21 | import Ecto
22 | import Ecto.Changeset
23 | import Ecto.Query
24 | import CoherenceDemo.DataCase
25 | end
26 | end
27 |
28 | setup tags do
29 | :ok = Ecto.Adapters.SQL.Sandbox.checkout(CoherenceDemo.Repo)
30 |
31 | unless tags[:async] do
32 | Ecto.Adapters.SQL.Sandbox.mode(CoherenceDemo.Repo, {:shared, self()})
33 | end
34 |
35 | :ok
36 | end
37 |
38 | @doc """
39 | A helper that transform changeset errors to a map of messages.
40 |
41 | assert {:error, changeset} = Accounts.create_user(%{password: "short"})
42 | assert "password is too short" in errors_on(changeset).password
43 | assert %{password: ["password is too short"]} = errors_on(changeset)
44 |
45 | """
46 | def errors_on(changeset) do
47 | Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
48 | Enum.reduce(opts, message, fn {key, value}, acc ->
49 | String.replace(acc, "%{#{key}}", to_string(value))
50 | end)
51 | end)
52 | end
53 | end
54 |
--------------------------------------------------------------------------------
/assets/brunch-config.js:
--------------------------------------------------------------------------------
1 | exports.config = {
2 | // See http://brunch.io/#documentation for docs.
3 | files: {
4 | javascripts: {
5 | joinTo: "js/app.js"
6 |
7 | // To use a separate vendor.js bundle, specify two files path
8 | // http://brunch.io/docs/config#-files-
9 | // joinTo: {
10 | // "js/app.js": /^js/,
11 | // "js/vendor.js": /^(?!js)/
12 | // }
13 | //
14 | // To change the order of concatenation of files, explicitly mention here
15 | // order: {
16 | // before: [
17 | // "vendor/js/jquery-2.1.1.js",
18 | // "vendor/js/bootstrap.min.js"
19 | // ]
20 | // }
21 | },
22 | stylesheets: {
23 | joinTo: "css/app.css"
24 | },
25 | templates: {
26 | joinTo: "js/app.js"
27 | }
28 | },
29 |
30 | conventions: {
31 | // This option sets where we should place non-css and non-js assets in.
32 | // By default, we set this to "/assets/static". Files in this directory
33 | // will be copied to `paths.public`, which is "priv/static" by default.
34 | assets: /^(static)/
35 | },
36 |
37 | // Phoenix paths configuration
38 | paths: {
39 | // Dependencies and current project directories to watch
40 | watched: ["static", "css", "js", "vendor"],
41 | // Where to compile files to
42 | public: "../priv/static"
43 | },
44 |
45 | // Configure your plugins
46 | plugins: {
47 | babel: {
48 | // Do not use ES6 compiler in vendor code
49 | ignore: [/vendor/]
50 | }
51 | },
52 |
53 | modules: {
54 | autoRequire: {
55 | "js/app.js": ["js/app"]
56 | }
57 | },
58 |
59 | npm: {
60 | enabled: true
61 | }
62 | };
63 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/coherence/session/new.html.eex:
--------------------------------------------------------------------------------
1 |
2 |
3 |
<%= gettext "Default Login Credentials" %>
4 |
5 |
6 |
<%= gettext "Email" %>: demouser@example.com
7 |
<%= gettext "Password" %>: secret
8 |
9 |
10 |
11 |
12 | <%= form_for @conn, session_path(@conn, :create), [as: :session], fn f -> %>
13 |
14 | <% login_field = Coherence.Config.login_field %>
15 |
16 | <%= required_label f, login_field, class: "control-label" %>
17 | <%= text_input f, login_field, class: "form-control", required: "" %>
18 | <%= error_tag f, login_field %>
19 |
20 |
21 |
22 | <%= required_label f, dgettext("coherence", "Password"), class: "control-label" %>
23 | <%= password_input f, :password, class: "form-control", required: "" %>
24 | <%= error_tag f, :password %>
25 |
26 |
27 | <%= if @remember do %>
28 |
29 |
30 | <%= dgettext "coherence", "Remember Me?" %>
31 |
32 |
33 | <% end %>
34 |
35 |
36 | <%= submit dgettext("coherence", "Sign In"), class: "btn btn-primary" %>
37 | <%= link dgettext("coherence", "Cancel"), to: Coherence.Config.logged_out_url("/"), class: "btn" %>
38 |
39 |
40 |
41 |
42 | <%= coherence_links(@conn, :new_session) %>
43 |
44 |
45 | <% end %>
46 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/layout/app.html.eex:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | Hello CoherenceDemo!
11 | ">
12 |
13 |
14 |
15 |
16 |
35 |
36 |
<%= get_flash(@conn, :info) %>
37 |
<%= get_flash(@conn, :error) %>
38 |
39 |
40 | <%= render @view_module, @view_template, assigns %>
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/mix.exs:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemo.Mixfile do
2 | use Mix.Project
3 |
4 | def project do
5 | [
6 | app: :coherence_demo,
7 | version: "0.1.0",
8 | elixir: "~> 1.4",
9 | elixirc_paths: elixirc_paths(Mix.env),
10 | compilers: [:phoenix, :gettext] ++ Mix.compilers,
11 | start_permanent: Mix.env == :prod,
12 | aliases: aliases(),
13 | deps: deps()
14 | ]
15 | end
16 |
17 | # Configuration for the OTP application.
18 | #
19 | # Type `mix help compile.app` for more information.
20 | def application do
21 | [
22 | mod: {CoherenceDemo.Application, []},
23 | extra_applications: [:logger, :runtime_tools]
24 | ]
25 | end
26 |
27 | # Specifies which paths to compile per environment.
28 | defp elixirc_paths(:test), do: ["lib", "test/support"]
29 | defp elixirc_paths(_), do: ["lib"]
30 |
31 | # Specifies your project dependencies.
32 | #
33 | # Type `mix help deps` for examples and options.
34 | defp deps do
35 | [
36 | {:phoenix, "~> 1.3"},
37 | {:phoenix_pubsub, "~> 1.0"},
38 | {:phoenix_ecto, "~> 3.2"},
39 | {:postgrex, ">= 0.0.0"},
40 | {:phoenix_html, "~> 2.10"},
41 | {:phoenix_live_reload, "~> 1.0", only: :dev},
42 | {:gettext, "~> 0.11"},
43 | # {:coherence, path: "../coherence3"},
44 | {:coherence, github: "smpallen99/coherence"},
45 | {:cowboy, "~> 1.0"}
46 | ]
47 | end
48 |
49 | # Aliases are shortcuts or tasks specific to the current project.
50 | # For example, to create, migrate and run the seeds file at once:
51 | #
52 | # $ mix ecto.setup
53 | #
54 | # See the documentation for `Mix` for more info on aliases.
55 | defp aliases do
56 | [
57 | "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
58 | "ecto.reset": ["ecto.drop", "ecto.setup"],
59 | "test": ["ecto.create --quiet", "ecto.migrate", "test"]
60 | ]
61 | end
62 | end
63 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/controllers/coherence/redirects.ex:
--------------------------------------------------------------------------------
1 | defmodule Coherence.Redirects do
2 | @moduledoc """
3 | Define controller action redirection functions.
4 |
5 | This module contains default redirect functions for each of the controller
6 | actions that perform redirects. By using this Module you get the following
7 | functions:
8 |
9 | * session_create/2
10 | * session_delete/2
11 | * password_create/2
12 | * password_update/2,
13 | * unlock_create_not_locked/2
14 | * unlock_create_invalid/2
15 | * unlock_create/2
16 | * unlock_edit_not_locked/2
17 | * unlock_edit/2
18 | * unlock_edit_invalid/2
19 | * registration_create/2
20 | * invitation_create/2
21 | * confirmation_create/2
22 | * confirmation_edit_invalid/2
23 | * confirmation_edit_expired/2
24 | * confirmation_edit/2
25 | * confirmation_edit_error/2
26 |
27 | You can override any of the functions to customize the redirect path. Each
28 | function is passed the `conn` and `params` arguments from the controller.
29 |
30 | ## Examples
31 |
32 | import CoherenceDemoWeb.Router.Helpers
33 |
34 | # override the log out action back to the log in page
35 | def session_delete(conn, _), do: redirect(conn, to: session_path(conn, :new))
36 |
37 | # redirect the user to the login page after registering
38 | def registration_create(conn, _), do: redirect(conn, to: session_path(conn, :new))
39 |
40 | # disable the user_return_to feature on login
41 | def session_create(conn, _), do: redirect(conn, to: landing_path(conn, :index))
42 |
43 | """
44 | use Redirects
45 | # Uncomment the import below if adding overrides
46 | # import CoherenceDemoWeb.Router.Helpers
47 |
48 | # Add function overrides below
49 |
50 | # Example usage
51 | # Uncomment the following line to return the user to the login form after logging out
52 | # def session_delete(conn, _), do: redirect(conn, to: session_path(conn, :new))
53 |
54 | end
55 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/endpoint.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.Endpoint do
2 | use Phoenix.Endpoint, otp_app: :coherence_demo
3 |
4 | socket "/socket", CoherenceDemoWeb.UserSocket
5 |
6 | # Serve at "/" the static files from "priv/static" directory.
7 | #
8 | # You should set gzip to true if you are running phoenix.digest
9 | # when deploying your static files in production.
10 | plug Plug.Static,
11 | at: "/", from: :coherence_demo, gzip: false,
12 | only: ~w(css fonts images js favicon.ico robots.txt)
13 |
14 | # Code reloading can be explicitly enabled under the
15 | # :code_reloader configuration of your endpoint.
16 | if code_reloading? do
17 | socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
18 | plug Phoenix.LiveReloader
19 | plug Phoenix.CodeReloader
20 | end
21 |
22 | plug Plug.RequestId
23 | plug Plug.Logger
24 |
25 | plug Plug.Parsers,
26 | parsers: [:urlencoded, :multipart, :json],
27 | pass: ["*/*"],
28 | json_decoder: Poison
29 |
30 | plug Plug.MethodOverride
31 | plug Plug.Head
32 |
33 | # The session will be stored in the cookie and signed,
34 | # this means its contents can be read but not tampered with.
35 | # Set :encryption_salt if you would also like to encrypt it.
36 | plug Plug.Session,
37 | store: :cookie,
38 | key: "_coherence_demo_key",
39 | signing_salt: "tzw6MGzw"
40 |
41 | plug CoherenceDemoWeb.Router
42 |
43 | @doc """
44 | Callback invoked for dynamically configuring the endpoint.
45 |
46 | It receives the endpoint configuration and checks if
47 | configuration should be loaded from the system environment.
48 | """
49 | def init(_key, config) do
50 | if config[:load_from_system_env] do
51 | port = System.get_env("PORT") || raise "expected the PORT environment variable to be set"
52 | {:ok, Keyword.put(config, :http, [:inet6, port: port])}
53 | else
54 | {:ok, config}
55 | end
56 | end
57 | end
58 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/controllers/post_controller.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.PostController do
2 | use CoherenceDemoWeb, :controller
3 |
4 | alias CoherenceDemo.Blogs
5 | alias CoherenceDemo.Blogs.Post
6 |
7 | def index(conn, _params) do
8 | posts = Blogs.list_posts()
9 | render(conn, "index.html", posts: posts)
10 | end
11 |
12 | def new(conn, _params) do
13 | changeset = Blogs.change_post(%Post{})
14 | render(conn, "new.html", changeset: changeset)
15 | end
16 |
17 | def create(conn, %{"post" => post_params}) do
18 | case Blogs.create_post(post_params) do
19 | {:ok, post} ->
20 | conn
21 | |> put_flash(:info, "Post created successfully.")
22 | |> redirect(to: post_path(conn, :show, post))
23 | {:error, %Ecto.Changeset{} = changeset} ->
24 | render(conn, "new.html", changeset: changeset)
25 | end
26 | end
27 |
28 | def show(conn, %{"id" => id}) do
29 | post = Blogs.get_post!(id)
30 | render(conn, "show.html", post: post)
31 | end
32 |
33 | def edit(conn, %{"id" => id}) do
34 | post = Blogs.get_post!(id)
35 | changeset = Blogs.change_post(post)
36 | render(conn, "edit.html", post: post, changeset: changeset)
37 | end
38 |
39 | def update(conn, %{"id" => id, "post" => post_params}) do
40 | post = Blogs.get_post!(id)
41 |
42 | case Blogs.update_post(post, post_params) do
43 | {:ok, post} ->
44 | conn
45 | |> put_flash(:info, "Post updated successfully.")
46 | |> redirect(to: post_path(conn, :show, post))
47 | {:error, %Ecto.Changeset{} = changeset} ->
48 | render(conn, "edit.html", post: post, changeset: changeset)
49 | end
50 | end
51 |
52 | def delete(conn, %{"id" => id}) do
53 | post = Blogs.get_post!(id)
54 | {:ok, _post} = Blogs.delete_post(post)
55 |
56 | conn
57 | |> put_flash(:info, "Post deleted successfully.")
58 | |> redirect(to: post_path(conn, :index))
59 | end
60 | end
61 |
--------------------------------------------------------------------------------
/config/config.exs:
--------------------------------------------------------------------------------
1 | # This file is responsible for configuring your application
2 | # and its dependencies with the aid of the Mix.Config module.
3 | #
4 | # This configuration file is loaded before any dependency and
5 | # is restricted to this project.
6 | use Mix.Config
7 |
8 | # General application configuration
9 | config :coherence_demo,
10 | ecto_repos: [CoherenceDemo.Repo],
11 | generators: [binary_id: true]
12 |
13 | # Configures the endpoint
14 | config :coherence_demo, CoherenceDemoWeb.Endpoint,
15 | url: [host: "localhost"],
16 | secret_key_base: "5/uvDSgp4hmTvBNGyr7jC3NNx+7xm7+9qGugp5DbqDvihNY+e+73kZe/A15l9MoK",
17 | render_errors: [view: CoherenceDemoWeb.ErrorView, accepts: ~w(html json)],
18 | pubsub: [name: CoherenceDemo.PubSub,
19 | adapter: Phoenix.PubSub.PG2]
20 |
21 | # Configures Elixir's Logger
22 | config :logger, :console,
23 | format: "$time $metadata[$level] $message\n",
24 | metadata: [:request_id]
25 |
26 | # %% Coherence Configuration %% Don't remove this line
27 | config :coherence,
28 | user_schema: CoherenceDemo.Coherence.User,
29 | repo: CoherenceDemo.Repo,
30 | module: CoherenceDemo,
31 | web_module: CoherenceDemoWeb,
32 | router: CoherenceDemoWeb.Router,
33 | messages_backend: CoherenceDemoWeb.Coherence.Messages,
34 | require_current_password: false,
35 | logged_out_url: "/",
36 | allow_unconfirmed_access_for: 5,
37 | user_active_field: true,
38 | email_from_name: {:system, "NAME"},
39 | email_from_email: {:system, "EMAIL"},
40 | opts: [:rememberable, :unlockable_with_token, :invitable, :recoverable, :lockable, :trackable, :confirmable, :registerable, :authenticatable]
41 |
42 | config :coherence, CoherenceDemoWeb.Coherence.Mailer,
43 | adapter: Swoosh.Adapters.Sendgrid,
44 | api_key: {:system, "API_KEY"}
45 | # %% End Coherence Configuration %%
46 |
47 | # Import environment specific config. This must remain at the bottom
48 | # of this file so it overrides the configuration defined above.
49 | import_config "#{Mix.env}.exs"
50 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb do
2 | @moduledoc """
3 | The entrypoint for defining your web interface, such
4 | as controllers, views, channels and so on.
5 |
6 | This can be used in your application as:
7 |
8 | use CoherenceDemoWeb, :controller
9 | use CoherenceDemoWeb, :view
10 |
11 | The definitions below will be executed for every view,
12 | controller, etc, so keep them short and clean, focused
13 | on imports, uses and aliases.
14 |
15 | Do NOT define functions inside the quoted expressions
16 | below. Instead, define any helper function in modules
17 | and import those modules here.
18 | """
19 |
20 | def controller do
21 | quote do
22 | use Phoenix.Controller, namespace: CoherenceDemoWeb
23 | import Plug.Conn
24 | import CoherenceDemoWeb.Router.Helpers
25 | import CoherenceDemoWeb.Gettext
26 |
27 | alias CoherenceDemo.Repo
28 | end
29 | end
30 |
31 | def view do
32 | quote do
33 | use Phoenix.View, root: "lib/coherence_demo_web/templates",
34 | namespace: CoherenceDemoWeb
35 |
36 | # Import convenience functions from controllers
37 | import Phoenix.Controller, only: [get_flash: 2, view_module: 1]
38 |
39 | # Use all HTML functionality (forms, tags, etc)
40 | use Phoenix.HTML
41 |
42 | import CoherenceDemoWeb.Router.Helpers
43 | import CoherenceDemoWeb.ErrorHelpers
44 | import CoherenceDemoWeb.Gettext
45 | end
46 | end
47 |
48 | def router do
49 | quote do
50 | use Phoenix.Router
51 | import Plug.Conn
52 | import Phoenix.Controller
53 | end
54 | end
55 |
56 | def channel do
57 | quote do
58 | use Phoenix.Channel
59 | import CoherenceDemoWeb.Gettext
60 | end
61 | end
62 |
63 | @doc """
64 | When used, dispatch to the appropriate controller/view/etc.
65 | """
66 | defmacro __using__(which) when is_atom(which) do
67 | apply(__MODULE__, which, [])
68 | end
69 | end
70 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/coherence/invitation/edit.html.eex:
--------------------------------------------------------------------------------
1 |
2 |
3 | <%= form_for @changeset, invitation_path(@conn, :create_user), fn f -> %>
4 |
5 | <%= if @changeset.action do %>
6 |
7 |
<%= dgettext "coherence", "Oops, something went wrong! Please check the errors below." %>
8 |
9 | <% end %>
10 |
11 |
12 |
13 |
14 | <%= required_label f, dgettext("coherence", "Email"), class: "control-label" %>
15 | <%= text_input f, :name, class: "form-control", required: "" %>
16 | <%= error_tag f, :name %>
17 |
18 |
19 | <%= unless (login_field = Coherence.Config.login_field) == :email do %>
20 |
21 | <%= required_label f, login_field, class: "control-label" %>
22 | <%= text_input f, login_field, class: "form-control", required: "" %>
23 | <%= error_tag f, login_field %>
24 |
25 | <% end %>
26 |
27 |
28 | <%= required_label f, dgettext("coherence", "Email"), class: "control-label" %>
29 | <%= text_input f, :email, class: "form-control", required: "" %>
30 | <%= error_tag f, :email %>
31 |
32 |
33 |
34 | <%= required_label f, dgettext("coherence", "Password"), class: "control-label" %>
35 | <%= password_input f, :password, class: "form-control", required: "" %>
36 | <%= error_tag f, :password %>
37 |
38 |
39 |
40 | <%= required_label f, dgettext("coherence", "Password Confirmation"), class: "control-label" %>
41 | <%= password_input f, :password_confirmation, class: "form-control", required: "" %>
42 | <%= error_tag f, :password_confirmation %>
43 |
44 |
45 |
46 | <%= submit dgettext("coherence", "Create"), class: "btn btn-primary" %>
47 | <%= link dgettext("coherence", "Cancel"), to: Coherence.Config.logged_out_url("/"), class: "btn" %>
48 |
49 | <% end %>
50 |
--------------------------------------------------------------------------------
/config/dev.exs:
--------------------------------------------------------------------------------
1 | use Mix.Config
2 |
3 | # For development, we disable any cache and enable
4 | # debugging and code reloading.
5 | #
6 | # The watchers configuration can be used to run external
7 | # watchers to your application. For example, we use it
8 | # with brunch.io to recompile .js and .css sources.
9 | config :coherence_demo, CoherenceDemoWeb.Endpoint,
10 | http: [port: 4008],
11 | debug_errors: true,
12 | code_reloader: true,
13 | check_origin: false,
14 | watchers: [node: ["node_modules/brunch/bin/brunch", "watch", "--stdin",
15 | cd: Path.expand("../assets", __DIR__)]]
16 |
17 | # ## SSL Support
18 | #
19 | # In order to use HTTPS in development, a self-signed
20 | # certificate can be generated by running the following
21 | # command from your terminal:
22 | #
23 | # openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout priv/server.key -out priv/server.pem
24 | #
25 | # The `http:` config above can be replaced with:
26 | #
27 | # https: [port: 4000, keyfile: "priv/server.key", certfile: "priv/server.pem"],
28 | #
29 | # If desired, both `http:` and `https:` keys can be
30 | # configured to run both http and https servers on
31 | # different ports.
32 |
33 | # Watch static and templates for browser reloading.
34 | config :coherence_demo, CoherenceDemoWeb.Endpoint,
35 | live_reload: [
36 | patterns: [
37 | ~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$},
38 | ~r{priv/gettext/.*(po)$},
39 | ~r{lib/coherence_demo_web/views/.*(ex)$},
40 | ~r{lib/coherence_demo_web/templates/.*(eex)$}
41 | ]
42 | ]
43 |
44 | # Do not include metadata nor timestamps in development logs
45 | config :logger, :console, format: "[$level] $message\n"
46 |
47 | # Set a higher stacktrace during development. Avoid configuring such
48 | # in production as building large stacktraces may be expensive.
49 | config :phoenix, :stacktrace_depth, 20
50 |
51 | # Configure your database
52 | config :coherence_demo, CoherenceDemo.Repo,
53 | adapter: Ecto.Adapters.Postgres,
54 | username: "postgres",
55 | password: "postgres",
56 | database: "coherence_demo_dev",
57 | hostname: "localhost",
58 | pool_size: 10
59 |
--------------------------------------------------------------------------------
/lib/coherence_demo/blogs/blogs.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemo.Blogs do
2 | @moduledoc """
3 | The Blogs context.
4 | """
5 |
6 | import Ecto.Query, warn: false
7 | alias CoherenceDemo.Repo
8 |
9 | alias CoherenceDemo.Blogs.Post
10 |
11 | @doc """
12 | Returns the list of posts.
13 |
14 | ## Examples
15 |
16 | iex> list_posts()
17 | [%Post{}, ...]
18 |
19 | """
20 | def list_posts do
21 | Repo.all(Post)
22 | end
23 |
24 | @doc """
25 | Gets a single post.
26 |
27 | Raises `Ecto.NoResultsError` if the Post does not exist.
28 |
29 | ## Examples
30 |
31 | iex> get_post!(123)
32 | %Post{}
33 |
34 | iex> get_post!(456)
35 | ** (Ecto.NoResultsError)
36 |
37 | """
38 | def get_post!(id), do: Repo.get!(Post, id)
39 |
40 | @doc """
41 | Creates a post.
42 |
43 | ## Examples
44 |
45 | iex> create_post(%{field: value})
46 | {:ok, %Post{}}
47 |
48 | iex> create_post(%{field: bad_value})
49 | {:error, %Ecto.Changeset{}}
50 |
51 | """
52 | def create_post(attrs \\ %{}) do
53 | %Post{}
54 | |> Post.changeset(attrs)
55 | |> Repo.insert()
56 | end
57 |
58 | @doc """
59 | Updates a post.
60 |
61 | ## Examples
62 |
63 | iex> update_post(post, %{field: new_value})
64 | {:ok, %Post{}}
65 |
66 | iex> update_post(post, %{field: bad_value})
67 | {:error, %Ecto.Changeset{}}
68 |
69 | """
70 | def update_post(%Post{} = post, attrs) do
71 | post
72 | |> Post.changeset(attrs)
73 | |> Repo.update()
74 | end
75 |
76 | @doc """
77 | Deletes a Post.
78 |
79 | ## Examples
80 |
81 | iex> delete_post(post)
82 | {:ok, %Post{}}
83 |
84 | iex> delete_post(post)
85 | {:error, %Ecto.Changeset{}}
86 |
87 | """
88 | def delete_post(%Post{} = post) do
89 | Repo.delete(post)
90 | end
91 |
92 | @doc """
93 | Returns an `%Ecto.Changeset{}` for tracking post changes.
94 |
95 | ## Examples
96 |
97 | iex> change_post(post)
98 | %Ecto.Changeset{source: %Post{}}
99 |
100 | """
101 | def change_post(%Post{} = post) do
102 | Post.changeset(post, %{})
103 | end
104 | end
105 |
--------------------------------------------------------------------------------
/test/coherence_demo/blogs/blogs_test.exs:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemo.BlogsTest do
2 | use CoherenceDemo.DataCase
3 |
4 | alias CoherenceDemo.Blogs
5 |
6 | describe "posts" do
7 | alias CoherenceDemo.Blogs.Post
8 |
9 | @valid_attrs %{body: "some body", title: "some title"}
10 | @update_attrs %{body: "some updated body", title: "some updated title"}
11 | @invalid_attrs %{body: nil, title: nil}
12 |
13 | def post_fixture(attrs \\ %{}) do
14 | {:ok, post} =
15 | attrs
16 | |> Enum.into(@valid_attrs)
17 | |> Blogs.create_post()
18 |
19 | post
20 | end
21 |
22 | test "list_posts/0 returns all posts" do
23 | post = post_fixture()
24 | assert Blogs.list_posts() == [post]
25 | end
26 |
27 | test "get_post!/1 returns the post with given id" do
28 | post = post_fixture()
29 | assert Blogs.get_post!(post.id) == post
30 | end
31 |
32 | test "create_post/1 with valid data creates a post" do
33 | assert {:ok, %Post{} = post} = Blogs.create_post(@valid_attrs)
34 | assert post.body == "some body"
35 | assert post.title == "some title"
36 | end
37 |
38 | test "create_post/1 with invalid data returns error changeset" do
39 | assert {:error, %Ecto.Changeset{}} = Blogs.create_post(@invalid_attrs)
40 | end
41 |
42 | test "update_post/2 with valid data updates the post" do
43 | post = post_fixture()
44 | assert {:ok, post} = Blogs.update_post(post, @update_attrs)
45 | assert %Post{} = post
46 | assert post.body == "some updated body"
47 | assert post.title == "some updated title"
48 | end
49 |
50 | test "update_post/2 with invalid data returns error changeset" do
51 | post = post_fixture()
52 | assert {:error, %Ecto.Changeset{}} = Blogs.update_post(post, @invalid_attrs)
53 | assert post == Blogs.get_post!(post.id)
54 | end
55 |
56 | test "delete_post/1 deletes the post" do
57 | post = post_fixture()
58 | assert {:ok, %Post{}} = Blogs.delete_post(post)
59 | assert_raise Ecto.NoResultsError, fn -> Blogs.get_post!(post.id) end
60 | end
61 |
62 | test "change_post/1 returns a post changeset" do
63 | post = post_fixture()
64 | assert %Ecto.Changeset{} = Blogs.change_post(post)
65 | end
66 | end
67 | end
68 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/templates/coherence/registration/form.html.eex:
--------------------------------------------------------------------------------
1 | <%= form_for @changeset, @action, [as: :registration], fn f -> %>
2 |
3 | <%= if @changeset.action do %>
4 |
5 |
<%= dgettext "coherence", "Oops, something went wrong! Please check the errors below." %>
6 |
7 | <% end %>
8 |
9 |
10 | <%= required_label f, dgettext("coherence", "Name"), class: "control-label" %>
11 | <%= text_input f, :name, class: "form-control", required: "" %>
12 | <%= error_tag f, :name %>
13 |
14 |
15 | <%= unless (login_field = Coherence.Config.login_field) == :email do %>
16 |
17 | <%= required_label f, login_field, class: "control-label" %>
18 | <%= text_input f, login_field, class: "form-control", required: "" %>
19 | <%= error_tag f, login_field %>
20 |
21 | <% end %>
22 |
23 |
24 | <%= required_label f, dgettext("coherence", "Email"), class: "control-label" %>
25 | <%= text_input f, :email, class: "form-control", required: "" %>
26 | <%= error_tag f, :email %>
27 |
28 |
29 | <%= if Coherence.Config.require_current_password and not is_nil(@changeset.data.id) do %>
30 |
31 | <%= required_label f, :current_password, class: "control-label" %>
32 | <%= password_input f, :current_password, [class: "form-control"] ++ @required %>
33 | <%= error_tag f, :current_password %>
34 |
35 | <% end %>
36 |
37 |
38 | <%= required_label f, dgettext("coherence", "Password"), class: "control-label" %>
39 | <%= password_input f, :password, [class: "form-control"] ++ @required %>
40 | <%= error_tag f, :password %>
41 |
42 |
43 |
44 | <%= required_label f, dgettext("coherence", "Password Confirmation"), class: "control-label" %>
45 | <%= password_input f, :password_confirmation, [class: "form-control"] ++ @required %>
46 | <%= error_tag f, :password_confirmation %>
47 |
48 |
49 |
50 | <%= submit @label, class: "btn btn-primary" %>
51 | <%= link dgettext("coherence", "Cancel"), to: Coherence.Config.logged_out_url("/"), class: "btn" %>
52 |
53 | <% end %>
54 |
--------------------------------------------------------------------------------
/assets/js/socket.js:
--------------------------------------------------------------------------------
1 | // NOTE: The contents of this file will only be executed if
2 | // you uncomment its entry in "assets/js/app.js".
3 |
4 | // To use Phoenix channels, the first step is to import Socket
5 | // and connect at the socket path in "lib/web/endpoint.ex":
6 | import {Socket} from "phoenix"
7 |
8 | let socket = new Socket("/socket", {params: {token: window.userToken}})
9 |
10 | // When you connect, you'll often need to authenticate the client.
11 | // For example, imagine you have an authentication plug, `MyAuth`,
12 | // which authenticates the session and assigns a `:current_user`.
13 | // If the current user exists you can assign the user's token in
14 | // the connection for use in the layout.
15 | //
16 | // In your "lib/web/router.ex":
17 | //
18 | // pipeline :browser do
19 | // ...
20 | // plug MyAuth
21 | // plug :put_user_token
22 | // end
23 | //
24 | // defp put_user_token(conn, _) do
25 | // if current_user = conn.assigns[:current_user] do
26 | // token = Phoenix.Token.sign(conn, "user socket", current_user.id)
27 | // assign(conn, :user_token, token)
28 | // else
29 | // conn
30 | // end
31 | // end
32 | //
33 | // Now you need to pass this token to JavaScript. You can do so
34 | // inside a script tag in "lib/web/templates/layout/app.html.eex":
35 | //
36 | //
37 | //
38 | // You will need to verify the user token in the "connect/2" function
39 | // in "lib/web/channels/user_socket.ex":
40 | //
41 | // def connect(%{"token" => token}, socket) do
42 | // # max_age: 1209600 is equivalent to two weeks in seconds
43 | // case Phoenix.Token.verify(socket, "user socket", token, max_age: 1209600) do
44 | // {:ok, user_id} ->
45 | // {:ok, assign(socket, :user, user_id)}
46 | // {:error, reason} ->
47 | // :error
48 | // end
49 | // end
50 | //
51 | // Finally, pass the token on connect as below. Or remove it
52 | // from connect if you don't care about authentication.
53 |
54 | socket.connect()
55 |
56 | // Now that you are connected, you can join channels with a topic:
57 | let channel = socket.channel("topic:subtopic", {})
58 | channel.join()
59 | .receive("ok", resp => { console.log("Joined successfully", resp) })
60 | .receive("error", resp => { console.log("Unable to join", resp) })
61 |
62 | export default socket
63 |
--------------------------------------------------------------------------------
/config/prod.exs:
--------------------------------------------------------------------------------
1 | use Mix.Config
2 |
3 | # For production, we often load configuration from external
4 | # sources, such as your system environment. For this reason,
5 | # you won't find the :http configuration below, but set inside
6 | # CoherenceDemoWeb.Endpoint.init/2 when load_from_system_env is
7 | # true. Any dynamic configuration should be done there.
8 | #
9 | # Don't forget to configure the url host to something meaningful,
10 | # Phoenix uses this information when generating URLs.
11 | #
12 | # Finally, we also include the path to a cache manifest
13 | # containing the digested version of static files. This
14 | # manifest is generated by the mix phx.digest task
15 | # which you typically run after static files are built.
16 | config :coherence_demo, CoherenceDemoWeb.Endpoint,
17 | load_from_system_env: true,
18 | url: [host: "example.com", port: 80],
19 | cache_static_manifest: "priv/static/cache_manifest.json"
20 |
21 | # Do not print debug messages in production
22 | config :logger, level: :info
23 |
24 | # ## SSL Support
25 | #
26 | # To get SSL working, you will need to add the `https` key
27 | # to the previous section and set your `:url` port to 443:
28 | #
29 | # config :coherence_demo, CoherenceDemoWeb.Endpoint,
30 | # ...
31 | # url: [host: "example.com", port: 443],
32 | # https: [:inet6,
33 | # port: 443,
34 | # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
35 | # certfile: System.get_env("SOME_APP_SSL_CERT_PATH")]
36 | #
37 | # Where those two env variables return an absolute path to
38 | # the key and cert in disk or a relative path inside priv,
39 | # for example "priv/ssl/server.key".
40 | #
41 | # We also recommend setting `force_ssl`, ensuring no data is
42 | # ever sent via http, always redirecting to https:
43 | #
44 | # config :coherence_demo, CoherenceDemoWeb.Endpoint,
45 | # force_ssl: [hsts: true]
46 | #
47 | # Check `Plug.SSL` for all available options in `force_ssl`.
48 |
49 | # ## Using releases
50 | #
51 | # If you are doing OTP releases, you need to instruct Phoenix
52 | # to start the server for all endpoints:
53 | #
54 | # config :phoenix, :serve_endpoints, true
55 | #
56 | # Alternatively, you can configure exactly which server to
57 | # start per endpoint:
58 | #
59 | # config :coherence_demo, CoherenceDemoWeb.Endpoint, server: true
60 | #
61 |
62 | # Finally import the config/prod.secret.exs
63 | # which should be versioned separately.
64 | import_config "prod.secret.exs"
65 |
--------------------------------------------------------------------------------
/priv/gettext/en/LC_MESSAGES/errors.po:
--------------------------------------------------------------------------------
1 | ## `msgid`s in this file come from POT (.pot) files.
2 | ##
3 | ## Do not add, change, or remove `msgid`s manually here as
4 | ## they're tied to the ones in the corresponding POT file
5 | ## (with the same domain).
6 | ##
7 | ## Use `mix gettext.extract --merge` or `mix gettext.merge`
8 | ## to merge POT files into PO files.
9 | msgid ""
10 | msgstr ""
11 | "Language: en\n"
12 |
13 | ## From Ecto.Changeset.cast/4
14 | msgid "can't be blank"
15 | msgstr ""
16 |
17 | ## From Ecto.Changeset.unique_constraint/3
18 | msgid "has already been taken"
19 | msgstr ""
20 |
21 | ## From Ecto.Changeset.put_change/3
22 | msgid "is invalid"
23 | msgstr ""
24 |
25 | ## From Ecto.Changeset.validate_acceptance/3
26 | msgid "must be accepted"
27 | msgstr ""
28 |
29 | ## From Ecto.Changeset.validate_format/3
30 | msgid "has invalid format"
31 | msgstr ""
32 |
33 | ## From Ecto.Changeset.validate_subset/3
34 | msgid "has an invalid entry"
35 | msgstr ""
36 |
37 | ## From Ecto.Changeset.validate_exclusion/3
38 | msgid "is reserved"
39 | msgstr ""
40 |
41 | ## From Ecto.Changeset.validate_confirmation/3
42 | msgid "does not match confirmation"
43 | msgstr ""
44 |
45 | ## From Ecto.Changeset.no_assoc_constraint/3
46 | msgid "is still associated with this entry"
47 | msgstr ""
48 |
49 | msgid "are still associated with this entry"
50 | msgstr ""
51 |
52 | ## From Ecto.Changeset.validate_length/3
53 | msgid "should be %{count} character(s)"
54 | msgid_plural "should be %{count} character(s)"
55 | msgstr[0] ""
56 | msgstr[1] ""
57 |
58 | msgid "should have %{count} item(s)"
59 | msgid_plural "should have %{count} item(s)"
60 | msgstr[0] ""
61 | msgstr[1] ""
62 |
63 | msgid "should be at least %{count} character(s)"
64 | msgid_plural "should be at least %{count} character(s)"
65 | msgstr[0] ""
66 | msgstr[1] ""
67 |
68 | msgid "should have at least %{count} item(s)"
69 | msgid_plural "should have at least %{count} item(s)"
70 | msgstr[0] ""
71 | msgstr[1] ""
72 |
73 | msgid "should be at most %{count} character(s)"
74 | msgid_plural "should be at most %{count} character(s)"
75 | msgstr[0] ""
76 | msgstr[1] ""
77 |
78 | msgid "should have at most %{count} item(s)"
79 | msgid_plural "should have at most %{count} item(s)"
80 | msgstr[0] ""
81 | msgstr[1] ""
82 |
83 | ## From Ecto.Changeset.validate_number/3
84 | msgid "must be less than %{number}"
85 | msgstr ""
86 |
87 | msgid "must be greater than %{number}"
88 | msgstr ""
89 |
90 | msgid "must be less than or equal to %{number}"
91 | msgstr ""
92 |
93 | msgid "must be greater than or equal to %{number}"
94 | msgstr ""
95 |
96 | msgid "must be equal to %{number}"
97 | msgstr ""
98 |
--------------------------------------------------------------------------------
/priv/gettext/errors.pot:
--------------------------------------------------------------------------------
1 | ## This file is a PO Template file.
2 | ##
3 | ## `msgid`s here are often extracted from source code.
4 | ## Add new translations manually only if they're dynamic
5 | ## translations that can't be statically extracted.
6 | ##
7 | ## Run `mix gettext.extract` to bring this file up to
8 | ## date. Leave `msgstr`s empty as changing them here as no
9 | ## effect: edit them in PO (`.po`) files instead.
10 |
11 | ## From Ecto.Changeset.cast/4
12 | msgid "can't be blank"
13 | msgstr ""
14 |
15 | ## From Ecto.Changeset.unique_constraint/3
16 | msgid "has already been taken"
17 | msgstr ""
18 |
19 | ## From Ecto.Changeset.put_change/3
20 | msgid "is invalid"
21 | msgstr ""
22 |
23 | ## From Ecto.Changeset.validate_acceptance/3
24 | msgid "must be accepted"
25 | msgstr ""
26 |
27 | ## From Ecto.Changeset.validate_format/3
28 | msgid "has invalid format"
29 | msgstr ""
30 |
31 | ## From Ecto.Changeset.validate_subset/3
32 | msgid "has an invalid entry"
33 | msgstr ""
34 |
35 | ## From Ecto.Changeset.validate_exclusion/3
36 | msgid "is reserved"
37 | msgstr ""
38 |
39 | ## From Ecto.Changeset.validate_confirmation/3
40 | msgid "does not match confirmation"
41 | msgstr ""
42 |
43 | ## From Ecto.Changeset.no_assoc_constraint/3
44 | msgid "is still associated with this entry"
45 | msgstr ""
46 |
47 | msgid "are still associated with this entry"
48 | msgstr ""
49 |
50 | ## From Ecto.Changeset.validate_length/3
51 | msgid "should be %{count} character(s)"
52 | msgid_plural "should be %{count} character(s)"
53 | msgstr[0] ""
54 | msgstr[1] ""
55 |
56 | msgid "should have %{count} item(s)"
57 | msgid_plural "should have %{count} item(s)"
58 | msgstr[0] ""
59 | msgstr[1] ""
60 |
61 | msgid "should be at least %{count} character(s)"
62 | msgid_plural "should be at least %{count} character(s)"
63 | msgstr[0] ""
64 | msgstr[1] ""
65 |
66 | msgid "should have at least %{count} item(s)"
67 | msgid_plural "should have at least %{count} item(s)"
68 | msgstr[0] ""
69 | msgstr[1] ""
70 |
71 | msgid "should be at most %{count} character(s)"
72 | msgid_plural "should be at most %{count} character(s)"
73 | msgstr[0] ""
74 | msgstr[1] ""
75 |
76 | msgid "should have at most %{count} item(s)"
77 | msgid_plural "should have at most %{count} item(s)"
78 | msgstr[0] ""
79 | msgstr[1] ""
80 |
81 | ## From Ecto.Changeset.validate_number/3
82 | msgid "must be less than %{number}"
83 | msgstr ""
84 |
85 | msgid "must be greater than %{number}"
86 | msgstr ""
87 |
88 | msgid "must be less than or equal to %{number}"
89 | msgstr ""
90 |
91 | msgid "must be greater than or equal to %{number}"
92 | msgstr ""
93 |
94 | msgid "must be equal to %{number}"
95 | msgstr ""
96 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/emails/coherence/user_email.ex:
--------------------------------------------------------------------------------
1 | Code.ensure_loaded Phoenix.Swoosh
2 |
3 | defmodule CoherenceDemoWeb.Coherence.UserEmail do
4 | @moduledoc false
5 | use Phoenix.Swoosh, view: CoherenceDemoWeb.Coherence.EmailView, layout: {CoherenceDemoWeb.Coherence.LayoutView, :email}
6 | alias Swoosh.Email
7 | require Logger
8 | alias Coherence.Config
9 | import CoherenceDemoWeb.Gettext
10 |
11 | defp site_name, do: Config.site_name(inspect Config.module)
12 |
13 | def password(user, url) do
14 | %Email{}
15 | |> from(from_email())
16 | |> to(user_email(user))
17 | |> add_reply_to()
18 | |> subject(dgettext("coherence", "%{site_name} - Reset password instructions", site_name: site_name()))
19 | |> render_body("password.html", %{url: url, name: first_name(user.name)})
20 | end
21 |
22 | def confirmation(user, url) do
23 | %Email{}
24 | |> from(from_email())
25 | |> to(user_email(user))
26 | |> add_reply_to()
27 | |> subject(dgettext("coherence", "%{site_name} - Confirm your new account", site_name: site_name()))
28 | |> render_body("confirmation.html", %{url: url, name: first_name(user.name)})
29 | end
30 |
31 | def invitation(invitation, url) do
32 | %Email{}
33 | |> from(from_email())
34 | |> to(user_email(invitation))
35 | |> add_reply_to()
36 | |> subject(dgettext("coherence", "%{site_name} - Invitation to create a new account", site_name: site_name()))
37 | |> render_body("invitation.html", %{url: url, name: first_name(invitation.name)})
38 | end
39 |
40 | def unlock(user, url) do
41 | %Email{}
42 | |> from(from_email())
43 | |> to(user_email(user))
44 | |> add_reply_to()
45 | |> subject(dgettext("coherence", "%{site_name} - Unlock Instructions", site_name: site_name()))
46 | |> render_body("unlock.html", %{url: url, name: first_name(user.name)})
47 | end
48 |
49 | defp add_reply_to(mail) do
50 | case Coherence.Config.email_reply_to do
51 | nil -> mail
52 | true -> reply_to mail, from_email()
53 | address -> reply_to mail, address
54 | end
55 | end
56 |
57 | defp first_name(name) do
58 | case String.split(name, " ") do
59 | [first_name | _] -> first_name
60 | _ -> name
61 | end
62 | end
63 |
64 | defp user_email(user) do
65 | {user.name, user.email}
66 | end
67 |
68 | defp from_email do
69 | case Coherence.Config.email_from do
70 | nil ->
71 | Logger.error ~s|Need to configure :coherence, :email_from_name, "Name", and :email_from_email, "me@example.com"|
72 | nil
73 | {name, email} = email_tuple ->
74 | if is_nil(name) or is_nil(email) do
75 | Logger.error ~s|Need to configure :coherence, :email_from_name, "Name", and :email_from_email, "me@example.com"|
76 | nil
77 | else
78 | email_tuple
79 | end
80 | end
81 | end
82 | end
83 |
--------------------------------------------------------------------------------
/test/coherence_demo_web/controllers/post_controller_test.exs:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.PostControllerTest do
2 | use CoherenceDemoWeb.ConnCase
3 |
4 | alias CoherenceDemo.Blogs
5 |
6 | @create_attrs %{body: "some body", title: "some title"}
7 | @update_attrs %{body: "some updated body", title: "some updated title"}
8 | @invalid_attrs %{body: nil, title: nil}
9 |
10 | def fixture(:post) do
11 | {:ok, post} = Blogs.create_post(@create_attrs)
12 | post
13 | end
14 |
15 | describe "index" do
16 | test "lists all posts", %{conn: conn} do
17 | conn = get conn, post_path(conn, :index)
18 | assert html_response(conn, 200) =~ "Listing Posts"
19 | end
20 | end
21 |
22 | describe "new post" do
23 | test "renders form", %{conn: conn} do
24 | conn = get conn, post_path(conn, :new)
25 | assert html_response(conn, 200) =~ "New Post"
26 | end
27 | end
28 |
29 | describe "create post" do
30 | test "redirects to show when data is valid", %{conn: conn} do
31 | conn = post conn, post_path(conn, :create), post: @create_attrs
32 |
33 | assert %{id: id} = redirected_params(conn)
34 | assert redirected_to(conn) == post_path(conn, :show, id)
35 |
36 | conn = get conn, post_path(conn, :show, id)
37 | assert html_response(conn, 200) =~ "Show Post"
38 | end
39 |
40 | test "renders errors when data is invalid", %{conn: conn} do
41 | conn = post conn, post_path(conn, :create), post: @invalid_attrs
42 | assert html_response(conn, 200) =~ "New Post"
43 | end
44 | end
45 |
46 | describe "edit post" do
47 | setup [:create_post]
48 |
49 | test "renders form for editing chosen post", %{conn: conn, post: post} do
50 | conn = get conn, post_path(conn, :edit, post)
51 | assert html_response(conn, 200) =~ "Edit Post"
52 | end
53 | end
54 |
55 | describe "update post" do
56 | setup [:create_post]
57 |
58 | test "redirects when data is valid", %{conn: conn, post: post} do
59 | conn = put conn, post_path(conn, :update, post), post: @update_attrs
60 | assert redirected_to(conn) == post_path(conn, :show, post)
61 |
62 | conn = get conn, post_path(conn, :show, post)
63 | assert html_response(conn, 200) =~ "some updated body"
64 | end
65 |
66 | test "renders errors when data is invalid", %{conn: conn, post: post} do
67 | conn = put conn, post_path(conn, :update, post), post: @invalid_attrs
68 | assert html_response(conn, 200) =~ "Edit Post"
69 | end
70 | end
71 |
72 | describe "delete post" do
73 | setup [:create_post]
74 |
75 | test "deletes chosen post", %{conn: conn, post: post} do
76 | conn = delete conn, post_path(conn, :delete, post)
77 | assert redirected_to(conn) == post_path(conn, :index)
78 | assert_error_sent 404, fn ->
79 | get conn, post_path(conn, :show, post)
80 | end
81 | end
82 | end
83 |
84 | defp create_post(_) do
85 | post = fixture(:post)
86 | {:ok, post: post}
87 | end
88 | end
89 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/controllers/user_controller.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.UserController do
2 | use CoherenceDemoWeb, :controller
3 | use Timex
4 |
5 | alias Coherence.Controller
6 | alias CoherenceDemo.Coherence.User
7 |
8 | def index(conn, _params) do
9 | users = Repo.all(User)
10 | render(conn, "index.html", users: users)
11 | end
12 |
13 | def new(conn, _params) do
14 | changeset = User.changeset(%User{})
15 | render(conn, "new.html", changeset: changeset)
16 | end
17 |
18 | def create(conn, %{"user" => user_params}) do
19 | changeset = User.changeset(%User{}, user_params)
20 |
21 | case Repo.insert(changeset) do
22 | {:ok, _user} ->
23 | conn
24 | |> put_flash(:info, "User created successfully.")
25 | |> redirect(to: user_path(conn, :index))
26 | {:error, changeset} ->
27 | render(conn, "new.html", changeset: changeset)
28 | end
29 | end
30 |
31 | def show(conn, %{"id" => id}) do
32 | user = Repo.get!(User, id)
33 | render(conn, "show.html", user: user)
34 | end
35 |
36 | def edit(conn, %{"id" => id}) do
37 | user = Repo.get!(User, id)
38 | changeset = User.changeset(user)
39 | render(conn, "edit.html", user: user, changeset: changeset)
40 | end
41 |
42 | def update(conn, %{"id" => id, "user" => user_params}) do
43 | user = Repo.get!(User, id)
44 | changeset = User.changeset(user, user_params)
45 |
46 | case Repo.update(changeset) do
47 | {:ok, user} ->
48 | conn
49 | |> put_flash(:info, "User updated successfully.")
50 | |> redirect(to: user_path(conn, :show, user))
51 | {:error, changeset} ->
52 | render(conn, "edit.html", user: user, changeset: changeset)
53 | end
54 | end
55 |
56 | def delete(conn, %{"id" => id}) do
57 | user = Repo.get!(User, id)
58 |
59 | # Here we use delete! (with a bang) because we expect
60 | # it to always work (and if it does not, it will raise).
61 | Repo.delete!(user)
62 |
63 | conn
64 | |> put_flash(:info, "User deleted successfully.")
65 | |> redirect(to: user_path(conn, :index))
66 | end
67 |
68 | def confirm(conn, %{"id" => id}) do
69 | case Repo.get User, id do
70 | nil ->
71 | conn
72 | |> put_flash(:error, "User not found")
73 | |> redirect(to: user_path(conn, :index))
74 | user ->
75 | case Controller.confirm! user do
76 | {:error, changeset} ->
77 | conn
78 | |> put_flash(:error, format_errors(changeset))
79 | _ ->
80 | put_flash(conn, :info, "User confirmed!")
81 | end
82 | |> redirect(to: user_path(conn, :show, user.id))
83 | end
84 | end
85 |
86 | def lock(conn, %{"id" => id}) do
87 | locked_at = DateTime.utc_now
88 | |> Timex.shift(years: 10)
89 |
90 | case Repo.get User, id do
91 | nil ->
92 | conn
93 | |> put_flash(:error, "User not found")
94 | |> redirect(to: user_path(conn, :index))
95 | user ->
96 | case Controller.lock! user, locked_at do
97 | {:error, changeset} ->
98 | conn
99 | |> put_flash(:error, format_errors(changeset))
100 | _ ->
101 | put_flash(conn, :info, "User locked!")
102 | end
103 | |> redirect(to: user_path(conn, :show, user.id))
104 | end
105 | end
106 |
107 | def unlock(conn, %{"id" => id}) do
108 | case Repo.get User, id do
109 | nil ->
110 | conn
111 | |> put_flash(:error, "User not found")
112 | |> redirect(to: user_path(conn, :index))
113 | user ->
114 | case Controller.unlock! user do
115 | {:error, changeset} ->
116 | conn
117 | |> put_flash(:error, format_errors(changeset))
118 | _ ->
119 | put_flash(conn, :info, "User unlocked!")
120 | end
121 | |> redirect(to: user_path(conn, :show, user.id))
122 | end
123 | end
124 | defp format_errors(changeset) do
125 | for error <- changeset.errors do
126 | case error do
127 | {:locked_at, {err, _}} -> err
128 | {_field, {err, _}} when is_binary(err) or is_atom(err) ->
129 | "#{err}"
130 | other -> inspect other
131 | end
132 | end
133 | |> Enum.join(" \n")
134 | end
135 | end
136 |
--------------------------------------------------------------------------------
/lib/coherence_demo/coherence/schemas.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemo.Coherence.Schemas do
2 |
3 | use Coherence.Config
4 |
5 | import Ecto.Query
6 |
7 | @user_schema Config.user_schema
8 | @repo Config.repo
9 |
10 | def list_user do
11 | @repo.all @user_schema
12 | end
13 |
14 | def list_by_user(opts) do
15 | @repo.all query_by(@user_schema, opts)
16 | end
17 |
18 | def get_by_user(opts) do
19 | @repo.get_by @user_schema, opts
20 | end
21 |
22 | def get_user(id) do
23 | @repo.get @user_schema, id
24 | end
25 |
26 | def get_user!(id) do
27 | @repo.get! @user_schema, id
28 | end
29 |
30 | def get_user_by_email(email) do
31 | @repo.get_by @user_schema, email: email
32 | end
33 |
34 | def change_user(struct, params) do
35 | @user_schema.changeset struct, params
36 | end
37 |
38 | def change_user(params) do
39 | @user_schema.changeset @user_schema.__struct__, params
40 | end
41 |
42 | def change_user do
43 | @user_schema.changeset @user_schema.__struct__, %{}
44 | end
45 |
46 | def create_user(params) do
47 | @repo.insert change_user(params)
48 | end
49 |
50 | def create_user!(params) do
51 | @repo.insert! change_user(params)
52 | end
53 |
54 | def update_user(user, params) do
55 | @repo.update change_user(user, params)
56 | end
57 |
58 | def update_user!(user, params) do
59 | @repo.update! change_user(user, params)
60 | end
61 |
62 | Enum.each [CoherenceDemo.Coherence.Invitation, CoherenceDemo.Coherence.Rememberable], fn module ->
63 |
64 | name =
65 | module
66 | |> Module.split
67 | |> List.last
68 | |> String.downcase
69 |
70 | def unquote(String.to_atom("list_#{name}"))() do
71 | @repo.all unquote(module)
72 | end
73 |
74 | def unquote(String.to_atom("list_#{name}"))(%Ecto.Query{} = query) do
75 | @repo.all query
76 | end
77 |
78 | def unquote(String.to_atom("list_by_#{name}"))(opts) do
79 | @repo.all query_by(unquote(module), opts)
80 | end
81 |
82 | def unquote(String.to_atom("get_#{name}"))(id) do
83 | @repo.get unquote(module), id
84 | end
85 |
86 | def unquote(String.to_atom("get_#{name}!"))(id) do
87 | @repo.get! unquote(module), id
88 | end
89 |
90 | def unquote(String.to_atom("get_by_#{name}"))(opts) do
91 | @repo.get_by unquote(module), opts
92 | end
93 |
94 | def unquote(String.to_atom("change_#{name}"))(struct, params) do
95 | unquote(module).changeset(struct, params)
96 | end
97 |
98 | def unquote(String.to_atom("change_#{name}"))(params) do
99 | unquote(module).new_changeset(params)
100 | end
101 |
102 | def unquote(String.to_atom("change_#{name}"))() do
103 | unquote(module).new_changeset(%{})
104 | end
105 |
106 | def unquote(String.to_atom("create_#{name}"))(params) do
107 | @repo.insert unquote(module).new_changeset(params)
108 | end
109 |
110 | def unquote(String.to_atom("create_#{name}!"))(params) do
111 | @repo.insert! unquote(module).new_changeset(params)
112 | end
113 |
114 | def unquote(String.to_atom("update_#{name}"))(struct, params) do
115 | @repo.update unquote(module).changeset(struct, params)
116 | end
117 |
118 | def unquote(String.to_atom("update_#{name}!"))(struct, params) do
119 | @repo.update! unquote(module).changeset(struct, params)
120 | end
121 |
122 | def unquote(String.to_atom("delete_#{name}"))(struct) do
123 | @repo.delete struct
124 | end
125 | end
126 |
127 | def query_by(schema, opts) do
128 | Enum.reduce opts, schema, fn {k, v}, query ->
129 | where(query, [b], field(b, ^k) == ^v)
130 | end
131 | end
132 |
133 | def delete_all(%Ecto.Query{} = query) do
134 | @repo.delete_all query
135 | end
136 |
137 | def delete_all(module) when is_atom(module) do
138 | @repo.delete_all module
139 | end
140 |
141 | def create(%Ecto.Changeset{} = changeset) do
142 | @repo.insert changeset
143 | end
144 |
145 | def create!(%Ecto.Changeset{} = changeset) do
146 | @repo.insert! changeset
147 | end
148 |
149 | def update(%Ecto.Changeset{} = changeset) do
150 | @repo.update changeset
151 | end
152 |
153 | def update!(%Ecto.Changeset{} = changeset) do
154 | @repo.update! changeset
155 | end
156 |
157 | def delete(schema) do
158 | @repo.delete schema
159 | end
160 |
161 | def delete!(schema) do
162 | @repo.delete! schema
163 | end
164 |
165 | end
166 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/coherence_messages.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.Coherence.Messages do
2 | @moduledoc """
3 | Application facing messages generated by the Coherence application.
4 |
5 | This module was created by the coh.install mix task. It contains all the
6 | messages used in the coherence application except those in other generated
7 | files like the view and templates.
8 |
9 | To assist in upgrading Coherence, the `Coherence.Messages behaviour will
10 | alway contain every message for the current version. This will help in upgrades
11 | to ensure the user had added new the new messages from the current version.
12 | """
13 | @behaviour Coherence.Messages
14 |
15 | import CoherenceDemoWeb.Gettext
16 |
17 | # Change this to override the "coherence" gettext domain. If you would like
18 | # the coherence message to be part of your projects domain change it to "default"
19 | @domain "coherence"
20 |
21 | ##################
22 | # Messages
23 |
24 | def account_already_confirmed, do: dgettext(@domain, "Account already confirmed.")
25 | def account_is_not_locked, do: dgettext(@domain, "Account is not locked.")
26 | def account_updated_successfully, do: dgettext(@domain, "Account updated successfully.")
27 | def already_confirmed, do: dgettext(@domain, "already confirmed")
28 | def already_locked, do: dgettext(@domain, "already locked")
29 | def already_logged_in, do: dgettext(@domain, "Already logged in.")
30 | def cant_be_blank, do: dgettext(@domain, "can't be blank")
31 | def cant_find_that_token, do: dgettext(@domain, "Can't find that token")
32 | def confirmation_email_sent, do: dgettext(@domain, "Confirmation email sent.")
33 | def confirmation_token_expired, do: dgettext(@domain, "Confirmation token expired.")
34 | def could_not_find_that_email_address, do: dgettext(@domain, "Could not find that email address")
35 | def forgot_your_password, do: dgettext(@domain, "Forgot your password?")
36 | def http_authentication_required, do: dgettext(@domain, "HTTP Authentication Required")
37 | def incorrect_login_or_password(opts), do: dgettext(@domain, "Incorrect %{login_field} or password.", opts)
38 | def invalid_current_password, do: dgettext(@domain, "invalid current password")
39 | def invalid_invitation, do: dgettext(@domain, "Invalid Invitation. Please contact the site administrator.")
40 | def invalid_request, do: dgettext(@domain, "Invalid Request.")
41 | def invalid_confirmation_token, do: dgettext(@domain, "Invalid confirmation token.")
42 | def invalid_email_or_password, do: dgettext(@domain, "Invalid email or password.")
43 | def invalid_invitation_token, do: dgettext(@domain, "Invalid invitation token.")
44 | def invalid_reset_token, do: dgettext(@domain, "Invalid reset token.")
45 | def invalid_unlock_token, do: dgettext(@domain, "Invalid unlock token.")
46 | def invitation_already_sent, do: dgettext(@domain, "Invitation already sent.")
47 | def invitation_sent, do: dgettext(@domain, "Invitation sent.")
48 | def invite_someone, do: dgettext(@domain, "Invite Someone")
49 | def maximum_login_attempts_exceeded, do: dgettext(@domain, "Maximum Login attempts exceeded. Your account has been locked.")
50 | def need_an_account, do: dgettext(@domain, "Need An Account?")
51 | def not_locked, do: dgettext(@domain, "not locked")
52 | def password_reset_token_expired, do: dgettext(@domain, "Password reset token expired.")
53 | def password_updated_successfully, do: dgettext(@domain, "Password updated successfully.")
54 | def problem_confirming_user_account, do: dgettext(@domain, "Problem confirming user account. Please contact the system administrator.")
55 | def registration_created_successfully, do: dgettext(@domain, "Registration created successfully.")
56 | def required, do: dgettext(@domain, "required")
57 | def resend_confirmation_email, do: dgettext(@domain, "Resend confirmation email")
58 | def reset_email_sent, do: dgettext(@domain, "Reset email sent. Check your email for a reset link.")
59 | def restricted_area, do: dgettext(@domain, "Restricted Area")
60 | def send_an_unlock_email, do: dgettext(@domain, "Send an unlock email")
61 | def sign_in, do: dgettext(@domain, "Sign In")
62 | def sign_out, do: dgettext(@domain, "Sign Out")
63 | def signed_in_successfully, do: dgettext(@domain, "Signed in successfully.")
64 | def too_many_failed_login_attempts, do: dgettext(@domain, "Too many failed login attempts. Account has been locked.")
65 | def unauthorized_ip_address, do: dgettext(@domain, "Unauthorized IP Address")
66 | def unlock_instructions_sent, do: dgettext(@domain, "Unlock Instructions sent.")
67 | def user_account_confirmed_successfully, do: dgettext(@domain, "User account confirmed successfully.")
68 | def user_already_has_an_account, do: dgettext(@domain, "User already has an account!")
69 | def you_must_confirm_your_account, do: dgettext(@domain, "You must confirm your account before you can login.")
70 | def your_account_has_been_unlocked, do: dgettext(@domain, "Your account has been unlocked")
71 | def your_account_is_not_locked, do: dgettext(@domain, "Your account is not locked.")
72 | def verify_user_token(opts),
73 | do: dgettext(@domain, "Invalid %{user_token} error: %{error}", opts)
74 | def you_are_using_an_invalid_security_token,
75 | do: dgettext(@domain, "You are using an invalid security token for this site! This security\n" <>
76 | "violation has been logged.\n")
77 | def mailer_required, do: dgettext(@domain, "Mailer configuration required!")
78 | def account_is_inactive(), do: dgettext(@domain, "Account is inactive!")
79 | end
80 |
--------------------------------------------------------------------------------
/mix.lock:
--------------------------------------------------------------------------------
1 | %{"certifi": {:hex, :certifi, "2.0.0", "a0c0e475107135f76b8c1d5bc7efb33cd3815cb3cf3dea7aefdd174dabead064", [], [], "hexpm"},
2 | "coherence": {:git, "https://github.com/smpallen99/coherence.git", "d2220779fe46c3528cb1bbe6e8d7e802468dc50d", []},
3 | "combine": {:hex, :combine, "0.9.6", "8d1034a127d4cbf6924c8a5010d3534d958085575fa4d9b878f200d79ac78335", [], [], "hexpm"},
4 | "comeonin": {:hex, :comeonin, "3.2.0", "cb10995a22aed6812667efb3856f548818c85d85394d8132bc116fbd6995c1ef", [], [{:elixir_make, "~> 0.4", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm"},
5 | "connection": {:hex, :connection, "1.0.4", "a1cae72211f0eef17705aaededacac3eb30e6625b04a6117c1b2db6ace7d5976", [], [], "hexpm"},
6 | "cowboy": {:hex, :cowboy, "1.1.2", "61ac29ea970389a88eca5a65601460162d370a70018afe6f949a29dca91f3bb0", [], [{:cowlib, "~> 1.0.2", [hex: :cowlib, repo: "hexpm", optional: false]}, {:ranch, "~> 1.3.2", [hex: :ranch, repo: "hexpm", optional: false]}], "hexpm"},
7 | "cowlib": {:hex, :cowlib, "1.0.2", "9d769a1d062c9c3ac753096f868ca121e2730b9a377de23dec0f7e08b1df84ee", [], [], "hexpm"},
8 | "db_connection": {:hex, :db_connection, "1.1.2", "2865c2a4bae0714e2213a0ce60a1b12d76a6efba0c51fbda59c9ab8d1accc7a8", [], [{:connection, "~> 1.0.2", [hex: :connection, repo: "hexpm", optional: false]}, {:poolboy, "~> 1.5", [hex: :poolboy, repo: "hexpm", optional: true]}, {:sbroker, "~> 1.0", [hex: :sbroker, repo: "hexpm", optional: true]}], "hexpm"},
9 | "decimal": {:hex, :decimal, "1.4.0", "fac965ce71a46aab53d3a6ce45662806bdd708a4a95a65cde8a12eb0124a1333", [], [], "hexpm"},
10 | "ecto": {:hex, :ecto, "2.1.6", "29b45f393c2ecd99f83e418ea9b0a2af6078ecb30f401481abac8a473c490f84", [], [{:db_connection, "~> 1.1", [hex: :db_connection, repo: "hexpm", optional: true]}, {:decimal, "~> 1.2", [hex: :decimal, repo: "hexpm", optional: false]}, {:mariaex, "~> 0.8.0", [hex: :mariaex, repo: "hexpm", optional: true]}, {:poison, "~> 2.2 or ~> 3.0", [hex: :poison, repo: "hexpm", optional: true]}, {:poolboy, "~> 1.5", [hex: :poolboy, repo: "hexpm", optional: false]}, {:postgrex, "~> 0.13.0", [hex: :postgrex, repo: "hexpm", optional: true]}, {:sbroker, "~> 1.0", [hex: :sbroker, repo: "hexpm", optional: true]}], "hexpm"},
11 | "elixir_make": {:hex, :elixir_make, "0.4.0", "992f38fabe705bb45821a728f20914c554b276838433349d4f2341f7a687cddf", [], [], "hexpm"},
12 | "fs": {:hex, :fs, "0.9.2", "ed17036c26c3f70ac49781ed9220a50c36775c6ca2cf8182d123b6566e49ec59", [], [], "hexpm"},
13 | "gettext": {:hex, :gettext, "0.13.1", "5e0daf4e7636d771c4c71ad5f3f53ba09a9ae5c250e1ab9c42ba9edccc476263", [], [], "hexpm"},
14 | "hackney": {:hex, :hackney, "1.9.0", "51c506afc0a365868469dcfc79a9d0b94d896ec741cfd5bd338f49a5ec515bfe", [], [{:certifi, "2.0.0", [hex: :certifi, repo: "hexpm", optional: false]}, {:idna, "5.1.0", [hex: :idna, repo: "hexpm", optional: false]}, {:metrics, "1.0.1", [hex: :metrics, repo: "hexpm", optional: false]}, {:mimerl, "1.0.2", [hex: :mimerl, repo: "hexpm", optional: false]}, {:ssl_verify_fun, "1.1.1", [hex: :ssl_verify_fun, repo: "hexpm", optional: false]}], "hexpm"},
15 | "idna": {:hex, :idna, "5.1.0", "d72b4effeb324ad5da3cab1767cb16b17939004e789d8c0ad5b70f3cea20c89a", [], [{:unicode_util_compat, "0.3.1", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm"},
16 | "metrics": {:hex, :metrics, "1.0.1", "25f094dea2cda98213cecc3aeff09e940299d950904393b2a29d191c346a8486", [], [], "hexpm"},
17 | "mime": {:hex, :mime, "1.1.0", "01c1d6f4083d8aa5c7b8c246ade95139620ef8effb009edde934e0ec3b28090a", [], [], "hexpm"},
18 | "mimerl": {:hex, :mimerl, "1.0.2", "993f9b0e084083405ed8252b99460c4f0563e41729ab42d9074fd5e52439be88", [], [], "hexpm"},
19 | "phoenix": {:hex, :phoenix, "1.3.0", "1c01124caa1b4a7af46f2050ff11b267baa3edb441b45dbf243e979cd4c5891b", [], [{:cowboy, "~> 1.0", [hex: :cowboy, repo: "hexpm", optional: true]}, {:phoenix_pubsub, "~> 1.0", [hex: :phoenix_pubsub, repo: "hexpm", optional: false]}, {:plug, "~> 1.3.3 or ~> 1.4", [hex: :plug, repo: "hexpm", optional: false]}, {:poison, "~> 2.2 or ~> 3.0", [hex: :poison, repo: "hexpm", optional: false]}], "hexpm"},
20 | "phoenix_ecto": {:hex, :phoenix_ecto, "3.2.3", "450c749876ff1de4a78fdb305a142a76817c77a1cd79aeca29e5fc9a6c630b26", [], [{:ecto, "~> 2.1", [hex: :ecto, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 2.9", [hex: :phoenix_html, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm"},
21 | "phoenix_html": {:hex, :phoenix_html, "2.10.3", "432dec9e04372eeb7a6dbf59a778cf43eb44518441932217371fa535f2bcfd80", [], [{:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm"},
22 | "phoenix_live_reload": {:hex, :phoenix_live_reload, "1.0.8", "4333f9c74190f485a74866beff2f9304f069d53f047f5fbb0fb8d1ee4c495f73", [], [{:fs, "~> 0.9.1", [hex: :fs, repo: "hexpm", optional: false]}, {:phoenix, "~> 1.0 or ~> 1.2-rc", [hex: :phoenix, repo: "hexpm", optional: false]}], "hexpm"},
23 | "phoenix_pubsub": {:hex, :phoenix_pubsub, "1.0.2", "bfa7fd52788b5eaa09cb51ff9fcad1d9edfeb68251add458523f839392f034c1", [], [], "hexpm"},
24 | "phoenix_swoosh": {:hex, :phoenix_swoosh, "0.2.0", "a7e0b32077cd6d2323ae15198839b05d9caddfa20663fd85787479e81f89520e", [], [{:phoenix, "~> 1.0", [hex: :phoenix, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 2.2", [hex: :phoenix_html, repo: "hexpm", optional: false]}, {:swoosh, "~> 0.1", [hex: :swoosh, repo: "hexpm", optional: false]}], "hexpm"},
25 | "plug": {:hex, :plug, "1.4.3", "236d77ce7bf3e3a2668dc0d32a9b6f1f9b1f05361019946aae49874904be4aed", [], [{:cowboy, "~> 1.0.1 or ~> 1.1", [hex: :cowboy, repo: "hexpm", optional: true]}, {:mime, "~> 1.0", [hex: :mime, repo: "hexpm", optional: false]}], "hexpm"},
26 | "poison": {:hex, :poison, "3.1.0", "d9eb636610e096f86f25d9a46f35a9facac35609a7591b3be3326e99a0484665", [], [], "hexpm"},
27 | "poolboy": {:hex, :poolboy, "1.5.1", "6b46163901cfd0a1b43d692657ed9d7e599853b3b21b95ae5ae0a777cf9b6ca8", [], [], "hexpm"},
28 | "postgrex": {:hex, :postgrex, "0.13.3", "c277cfb2a9c5034d445a722494c13359e361d344ef6f25d604c2353185682bfc", [], [{:connection, "~> 1.0", [hex: :connection, repo: "hexpm", optional: false]}, {:db_connection, "~> 1.1", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.0", [hex: :decimal, repo: "hexpm", optional: false]}], "hexpm"},
29 | "ranch": {:hex, :ranch, "1.3.2", "e4965a144dc9fbe70e5c077c65e73c57165416a901bd02ea899cfd95aa890986", [], [], "hexpm"},
30 | "ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.1", "28a4d65b7f59893bc2c7de786dec1e1555bd742d336043fe644ae956c3497fbe", [], [], "hexpm"},
31 | "swoosh": {:hex, :swoosh, "0.8.1", "1d169e4b377095feba9b4456dac446155b11cde57f3a612c37035f073104f6f8", [], [{:cowboy, "~> 1.0", [hex: :cowboy, repo: "hexpm", optional: true]}, {:gen_smtp, "~> 0.11", [hex: :gen_smtp, repo: "hexpm", optional: true]}, {:hackney, "~> 1.6", [hex: :hackney, repo: "hexpm", optional: false]}, {:mime, "~> 1.1", [hex: :mime, repo: "hexpm", optional: false]}, {:plug, "~> 1.1", [hex: :plug, repo: "hexpm", optional: true]}, {:poison, "~> 1.5 or ~> 2.0 or ~> 3.0", [hex: :poison, repo: "hexpm", optional: false]}], "hexpm"},
32 | "timex": {:hex, :timex, "3.1.24", "d198ae9783ac807721cca0c5535384ebdf99da4976be8cefb9665a9262a1e9e3", [], [{:combine, "~> 0.7", [hex: :combine, repo: "hexpm", optional: false]}, {:gettext, "~> 0.10", [hex: :gettext, repo: "hexpm", optional: false]}, {:tzdata, "~> 0.1.8 or ~> 0.5", [hex: :tzdata, repo: "hexpm", optional: false]}], "hexpm"},
33 | "timex_ecto": {:hex, :timex_ecto, "3.1.1", "37d54f6879d96a6789bb497296531cfb853631de78e152969d95cff03c1368dd", [], [{:ecto, "~> 2.1.0", [hex: :ecto, repo: "hexpm", optional: false]}, {:timex, "~> 3.0", [hex: :timex, repo: "hexpm", optional: false]}], "hexpm"},
34 | "tzdata": {:hex, :tzdata, "0.5.12", "1c17b68692c6ba5b6ab15db3d64cc8baa0f182043d5ae9d4b6d35d70af76f67b", [], [{:hackney, "~> 1.0", [hex: :hackney, repo: "hexpm", optional: false]}], "hexpm"},
35 | "unicode_util_compat": {:hex, :unicode_util_compat, "0.3.1", "a1f612a7b512638634a603c8f401892afbf99b8ce93a45041f8aaca99cadb85e", [], [], "hexpm"},
36 | "uuid": {:hex, :uuid, "1.1.7", "007afd58273bc0bc7f849c3bdc763e2f8124e83b957e515368c498b641f7ab69", [], [], "hexpm"}}
37 |
--------------------------------------------------------------------------------
/lib/coherence_demo_web/views/coherence/coherence_view_helpers.ex:
--------------------------------------------------------------------------------
1 | defmodule CoherenceDemoWeb.Coherence.ViewHelpers do
2 | @moduledoc """
3 | Helper functions for Coherence Views.
4 | """
5 | use Phoenix.HTML
6 | alias Coherence.Config
7 | import CoherenceDemoWeb.Gettext
8 |
9 | @type conn :: Plug.Conn.t
10 | @type schema :: Ecto.Schema.t
11 |
12 | @seperator {:safe, " | "}
13 | @helpers CoherenceDemoWeb.Router.Helpers
14 |
15 | @recover_link dgettext("coherence", "Forgot your password?")
16 | @unlock_link dgettext("coherence", "Send an unlock email")
17 | @register_link dgettext("coherence", "Need An Account?")
18 | @invite_link dgettext("coherence", "Invite Someone")
19 | @confirm_link dgettext("coherence", "Resend confirmation email")
20 | @signin_link dgettext("coherence", "Sign In")
21 | @signout_link dgettext("coherence", "Sign Out")
22 |
23 | @doc """
24 | Create coherence template links.
25 |
26 | Generates links if the appropriate option is installed. This function
27 | can be used to:
28 |
29 | * create links for the new session page `:new_session`
30 | * create links for your layout template `:layout`
31 |
32 |
33 | Defaults are provided based on the options configured for Coherence.
34 | However, the defaults can be overridden by passing the following options.
35 |
36 | ## Customize the links
37 |
38 | ### :new_session Options
39 |
40 | * :recover - customize the recover link (#{@recover_link})
41 | * :unlock - customize the unlock link (#{@unlock_link})
42 | * :register - customize the register link (#{@register_link})
43 | * :confirm - customize the confirm link (#{@confirm_link})
44 |
45 | ### :layout Options
46 |
47 | * :list_tag - customize the list tag (:li)
48 | * :signout_class - customize the class on the signout link ("navbar-form")
49 | * :signin - customize the signin link text (#{@signin_link})
50 | * :signout - customize the signout link text (#{@signout_link})
51 | * :register - customize the register link text (#{@register_link})
52 |
53 | ### Disable links
54 |
55 | If you set an option to false, the link will not be shown. For example, to
56 | disable the register link on the layout, use the following in your layout template:
57 |
58 | coherence_links(conn, :layout, register: false)
59 |
60 | ## Examples
61 |
62 | coherence_links(conn, :new_session)
63 | Generates: #{@recover_link} #{@unlock_link} #{@register_link} #{@confirm_link}
64 |
65 | coherence_links(conn, :new_session, recover: "Password reset", register: false
66 | Generates: Password reset #{@unlock_link}
67 |
68 | coherence_links(conn, :layout) # when logged in
69 | Generates: User's Name #{@signout_link}
70 |
71 | coherence_links(conn, :layout) # when not logged in
72 | Generates: #{@register_link} #{@signin_link}
73 | """
74 | @spec coherence_links(conn, atom, Keyword.t) :: tuple
75 | def coherence_links(conn, which, opts \\ [])
76 | def coherence_links(conn, :new_session, opts) do
77 | recover_link = Keyword.get opts, :recover, @recover_link
78 | unlock_link = Keyword.get opts, :unlock, @unlock_link
79 | register_link = Keyword.get opts, :register, @register_link
80 | confirm_link = Keyword.get opts, :confirm, @confirm_link
81 |
82 | user_schema = Coherence.Config.user_schema
83 | [
84 | recover_link(conn, user_schema, recover_link),
85 | unlock_link(conn, user_schema, unlock_link),
86 | register_link(conn, user_schema, register_link),
87 | confirmation_link(conn, user_schema, confirm_link)
88 | ]
89 | |> List.flatten
90 | |> concat([])
91 | end
92 |
93 | def coherence_links(conn, :layout, opts) do
94 | list_tag = Keyword.get opts, :list_tag, :li
95 | signout_class = Keyword.get opts, :signout_class, "navbar-form"
96 | signin = Keyword.get opts, :signin, @signin_link
97 | signout = Keyword.get opts, :signout, @signout_link
98 | register = Keyword.get opts, :register, @register_link
99 |
100 | if Coherence.logged_in?(conn) do
101 | current_user = Coherence.current_user(conn)
102 | [
103 | content_tag(list_tag, profile_link(current_user, conn)),
104 | content_tag(list_tag, signout_link(conn, signout, signout_class))
105 | ]
106 | else
107 | signin_link = content_tag(list_tag, link(signin, to: coherence_path(@helpers, :session_path, conn, :new)))
108 | if Config.has_option(:registerable) && register do
109 | [content_tag(list_tag, link(register, to: coherence_path(@helpers, :registration_path, conn, :new))), signin_link]
110 | else
111 | signin_link
112 | end
113 | end
114 | end
115 |
116 | @doc """
117 | Helper to avoid compile warnings when options are disabled.
118 | """
119 | @spec coherence_path(module, atom, conn, atom) :: String.t
120 | def coherence_path(module, route_name, conn, action) do
121 | apply(module, route_name, [conn, action])
122 | end
123 | def coherence_path(module, route_name, conn, action, opts) do
124 | apply(module, route_name, [conn, action, opts])
125 | end
126 |
127 | defp concat([], acc), do: Enum.reverse(acc)
128 | defp concat([h|t], []), do: concat(t, [h])
129 | defp concat([h|t], acc), do: concat(t, [h, @seperator | acc])
130 |
131 | @spec recover_link(conn, module, false | String.t) :: [any] | []
132 | def recover_link(_conn, _user_schema, false), do: []
133 | def recover_link(conn, user_schema, text) do
134 | if user_schema.recoverable?, do: [recover_link(conn, text)], else: []
135 | end
136 |
137 | @spec recover_link(conn, String.t) :: tuple
138 | def recover_link(conn, text \\ @recover_link), do:
139 | link(text, to: coherence_path(@helpers, :password_path, conn, :new))
140 |
141 | @spec register_link(conn, module, false | String.t) :: [any] | []
142 | def register_link(_conn, _user_schema, false), do: []
143 | def register_link(conn, user_schema, text) do
144 | if user_schema.registerable?, do: [register_link(conn, text)], else: []
145 | end
146 |
147 | @spec register_link(conn, String.t) :: tuple
148 | def register_link(conn, text \\ @register_link), do:
149 | link(text, to: coherence_path(@helpers, :registration_path, conn, :new))
150 |
151 | @spec unlock_link(conn, module, false | String.t) :: [any] | []
152 | def unlock_link(_conn, _user_schema, false), do: []
153 | def unlock_link(conn, _user_schema, text) do
154 | if conn.assigns[:locked], do: [unlock_link(conn, text)], else: []
155 | end
156 |
157 | @spec unlock_link(conn, String.t) :: tuple
158 | def unlock_link(conn, text \\ @unlock_link), do:
159 | link(text, to: coherence_path(@helpers, :unlock_path, conn, :new))
160 |
161 | @spec invitation_link(conn, String.t) :: tuple
162 | def invitation_link(conn, text \\ @invite_link) do
163 | link text, to: coherence_path(@helpers, :invitation_path, conn, :new)
164 | end
165 |
166 | @spec signout_link(conn, String.t, String.t) :: tuple
167 | def signout_link(conn, text \\ @signout_link, signout_class \\ "") do
168 | link(text, to: coherence_path(@helpers, :session_path, conn, :delete), method: :delete, class: signout_class)
169 | end
170 |
171 | @spec confirmation_link(conn, module, false | String.t) :: [any] | []
172 | def confirmation_link(_conn, _user_schema, false), do: []
173 | def confirmation_link(conn, user_schema, text) do
174 | if user_schema.confirmable?, do: [confirmation_link(conn, text)], else: []
175 | end
176 |
177 | @spec confirmation_link(conn, String.t) :: tuple
178 | def confirmation_link(conn, text \\ @confirm_link) do
179 | link(text, to: coherence_path(@helpers, :confirmation_path, conn, :new))
180 | end
181 |
182 | @spec required_label(atom, String.t | atom, Keyword.t) :: tuple
183 | def required_label(f, name, opts \\ []) do
184 | label f, name, opts do
185 | [
186 | "#{humanize(name)}\n",
187 | content_tag(:abbr, "*", class: "required", title: "required")
188 | ]
189 | end
190 | end
191 |
192 | @spec current_user(conn) :: schema
193 | def current_user(conn) do
194 | Coherence.current_user(conn)
195 | end
196 |
197 | @spec logged_in?(conn) :: boolean
198 | def logged_in?(conn) do
199 | Coherence.logged_in?(conn)
200 | end
201 |
202 |
203 | defp profile_link(current_user, conn) do
204 | if Config.user_schema.registerable? do
205 | link current_user.name, to: coherence_path(@helpers, :registration_path, conn, :show)
206 | else
207 | current_user.name
208 | end
209 | end
210 | end
211 |
--------------------------------------------------------------------------------