diff --git a/.formatter.exs b/.formatter.exs index 8a6391c..ef8840c 100644 --- a/.formatter.exs +++ b/.formatter.exs @@ -1,5 +1,6 @@ [ - import_deps: [:ecto, :phoenix], - inputs: ["*.{ex,exs}", "priv/*/seeds.exs", "{config,lib,test}/**/*.{ex,exs}"], - subdirectories: ["priv/*/migrations"] + import_deps: [:ecto, :ecto_sql, :phoenix], + subdirectories: ["priv/*/migrations"], + plugins: [Phoenix.LiveView.HTMLFormatter], + inputs: ["*.{heex,ex,exs}", "{config,lib,test}/**/*.{heex,ex,exs}", "priv/*/seeds.exs"] ] diff --git a/.gitignore b/.gitignore index 9575f30..fab46fd 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,9 @@ erl_crash.dump # Also ignore archive artifacts (built via "mix archive.build"). *.ez +# Temporary files, for example, from tests. +/tmp/ + # Ignore package tarball (built via "mix hex.build"). link_shortener-*.tar diff --git a/assets/css/app.css b/assets/css/app.css index 19c2e51..378c8f9 100644 --- a/assets/css/app.css +++ b/assets/css/app.css @@ -1,120 +1,5 @@ -/* This file is for your main application CSS */ -@import "./phoenix.css"; - -/* Alerts and form errors used by phx.new */ -.alert { - padding: 15px; - margin-bottom: 20px; - border: 1px solid transparent; - border-radius: 4px; -} -.alert-info { - color: #31708f; - background-color: #d9edf7; - border-color: #bce8f1; -} -.alert-warning { - color: #8a6d3b; - background-color: #fcf8e3; - border-color: #faebcc; -} -.alert-danger { - color: #a94442; - background-color: #f2dede; - border-color: #ebccd1; -} -.alert p { - margin-bottom: 0; -} -.alert:empty { - display: none; -} -.invalid-feedback { - color: #a94442; - display: block; - margin: -1rem 0 2rem; -} - -/* LiveView specific classes for your customization */ -.phx-no-feedback.invalid-feedback, -.phx-no-feedback .invalid-feedback { - display: none; -} - -.phx-click-loading { - opacity: 0.5; - transition: opacity 1s ease-out; -} - -.phx-loading{ - cursor: wait; -} - -.phx-modal { - opacity: 1!important; - position: fixed; - z-index: 1; - left: 0; - top: 0; - width: 100%; - height: 100%; - overflow: auto; - background-color: rgba(0,0,0,0.4); -} - -.phx-modal-content { - background-color: #fefefe; - margin: 15vh auto; - padding: 20px; - border: 1px solid #888; - width: 80%; -} - -.phx-modal-close { - color: #aaa; - float: right; - font-size: 28px; - font-weight: bold; -} +@import "tailwindcss/base"; +@import "tailwindcss/components"; +@import "tailwindcss/utilities"; -.phx-modal-close:hover, -.phx-modal-close:focus { - color: black; - text-decoration: none; - cursor: pointer; -} - -.fade-in-scale { - animation: 0.2s ease-in 0s normal forwards 1 fade-in-scale-keys; -} - -.fade-out-scale { - animation: 0.2s ease-out 0s normal forwards 1 fade-out-scale-keys; -} - -.fade-in { - animation: 0.2s ease-out 0s normal forwards 1 fade-in-keys; -} -.fade-out { - animation: 0.2s ease-out 0s normal forwards 1 fade-out-keys; -} - -@keyframes fade-in-scale-keys{ - 0% { scale: 0.95; opacity: 0; } - 100% { scale: 1.0; opacity: 1; } -} - -@keyframes fade-out-scale-keys{ - 0% { scale: 1.0; opacity: 1; } - 100% { scale: 0.95; opacity: 0; } -} - -@keyframes fade-in-keys{ - 0% { opacity: 0; } - 100% { opacity: 1; } -} - -@keyframes fade-out-keys{ - 0% { opacity: 1; } - 100% { opacity: 0; } -} +/* This file is for your main application CSS */ diff --git a/assets/css/phoenix.css b/assets/css/phoenix.css deleted file mode 100644 index 0d59050..0000000 --- a/assets/css/phoenix.css +++ /dev/null @@ -1,101 +0,0 @@ -/* Includes some default style for the starter application. - * This can be safely deleted to start fresh. - */ - -/* Milligram v1.4.1 https://milligram.github.io - * Copyright (c) 2020 CJ Patoilo Licensed under the MIT license - */ - -*,*:after,*:before{box-sizing:inherit}html{box-sizing:border-box;font-size:62.5%}body{color:#000000;font-family:'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;font-size:1.6em;font-weight:300;letter-spacing:.01em;line-height:1.6}blockquote{border-left:0.3rem solid #d1d1d1;margin-left:0;margin-right:0;padding:1rem 1.5rem}blockquote *:last-child{margin-bottom:0}.button,button,input[type='button'],input[type='reset'],input[type='submit']{background-color:#0069d9;border:0.1rem solid #0069d9;border-radius:.4rem;color:#fff;cursor:pointer;display:inline-block;font-size:1.1rem;font-weight:700;height:3.8rem;letter-spacing:.1rem;line-height:3.8rem;padding:0 3.0rem;text-align:center;text-decoration:none;text-transform:uppercase;white-space:nowrap}.button:focus,.button:hover,button:focus,button:hover,input[type='button']:focus,input[type='button']:hover,input[type='reset']:focus,input[type='reset']:hover,input[type='submit']:focus,input[type='submit']:hover{background-color:#606c76;border-color:#606c76;color:#fff;outline:0}.button[disabled],button[disabled],input[type='button'][disabled],input[type='reset'][disabled],input[type='submit'][disabled]{cursor:default;opacity:.5}.button[disabled]:focus,.button[disabled]:hover,button[disabled]:focus,button[disabled]:hover,input[type='button'][disabled]:focus,input[type='button'][disabled]:hover,input[type='reset'][disabled]:focus,input[type='reset'][disabled]:hover,input[type='submit'][disabled]:focus,input[type='submit'][disabled]:hover{background-color:#0069d9;border-color:#0069d9}.button.button-outline,button.button-outline,input[type='button'].button-outline,input[type='reset'].button-outline,input[type='submit'].button-outline{background-color:transparent;color:#0069d9}.button.button-outline:focus,.button.button-outline:hover,button.button-outline:focus,button.button-outline:hover,input[type='button'].button-outline:focus,input[type='button'].button-outline:hover,input[type='reset'].button-outline:focus,input[type='reset'].button-outline:hover,input[type='submit'].button-outline:focus,input[type='submit'].button-outline:hover{background-color:transparent;border-color:#606c76;color:#606c76}.button.button-outline[disabled]:focus,.button.button-outline[disabled]:hover,button.button-outline[disabled]:focus,button.button-outline[disabled]:hover,input[type='button'].button-outline[disabled]:focus,input[type='button'].button-outline[disabled]:hover,input[type='reset'].button-outline[disabled]:focus,input[type='reset'].button-outline[disabled]:hover,input[type='submit'].button-outline[disabled]:focus,input[type='submit'].button-outline[disabled]:hover{border-color:inherit;color:#0069d9}.button.button-clear,button.button-clear,input[type='button'].button-clear,input[type='reset'].button-clear,input[type='submit'].button-clear{background-color:transparent;border-color:transparent;color:#0069d9}.button.button-clear:focus,.button.button-clear:hover,button.button-clear:focus,button.button-clear:hover,input[type='button'].button-clear:focus,input[type='button'].button-clear:hover,input[type='reset'].button-clear:focus,input[type='reset'].button-clear:hover,input[type='submit'].button-clear:focus,input[type='submit'].button-clear:hover{background-color:transparent;border-color:transparent;color:#606c76}.button.button-clear[disabled]:focus,.button.button-clear[disabled]:hover,button.button-clear[disabled]:focus,button.button-clear[disabled]:hover,input[type='button'].button-clear[disabled]:focus,input[type='button'].button-clear[disabled]:hover,input[type='reset'].button-clear[disabled]:focus,input[type='reset'].button-clear[disabled]:hover,input[type='submit'].button-clear[disabled]:focus,input[type='submit'].button-clear[disabled]:hover{color:#0069d9}code{background:#f4f5f6;border-radius:.4rem;font-size:86%;margin:0 .2rem;padding:.2rem .5rem;white-space:nowrap}pre{background:#f4f5f6;border-left:0.3rem solid #0069d9;overflow-y:hidden}pre>code{border-radius:0;display:block;padding:1rem 1.5rem;white-space:pre}hr{border:0;border-top:0.1rem solid #f4f5f6;margin:3.0rem 0}input[type='color'],input[type='date'],input[type='datetime'],input[type='datetime-local'],input[type='email'],input[type='month'],input[type='number'],input[type='password'],input[type='search'],input[type='tel'],input[type='text'],input[type='url'],input[type='week'],input:not([type]),textarea,select{-webkit-appearance:none;background-color:transparent;border:0.1rem solid #d1d1d1;border-radius:.4rem;box-shadow:none;box-sizing:inherit;height:3.8rem;padding:.6rem 1.0rem .7rem;width:100%}input[type='color']:focus,input[type='date']:focus,input[type='datetime']:focus,input[type='datetime-local']:focus,input[type='email']:focus,input[type='month']:focus,input[type='number']:focus,input[type='password']:focus,input[type='search']:focus,input[type='tel']:focus,input[type='text']:focus,input[type='url']:focus,input[type='week']:focus,input:not([type]):focus,textarea:focus,select:focus{border-color:#0069d9;outline:0}select{background:url('data:image/svg+xml;utf8,') center right no-repeat;padding-right:3.0rem}select:focus{background-image:url('data:image/svg+xml;utf8,')}select[multiple]{background:none;height:auto}textarea{min-height:6.5rem}label,legend{display:block;font-size:1.6rem;font-weight:700;margin-bottom:.5rem}fieldset{border-width:0;padding:0}input[type='checkbox'],input[type='radio']{display:inline}.label-inline{display:inline-block;font-weight:normal;margin-left:.5rem}.container{margin:0 auto;max-width:112.0rem;padding:0 2.0rem;position:relative;width:100%}.row{display:flex;flex-direction:column;padding:0;width:100%}.row.row-no-padding{padding:0}.row.row-no-padding>.column{padding:0}.row.row-wrap{flex-wrap:wrap}.row.row-top{align-items:flex-start}.row.row-bottom{align-items:flex-end}.row.row-center{align-items:center}.row.row-stretch{align-items:stretch}.row.row-baseline{align-items:baseline}.row .column{display:block;flex:1 1 auto;margin-left:0;max-width:100%;width:100%}.row .column.column-offset-10{margin-left:10%}.row .column.column-offset-20{margin-left:20%}.row .column.column-offset-25{margin-left:25%}.row .column.column-offset-33,.row .column.column-offset-34{margin-left:33.3333%}.row .column.column-offset-40{margin-left:40%}.row .column.column-offset-50{margin-left:50%}.row .column.column-offset-60{margin-left:60%}.row .column.column-offset-66,.row .column.column-offset-67{margin-left:66.6666%}.row .column.column-offset-75{margin-left:75%}.row .column.column-offset-80{margin-left:80%}.row .column.column-offset-90{margin-left:90%}.row .column.column-10{flex:0 0 10%;max-width:10%}.row .column.column-20{flex:0 0 20%;max-width:20%}.row .column.column-25{flex:0 0 25%;max-width:25%}.row .column.column-33,.row .column.column-34{flex:0 0 33.3333%;max-width:33.3333%}.row .column.column-40{flex:0 0 40%;max-width:40%}.row .column.column-50{flex:0 0 50%;max-width:50%}.row .column.column-60{flex:0 0 60%;max-width:60%}.row .column.column-66,.row .column.column-67{flex:0 0 66.6666%;max-width:66.6666%}.row .column.column-75{flex:0 0 75%;max-width:75%}.row .column.column-80{flex:0 0 80%;max-width:80%}.row .column.column-90{flex:0 0 90%;max-width:90%}.row .column .column-top{align-self:flex-start}.row .column .column-bottom{align-self:flex-end}.row .column .column-center{align-self:center}@media (min-width: 40rem){.row{flex-direction:row;margin-left:-1.0rem;width:calc(100% + 2.0rem)}.row .column{margin-bottom:inherit;padding:0 1.0rem}}a{color:#0069d9;text-decoration:none}a:focus,a:hover{color:#606c76}dl,ol,ul{list-style:none;margin-top:0;padding-left:0}dl dl,dl ol,dl ul,ol dl,ol ol,ol ul,ul dl,ul ol,ul ul{font-size:90%;margin:1.5rem 0 1.5rem 3.0rem}ol{list-style:decimal inside}ul{list-style:circle inside}.button,button,dd,dt,li{margin-bottom:1.0rem}fieldset,input,select,textarea{margin-bottom:1.5rem}blockquote,dl,figure,form,ol,p,pre,table,ul{margin-bottom:2.5rem}table{border-spacing:0;display:block;overflow-x:auto;text-align:left;width:100%}td,th{border-bottom:0.1rem solid #e1e1e1;padding:1.2rem 1.5rem}td:first-child,th:first-child{padding-left:0}td:last-child,th:last-child{padding-right:0}@media (min-width: 40rem){table{display:table;overflow-x:initial}}b,strong{font-weight:bold}p{margin-top:0}h1,h2,h3,h4,h5,h6{font-weight:300;letter-spacing:-.1rem;margin-bottom:2.0rem;margin-top:0}h1{font-size:4.6rem;line-height:1.2}h2{font-size:3.6rem;line-height:1.25}h3{font-size:2.8rem;line-height:1.3}h4{font-size:2.2rem;letter-spacing:-.08rem;line-height:1.35}h5{font-size:1.8rem;letter-spacing:-.05rem;line-height:1.5}h6{font-size:1.6rem;letter-spacing:0;line-height:1.4}img{max-width:100%}.clearfix:after{clear:both;content:' ';display:table}.float-left{float:left}.float-right{float:right} - -/* General style */ -h1{font-size: 3.6rem; line-height: 1.25} -h2{font-size: 2.8rem; line-height: 1.3} -h3{font-size: 2.2rem; letter-spacing: -.08rem; line-height: 1.35} -h4{font-size: 1.8rem; letter-spacing: -.05rem; line-height: 1.5} -h5{font-size: 1.6rem; letter-spacing: 0; line-height: 1.4} -h6{font-size: 1.4rem; letter-spacing: 0; line-height: 1.2} -pre{padding: 1em;} - -.container{ - margin: 0 auto; - max-width: 80.0rem; - padding: 0 2.0rem; - position: relative; - width: 100% -} -select { - width: auto; -} - -/* Phoenix promo and logo */ -.phx-hero { - text-align: center; - border-bottom: 1px solid #e3e3e3; - background: #eee; - border-radius: 6px; - padding: 3em 3em 1em; - margin-bottom: 3rem; - font-weight: 200; - font-size: 120%; -} -.phx-hero input { - background: #ffffff; -} -.phx-logo { - min-width: 300px; - margin: 1rem; - display: block; -} -.phx-logo img { - width: auto; - display: block; -} - -/* Headers */ -header { - width: 100%; - background: #fdfdfd; - border-bottom: 1px solid #eaeaea; - margin-bottom: 2rem; -} -header section { - align-items: center; - display: flex; - flex-direction: column; - justify-content: space-between; -} -header section :first-child { - order: 2; -} -header section :last-child { - order: 1; -} -header nav ul, -header nav li { - margin: 0; - padding: 0; - display: block; - text-align: right; - white-space: nowrap; -} -header nav ul { - margin: 1rem; - margin-top: 0; -} -header nav a { - display: block; -} - -@media (min-width: 40.0rem) { /* Small devices (landscape phones, 576px and up) */ - header section { - flex-direction: row; - } - header nav ul { - margin: 1rem; - } - .phx-logo { - flex-basis: 527px; - margin: 2rem 1rem; - } -} diff --git a/assets/js/app.js b/assets/js/app.js index 2ca06a5..d5e278a 100644 --- a/assets/js/app.js +++ b/assets/js/app.js @@ -1,7 +1,3 @@ -// We import the CSS which is extracted to its own file by esbuild. -// Remove this line if you add a your own CSS build pipeline (e.g postcss). -import "../css/app.css" - // If you want to use Phoenix channels, run `mix help phx.gen.channel` // to get started and then uncomment the line below. // import "./user_socket.js" @@ -27,12 +23,15 @@ import {LiveSocket} from "phoenix_live_view" import topbar from "../vendor/topbar" let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content") -let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}}) +let liveSocket = new LiveSocket("/live", Socket, { + longPollFallbackMs: 2500, + params: {_csrf_token: csrfToken} +}) // Show progress bar on live navigation and form submits topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"}) -window.addEventListener("phx:page-loading-start", info => topbar.show()) -window.addEventListener("phx:page-loading-stop", info => topbar.hide()) +window.addEventListener("phx:page-loading-start", _info => topbar.show(300)) +window.addEventListener("phx:page-loading-stop", _info => topbar.hide()) // connect if there are any LiveViews on the page liveSocket.connect() diff --git a/assets/tailwind.config.js b/assets/tailwind.config.js new file mode 100644 index 0000000..78011a6 --- /dev/null +++ b/assets/tailwind.config.js @@ -0,0 +1,74 @@ +// See the Tailwind configuration guide for advanced usage +// https://tailwindcss.com/docs/configuration + +const plugin = require("tailwindcss/plugin") +const fs = require("fs") +const path = require("path") + +module.exports = { + content: [ + "./js/**/*.js", + "../lib/link_shortener_web.ex", + "../lib/link_shortener_web/**/*.*ex" + ], + theme: { + extend: { + colors: { + brand: "#FD4F00", + } + }, + }, + plugins: [ + require("@tailwindcss/forms"), + // Allows prefixing tailwind classes with LiveView classes to add rules + // only when LiveView classes are applied, for example: + // + //
+ // + plugin(({addVariant}) => addVariant("phx-click-loading", [".phx-click-loading&", ".phx-click-loading &"])), + plugin(({addVariant}) => addVariant("phx-submit-loading", [".phx-submit-loading&", ".phx-submit-loading &"])), + plugin(({addVariant}) => addVariant("phx-change-loading", [".phx-change-loading&", ".phx-change-loading &"])), + + // Embeds Heroicons (https://heroicons.com) into your app.css bundle + // See your `CoreComponents.icon/1` for more information. + // + plugin(function({matchComponents, theme}) { + let iconsDir = path.join(__dirname, "../deps/heroicons/optimized") + let values = {} + let icons = [ + ["", "/24/outline"], + ["-solid", "/24/solid"], + ["-mini", "/20/solid"], + ["-micro", "/16/solid"] + ] + icons.forEach(([suffix, dir]) => { + fs.readdirSync(path.join(iconsDir, dir)).forEach(file => { + let name = path.basename(file, ".svg") + suffix + values[name] = {name, fullPath: path.join(iconsDir, dir, file)} + }) + }) + matchComponents({ + "hero": ({name, fullPath}) => { + let content = fs.readFileSync(fullPath).toString().replace(/\r?\n|\r/g, "") + let size = theme("spacing.6") + if (name.endsWith("-mini")) { + size = theme("spacing.5") + } else if (name.endsWith("-micro")) { + size = theme("spacing.4") + } + return { + [`--hero-${name}`]: `url('data:image/svg+xml;utf8,${content}')`, + "-webkit-mask": `var(--hero-${name})`, + "mask": `var(--hero-${name})`, + "mask-repeat": "no-repeat", + "background-color": "currentColor", + "vertical-align": "middle", + "display": "inline-block", + "width": size, + "height": size + } + } + }, {values}) + }) + ] +} diff --git a/assets/vendor/topbar.js b/assets/vendor/topbar.js index 1f62209..4195727 100644 --- a/assets/vendor/topbar.js +++ b/assets/vendor/topbar.js @@ -1,6 +1,6 @@ /** * @license MIT - * topbar 1.0.0, 2021-01-06 + * topbar 2.0.0, 2023-02-04 * https://buunguyen.github.io/topbar * Copyright (c) 2021 Buu Nguyen */ @@ -35,10 +35,11 @@ })(); var canvas, - progressTimerId, - fadeTimerId, currentProgress, showing, + progressTimerId = null, + fadeTimerId = null, + delayTimerId = null, addEvent = function (elem, type, handler) { if (elem.addEventListener) elem.addEventListener(type, handler, false); else if (elem.attachEvent) elem.attachEvent("on" + type, handler); @@ -95,21 +96,26 @@ for (var key in opts) if (options.hasOwnProperty(key)) options[key] = opts[key]; }, - show: function () { + show: function (delay) { if (showing) return; - showing = true; - if (fadeTimerId !== null) window.cancelAnimationFrame(fadeTimerId); - if (!canvas) createCanvas(); - canvas.style.opacity = 1; - canvas.style.display = "block"; - topbar.progress(0); - if (options.autoRun) { - (function loop() { - progressTimerId = window.requestAnimationFrame(loop); - topbar.progress( - "+" + 0.05 * Math.pow(1 - Math.sqrt(currentProgress), 2) - ); - })(); + if (delay) { + if (delayTimerId) return; + delayTimerId = setTimeout(() => topbar.show(), delay); + } else { + showing = true; + if (fadeTimerId !== null) window.cancelAnimationFrame(fadeTimerId); + if (!canvas) createCanvas(); + canvas.style.opacity = 1; + canvas.style.display = "block"; + topbar.progress(0); + if (options.autoRun) { + (function loop() { + progressTimerId = window.requestAnimationFrame(loop); + topbar.progress( + "+" + 0.05 * Math.pow(1 - Math.sqrt(currentProgress), 2) + ); + })(); + } } }, progress: function (to) { @@ -125,6 +131,8 @@ return currentProgress; }, hide: function () { + clearTimeout(delayTimerId); + delayTimerId = null; if (!showing) return; showing = false; if (progressTimerId != null) { diff --git a/config/config.exs b/config/config.exs index cb4bbb8..8c29002 100644 --- a/config/config.exs +++ b/config/config.exs @@ -8,14 +8,19 @@ import Config config :link_shortener, - ecto_repos: [LinkShortener.Repo] + ecto_repos: [LinkShortener.Repo], + generators: [timestamp_type: :utc_datetime] # Configures the endpoint config :link_shortener, LinkShortenerWeb.Endpoint, url: [host: "localhost"], - render_errors: [view: LinkShortenerWeb.ErrorView, accepts: ~w(html json), layout: false], + adapter: Bandit.PhoenixAdapter, + render_errors: [ + formats: [html: LinkShortenerWeb.ErrorHTML, json: LinkShortenerWeb.ErrorJSON], + layout: false + ], pubsub_server: LinkShortener.PubSub, - live_view: [signing_salt: "8wxfzzEQ"] + live_view: [signing_salt: "+S5BXaoX"] # Configures the mailer # @@ -26,19 +31,28 @@ config :link_shortener, LinkShortenerWeb.Endpoint, # at the `config/runtime.exs`. config :link_shortener, LinkShortener.Mailer, adapter: Swoosh.Adapters.Local -# Swoosh API client is needed for adapters other than SMTP. -config :swoosh, :api_client, false - # Configure esbuild (the version is required) config :esbuild, - version: "0.14.29", - default: [ + version: "0.17.11", + link_shortener: [ args: ~w(js/app.js --bundle --target=es2017 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*), cd: Path.expand("../assets", __DIR__), env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)} ] +# Configure tailwind (the version is required) +config :tailwind, + version: "3.4.3", + link_shortener: [ + args: ~w( + --config=tailwind.config.js + --input=css/app.css + --output=../priv/static/assets/app.css + ), + cd: Path.expand("../assets", __DIR__) + ] + # Configures Elixir's Logger config :logger, :console, format: "$time $metadata[$level] $message\n", @@ -47,10 +61,6 @@ config :logger, :console, # Use Jason for JSON parsing in Phoenix config :phoenix, :json_library, Jason -config :link_shortener, LinkShortenerWeb.Auth.Guardian, - issuer: "link_shortener", - secret_key: System.get_env("SECRET_KEY_BASE") - # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. import_config "#{config_env()}.exs" diff --git a/config/dev.exs b/config/dev.exs index 1ef51ea..eca34ca 100644 --- a/config/dev.exs +++ b/config/dev.exs @@ -2,10 +2,10 @@ import Config # Configure your database config :link_shortener, LinkShortener.Repo, - database: System.get_env("DATABASE_NAME"), username: System.get_env("DATABASE_USERNAME"), password: System.get_env("DATABASE_PASSWORD"), hostname: System.get_env("DATABASE_HOST"), + database: System.get_env("DATABASE_NAME"), port: System.get_env("DATABASE_PORT"), stacktrace: true, show_sensitive_data_on_connection_error: true, @@ -15,8 +15,8 @@ config :link_shortener, LinkShortener.Repo, # debugging and code reloading. # # The watchers configuration can be used to run external -# watchers to your application. For example, we use it -# with esbuild to bundle .js and .css sources. +# watchers to your application. For example, we can use it +# to bundle .js and .css sources. config :link_shortener, LinkShortenerWeb.Endpoint, # Binding to loopback ipv4 address prevents access from other machines. # Change to `ip: {0, 0, 0, 0}` to allow access from other machines. @@ -26,8 +26,8 @@ config :link_shortener, LinkShortenerWeb.Endpoint, debug_errors: true, secret_key_base: System.get_env("SECRET_KEY_BASE"), watchers: [ - # Start the esbuild watcher by calling Esbuild.install_and_run(:default, args) - esbuild: {Esbuild, :install_and_run, [:default, ~w(--sourcemap=inline --watch)]} + esbuild: {Esbuild, :install_and_run, [:link_shortener, ~w(--sourcemap=inline --watch)]}, + tailwind: {Tailwind, :install_and_run, [:link_shortener, ~w(--watch)]} ] # ## SSL Support @@ -38,7 +38,6 @@ config :link_shortener, LinkShortenerWeb.Endpoint, # # mix phx.gen.cert # -# Note that this task requires Erlang/OTP 20 or later. # Run `mix help phx.gen.cert` for more information. # # The `http:` config above can be replaced with: @@ -58,13 +57,15 @@ config :link_shortener, LinkShortenerWeb.Endpoint, config :link_shortener, LinkShortenerWeb.Endpoint, live_reload: [ patterns: [ - ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$", + ~r"priv/static/(?!uploads/).*(js|css|png|jpeg|jpg|gif|svg)$", ~r"priv/gettext/.*(po)$", - ~r"lib/link_shortener_web/(live|views)/.*(ex)$", - ~r"lib/link_shortener_web/templates/.*(eex)$" + ~r"lib/link_shortener_web/(controllers|live|components)/.*(ex|heex)$" ] ] +# Enable dev routes for dashboard and mailbox +config :link_shortener, dev_routes: true + # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" @@ -74,3 +75,12 @@ config :phoenix, :stacktrace_depth, 20 # Initialize plugs at runtime for faster development compilation config :phoenix, :plug_init_mode, :runtime + +config :phoenix_live_view, + # Include HEEx debug annotations as HTML comments in rendered markup + debug_heex_annotations: true, + # Enable helpful, but potentially expensive runtime checks + enable_expensive_runtime_checks: true + +# Disable swoosh api client as it is only required for production adapters. +config :swoosh, :api_client, false diff --git a/config/runtime.exs b/config/runtime.exs index 51b6f0b..e16096e 100644 --- a/config/runtime.exs +++ b/config/runtime.exs @@ -28,7 +28,7 @@ if config_env() == :prod do For example: ecto://USER:PASS@HOST/DATABASE """ - maybe_ipv6 = if System.get_env("ECTO_IPV6"), do: [:inet6], else: [] + maybe_ipv6 = if System.get_env("ECTO_IPV6") in ~w(true 1), do: [:inet6], else: [] config :link_shortener, LinkShortener.Repo, # ssl: true, @@ -51,18 +51,52 @@ if config_env() == :prod do host = System.get_env("PHX_HOST") || "example.com" port = String.to_integer(System.get_env("PORT") || "4000") + config :link_shortener, :dns_cluster_query, System.get_env("DNS_CLUSTER_QUERY") + config :link_shortener, LinkShortenerWeb.Endpoint, url: [host: host, port: 443, scheme: "https"], http: [ # Enable IPv6 and bind on all interfaces. # Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access. - # See the documentation on https://hexdocs.pm/plug_cowboy/Plug.Cowboy.html + # See the documentation on https://hexdocs.pm/bandit/Bandit.html#t:options/0 # for details about using IPv6 vs IPv4 and loopback vs public addresses. ip: {0, 0, 0, 0, 0, 0, 0, 0}, port: port ], secret_key_base: secret_key_base + # ## SSL Support + # + # To get SSL working, you will need to add the `https` key + # to your endpoint configuration: + # + # config :link_shortener, LinkShortenerWeb.Endpoint, + # https: [ + # ..., + # port: 443, + # cipher_suite: :strong, + # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), + # certfile: System.get_env("SOME_APP_SSL_CERT_PATH") + # ] + # + # The `cipher_suite` is set to `:strong` to support only the + # latest and more secure SSL ciphers. This means old browsers + # and clients may not be supported. You can set it to + # `:compatible` for wider support. + # + # `:keyfile` and `:certfile` expect an absolute path to the key + # and cert in disk or a relative path inside priv, for example + # "priv/ssl/server.key". For all supported SSL configuration + # options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 + # + # We also recommend setting `force_ssl` in your config/prod.exs, + # ensuring no data is ever sent via http, always redirecting to https: + # + # config :link_shortener, LinkShortenerWeb.Endpoint, + # force_ssl: [hsts: true] + # + # Check `Plug.SSL` for all available options in `force_ssl`. + # ## Configuring the mailer # # In production you need to configure the mailer to use a different adapter. diff --git a/config/test.exs b/config/test.exs index fb26508..383270d 100644 --- a/config/test.exs +++ b/config/test.exs @@ -1,8 +1,5 @@ import Config -# Only in tests, remove the complexity from the password hashing algorithm -config :bcrypt_elixir, :log_rounds, 1 - # Configure your database # # The MIX_TEST_PARTITION environment variable can be used @@ -14,7 +11,7 @@ config :link_shortener, LinkShortener.Repo, hostname: System.get_env("DATABASE_HOST"), database: "link_shortener_test#{System.get_env("MIX_TEST_PARTITION")}", pool: Ecto.Adapters.SQL.Sandbox, - pool_size: 10 + pool_size: System.schedulers_online() * 2 # We don't run a server during test. If one is required, # you can enable the server option below. @@ -23,11 +20,18 @@ config :link_shortener, LinkShortenerWeb.Endpoint, secret_key_base: System.get_env("SECRET_KEY_BASE"), server: false -# In test we don't send emails. +# In test we don't send emails config :link_shortener, LinkShortener.Mailer, adapter: Swoosh.Adapters.Test +# Disable swoosh api client as it is only required for production adapters +config :swoosh, :api_client, false + # Print only warnings and errors during test -config :logger, level: :warn +config :logger, level: :warning # Initialize plugs at runtime for faster test compilation config :phoenix, :plug_init_mode, :runtime + +# Enable helpful, but potentially expensive runtime checks +config :phoenix_live_view, + enable_expensive_runtime_checks: true diff --git a/lib/link_shortener/accounts/accounts.ex b/lib/link_shortener/accounts/accounts.ex deleted file mode 100644 index bdd1b86..0000000 --- a/lib/link_shortener/accounts/accounts.ex +++ /dev/null @@ -1,353 +0,0 @@ -defmodule LinkShortener.Accounts do - @moduledoc """ - The Accounts context. - """ - - import Ecto.Query, warn: false - alias LinkShortener.Repo - - alias LinkShortener.Accounts.{User, UserToken, UserNotifier} - - ## Database getters - - @doc """ - Gets a user by email. - - ## Examples - - iex> get_user_by_email("foo@example.com") - %User{} - - iex> get_user_by_email("unknown@example.com") - nil - - """ - def get_user_by_email(email) when is_binary(email) do - Repo.get_by(User, email: email) - end - - @doc """ - Gets a user by email and password. - - ## Examples - - iex> get_user_by_email_and_password("foo@example.com", "correct_password") - %User{} - - iex> get_user_by_email_and_password("foo@example.com", "invalid_password") - nil - - """ - def get_user_by_email_and_password(email, password) - when is_binary(email) and is_binary(password) do - user = Repo.get_by(User, email: email) - if User.valid_password?(user, password), do: user - end - - @doc """ - Gets a single user. - - Raises `Ecto.NoResultsError` if the User does not exist. - - ## Examples - - iex> get_user!(123) - %User{} - - iex> get_user!(456) - ** (Ecto.NoResultsError) - - """ - def get_user!(id), do: Repo.get!(User, id) - - ## User registration - - @doc """ - Registers a user. - - ## Examples - - iex> register_user(%{field: value}) - {:ok, %User{}} - - iex> register_user(%{field: bad_value}) - {:error, %Ecto.Changeset{}} - - """ - def register_user(attrs) do - %User{} - |> User.registration_changeset(attrs) - |> Repo.insert() - end - - @doc """ - Returns an `%Ecto.Changeset{}` for tracking user changes. - - ## Examples - - iex> change_user_registration(user) - %Ecto.Changeset{data: %User{}} - - """ - def change_user_registration(%User{} = user, attrs \\ %{}) do - User.registration_changeset(user, attrs, hash_password: false) - end - - ## Settings - - @doc """ - Returns an `%Ecto.Changeset{}` for changing the user email. - - ## Examples - - iex> change_user_email(user) - %Ecto.Changeset{data: %User{}} - - """ - def change_user_email(user, attrs \\ %{}) do - User.email_changeset(user, attrs) - end - - @doc """ - Emulates that the email will change without actually changing - it in the database. - - ## Examples - - iex> apply_user_email(user, "valid password", %{email: ...}) - {:ok, %User{}} - - iex> apply_user_email(user, "invalid password", %{email: ...}) - {:error, %Ecto.Changeset{}} - - """ - def apply_user_email(user, password, attrs) do - user - |> User.email_changeset(attrs) - |> User.validate_current_password(password) - |> Ecto.Changeset.apply_action(:update) - end - - @doc """ - Updates the user email using the given token. - - If the token matches, the user email is updated and the token is deleted. - The confirmed_at date is also updated to the current time. - """ - def update_user_email(user, token) do - context = "change:#{user.email}" - - with {:ok, query} <- UserToken.verify_change_email_token_query(token, context), - %UserToken{sent_to: email} <- Repo.one(query), - {:ok, _} <- Repo.transaction(user_email_multi(user, email, context)) do - :ok - else - _ -> :error - end - end - - defp user_email_multi(user, email, context) do - changeset = - user - |> User.email_changeset(%{email: email}) - |> User.confirm_changeset() - - Ecto.Multi.new() - |> Ecto.Multi.update(:user, changeset) - |> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, [context])) - end - - @doc """ - Delivers the update email instructions to the given user. - - ## Examples - - iex> deliver_update_email_instructions(user, current_email, &Routes.user_update_email_url(conn, :edit, &1)) - {:ok, %{to: ..., body: ...}} - - """ - def deliver_update_email_instructions(%User{} = user, current_email, update_email_url_fun) - when is_function(update_email_url_fun, 1) do - {encoded_token, user_token} = UserToken.build_email_token(user, "change:#{current_email}") - - Repo.insert!(user_token) - UserNotifier.deliver_update_email_instructions(user, update_email_url_fun.(encoded_token)) - end - - @doc """ - Returns an `%Ecto.Changeset{}` for changing the user password. - - ## Examples - - iex> change_user_password(user) - %Ecto.Changeset{data: %User{}} - - """ - def change_user_password(user, attrs \\ %{}) do - User.password_changeset(user, attrs, hash_password: false) - end - - @doc """ - Updates the user password. - - ## Examples - - iex> update_user_password(user, "valid password", %{password: ...}) - {:ok, %User{}} - - iex> update_user_password(user, "invalid password", %{password: ...}) - {:error, %Ecto.Changeset{}} - - """ - def update_user_password(user, password, attrs) do - changeset = - user - |> User.password_changeset(attrs) - |> User.validate_current_password(password) - - Ecto.Multi.new() - |> Ecto.Multi.update(:user, changeset) - |> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, :all)) - |> Repo.transaction() - |> case do - {:ok, %{user: user}} -> {:ok, user} - {:error, :user, changeset, _} -> {:error, changeset} - end - end - - ## Session - - @doc """ - Generates a session token. - """ - def generate_user_session_token(user) do - {token, user_token} = UserToken.build_session_token(user) - Repo.insert!(user_token) - token - end - - @doc """ - Gets the user with the given signed token. - """ - def get_user_by_session_token(token) do - {:ok, query} = UserToken.verify_session_token_query(token) - Repo.one(query) - end - - @doc """ - Deletes the signed token with the given context. - """ - def delete_session_token(token) do - Repo.delete_all(UserToken.token_and_context_query(token, "session")) - :ok - end - - ## Confirmation - - @doc """ - Delivers the confirmation email instructions to the given user. - - ## Examples - - iex> deliver_user_confirmation_instructions(user, &Routes.user_confirmation_url(conn, :edit, &1)) - {:ok, %{to: ..., body: ...}} - - iex> deliver_user_confirmation_instructions(confirmed_user, &Routes.user_confirmation_url(conn, :edit, &1)) - {:error, :already_confirmed} - - """ - def deliver_user_confirmation_instructions(%User{} = user, confirmation_url_fun) - when is_function(confirmation_url_fun, 1) do - if user.confirmed_at do - {:error, :already_confirmed} - else - {encoded_token, user_token} = UserToken.build_email_token(user, "confirm") - Repo.insert!(user_token) - UserNotifier.deliver_confirmation_instructions(user, confirmation_url_fun.(encoded_token)) - end - end - - @doc """ - Confirms a user by the given token. - - If the token matches, the user account is marked as confirmed - and the token is deleted. - """ - def confirm_user(token) do - with {:ok, query} <- UserToken.verify_email_token_query(token, "confirm"), - %User{} = user <- Repo.one(query), - {:ok, %{user: user}} <- Repo.transaction(confirm_user_multi(user)) do - {:ok, user} - else - _ -> :error - end - end - - defp confirm_user_multi(user) do - Ecto.Multi.new() - |> Ecto.Multi.update(:user, User.confirm_changeset(user)) - |> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, ["confirm"])) - end - - ## Reset password - - @doc """ - Delivers the reset password email to the given user. - - ## Examples - - iex> deliver_user_reset_password_instructions(user, &Routes.user_reset_password_url(conn, :edit, &1)) - {:ok, %{to: ..., body: ...}} - - """ - def deliver_user_reset_password_instructions(%User{} = user, reset_password_url_fun) - when is_function(reset_password_url_fun, 1) do - {encoded_token, user_token} = UserToken.build_email_token(user, "reset_password") - Repo.insert!(user_token) - UserNotifier.deliver_reset_password_instructions(user, reset_password_url_fun.(encoded_token)) - end - - @doc """ - Gets the user by reset password token. - - ## Examples - - iex> get_user_by_reset_password_token("validtoken") - %User{} - - iex> get_user_by_reset_password_token("invalidtoken") - nil - - """ - def get_user_by_reset_password_token(token) do - with {:ok, query} <- UserToken.verify_email_token_query(token, "reset_password"), - %User{} = user <- Repo.one(query) do - user - else - _ -> nil - end - end - - @doc """ - Resets the user password. - - ## Examples - - iex> reset_user_password(user, %{password: "new long password", password_confirmation: "new long password"}) - {:ok, %User{}} - - iex> reset_user_password(user, %{password: "valid", password_confirmation: "not the same"}) - {:error, %Ecto.Changeset{}} - - """ - def reset_user_password(user, attrs) do - Ecto.Multi.new() - |> Ecto.Multi.update(:user, User.password_changeset(user, attrs)) - |> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, :all)) - |> Repo.transaction() - |> case do - {:ok, %{user: user}} -> {:ok, user} - {:error, :user, changeset, _} -> {:error, changeset} - end - end -end diff --git a/lib/link_shortener/accounts/user.ex b/lib/link_shortener/accounts/user.ex deleted file mode 100644 index 7487093..0000000 --- a/lib/link_shortener/accounts/user.ex +++ /dev/null @@ -1,140 +0,0 @@ -defmodule LinkShortener.Accounts.User do - use Ecto.Schema - import Ecto.Changeset - - schema "users" do - field :email, :string - field :password, :string, virtual: true, redact: true - field :hashed_password, :string, redact: true - field :confirmed_at, :naive_datetime - - timestamps() - end - - @doc """ - A user changeset for registration. - - It is important to validate the length of both email and password. - Otherwise databases may truncate the email without warnings, which - could lead to unpredictable or insecure behaviour. Long passwords may - also be very expensive to hash for certain algorithms. - - ## Options - - * `:hash_password` - Hashes the password so it can be stored securely - in the database and ensures the password field is cleared to prevent - leaks in the logs. If password hashing is not needed and clearing the - password field is not desired (like when using this changeset for - validations on a LiveView form), this option can be set to `false`. - Defaults to `true`. - """ - def registration_changeset(user, attrs, opts \\ []) do - user - |> cast(attrs, [:email, :password]) - |> validate_email() - |> validate_password(opts) - end - - defp validate_email(changeset) do - changeset - |> validate_required([:email]) - |> validate_format(:email, ~r/^[^\s]+@[^\s]+$/, message: "must have the @ sign and no spaces") - |> validate_length(:email, max: 160) - |> unsafe_validate_unique(:email, LinkShortener.Repo) - |> unique_constraint(:email) - end - - defp validate_password(changeset, opts) do - changeset - |> validate_required([:password]) - |> validate_length(:password, min: 12, max: 72) - # |> validate_format(:password, ~r/[a-z]/, message: "at least one lower case character") - # |> validate_format(:password, ~r/[A-Z]/, message: "at least one upper case character") - # |> validate_format(:password, ~r/[!?@#$%^&*_0-9]/, message: "at least one digit or punctuation character") - |> maybe_hash_password(opts) - end - - defp maybe_hash_password(changeset, opts) do - hash_password? = Keyword.get(opts, :hash_password, true) - password = get_change(changeset, :password) - - if hash_password? && password && changeset.valid? do - changeset - # If using Bcrypt, then further validate it is at most 72 bytes long - |> validate_length(:password, max: 72, count: :bytes) - |> put_change(:hashed_password, Bcrypt.hash_pwd_salt(password)) - |> delete_change(:password) - else - changeset - end - end - - @doc """ - A user changeset for changing the email. - - It requires the email to change otherwise an error is added. - """ - def email_changeset(user, attrs) do - user - |> cast(attrs, [:email]) - |> validate_email() - |> case do - %{changes: %{email: _}} = changeset -> changeset - %{} = changeset -> add_error(changeset, :email, "did not change") - end - end - - @doc """ - A user changeset for changing the password. - - ## Options - - * `:hash_password` - Hashes the password so it can be stored securely - in the database and ensures the password field is cleared to prevent - leaks in the logs. If password hashing is not needed and clearing the - password field is not desired (like when using this changeset for - validations on a LiveView form), this option can be set to `false`. - Defaults to `true`. - """ - def password_changeset(user, attrs, opts \\ []) do - user - |> cast(attrs, [:password]) - |> validate_confirmation(:password, message: "does not match password") - |> validate_password(opts) - end - - @doc """ - Confirms the account by setting `confirmed_at`. - """ - def confirm_changeset(user) do - now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second) - change(user, confirmed_at: now) - end - - @doc """ - Verifies the password. - - If there is no user or the user doesn't have a password, we call - `Bcrypt.no_user_verify/0` to avoid timing attacks. - """ - def valid_password?(%LinkShortener.Accounts.User{hashed_password: hashed_password}, password) - when is_binary(hashed_password) and byte_size(password) > 0 do - Bcrypt.verify_pass(password, hashed_password) - end - - def valid_password?(_, _) do - Bcrypt.no_user_verify() - false - end - - @doc """ - Validates the current password otherwise adds an error to the changeset. - """ - def validate_current_password(changeset, password) do - if valid_password?(changeset.data, password) do - changeset - else - add_error(changeset, :current_password, "is not valid") - end - end -end diff --git a/lib/link_shortener/accounts/user_notifier.ex b/lib/link_shortener/accounts/user_notifier.ex deleted file mode 100644 index fca5c98..0000000 --- a/lib/link_shortener/accounts/user_notifier.ex +++ /dev/null @@ -1,79 +0,0 @@ -defmodule LinkShortener.Accounts.UserNotifier do - import Swoosh.Email - - alias LinkShortener.Mailer - - # Delivers the email using the application mailer. - defp deliver(recipient, subject, body) do - email = - new() - |> to(recipient) - |> from({"LinkShortener", "contact@example.com"}) - |> subject(subject) - |> text_body(body) - - with {:ok, _metadata} <- Mailer.deliver(email) do - {:ok, email} - end - end - - @doc """ - Deliver instructions to confirm account. - """ - def deliver_confirmation_instructions(user, url) do - deliver(user.email, "Confirmation instructions", """ - - ============================== - - Hi #{user.email}, - - You can confirm your account by visiting the URL below: - - #{url} - - If you didn't create an account with us, please ignore this. - - ============================== - """) - end - - @doc """ - Deliver instructions to reset a user password. - """ - def deliver_reset_password_instructions(user, url) do - deliver(user.email, "Reset password instructions", """ - - ============================== - - Hi #{user.email}, - - You can reset your password by visiting the URL below: - - #{url} - - If you didn't request this change, please ignore this. - - ============================== - """) - end - - @doc """ - Deliver instructions to update a user email. - """ - def deliver_update_email_instructions(user, url) do - deliver(user.email, "Update email instructions", """ - - ============================== - - Hi #{user.email}, - - You can change your email by visiting the URL below: - - #{url} - - If you didn't request this change, please ignore this. - - ============================== - """) - end -end diff --git a/lib/link_shortener/accounts/user_token.ex b/lib/link_shortener/accounts/user_token.ex deleted file mode 100644 index d5b739f..0000000 --- a/lib/link_shortener/accounts/user_token.ex +++ /dev/null @@ -1,179 +0,0 @@ -defmodule LinkShortener.Accounts.UserToken do - use Ecto.Schema - import Ecto.Query - alias LinkShortener.Accounts.UserToken - - @hash_algorithm :sha256 - @rand_size 32 - - # It is very important to keep the reset password token expiry short, - # since someone with access to the email may take over the account. - @reset_password_validity_in_days 1 - @confirm_validity_in_days 7 - @change_email_validity_in_days 7 - @session_validity_in_days 60 - - schema "users_tokens" do - field :token, :binary - field :context, :string - field :sent_to, :string - belongs_to :user, LinkShortener.Accounts.User - - timestamps(updated_at: false) - end - - @doc """ - Generates a token that will be stored in a signed place, - such as session or cookie. As they are signed, those - tokens do not need to be hashed. - - The reason why we store session tokens in the database, even - though Phoenix already provides a session cookie, is because - Phoenix' default session cookies are not persisted, they are - simply signed and potentially encrypted. This means they are - valid indefinitely, unless you change the signing/encryption - salt. - - Therefore, storing them allows individual user - sessions to be expired. The token system can also be extended - to store additional data, such as the device used for logging in. - You could then use this information to display all valid sessions - and devices in the UI and allow users to explicitly expire any - session they deem invalid. - """ - def build_session_token(user) do - token = :crypto.strong_rand_bytes(@rand_size) - {token, %UserToken{token: token, context: "session", user_id: user.id}} - end - - @doc """ - Checks if the token is valid and returns its underlying lookup query. - - The query returns the user found by the token, if any. - - The token is valid if it matches the value in the database and it has - not expired (after @session_validity_in_days). - """ - def verify_session_token_query(token) do - query = - from token in token_and_context_query(token, "session"), - join: user in assoc(token, :user), - where: token.inserted_at > ago(@session_validity_in_days, "day"), - select: user - - {:ok, query} - end - - @doc """ - Builds a token and its hash to be delivered to the user's email. - - The non-hashed token is sent to the user email while the - hashed part is stored in the database. The original token cannot be reconstructed, - which means anyone with read-only access to the database cannot directly use - the token in the application to gain access. Furthermore, if the user changes - their email in the system, the tokens sent to the previous email are no longer - valid. - - Users can easily adapt the existing code to provide other types of delivery methods, - for example, by phone numbers. - """ - def build_email_token(user, context) do - build_hashed_token(user, context, user.email) - end - - defp build_hashed_token(user, context, sent_to) do - token = :crypto.strong_rand_bytes(@rand_size) - hashed_token = :crypto.hash(@hash_algorithm, token) - - {Base.url_encode64(token, padding: false), - %UserToken{ - token: hashed_token, - context: context, - sent_to: sent_to, - user_id: user.id - }} - end - - @doc """ - Checks if the token is valid and returns its underlying lookup query. - - The query returns the user found by the token, if any. - - The given token is valid if it matches its hashed counterpart in the - database and the user email has not changed. This function also checks - if the token is being used within a certain period, depending on the - context. The default contexts supported by this function are either - "confirm", for account confirmation emails, and "reset_password", - for resetting the password. For verifying requests to change the email, - see `verify_change_email_token_query/2`. - """ - def verify_email_token_query(token, context) do - case Base.url_decode64(token, padding: false) do - {:ok, decoded_token} -> - hashed_token = :crypto.hash(@hash_algorithm, decoded_token) - days = days_for_context(context) - - query = - from token in token_and_context_query(hashed_token, context), - join: user in assoc(token, :user), - where: token.inserted_at > ago(^days, "day") and token.sent_to == user.email, - select: user - - {:ok, query} - - :error -> - :error - end - end - - defp days_for_context("confirm"), do: @confirm_validity_in_days - defp days_for_context("reset_password"), do: @reset_password_validity_in_days - - @doc """ - Checks if the token is valid and returns its underlying lookup query. - - The query returns the user found by the token, if any. - - This is used to validate requests to change the user - email. It is different from `verify_email_token_query/2` precisely because - `verify_email_token_query/2` validates the email has not changed, which is - the starting point by this function. - - The given token is valid if it matches its hashed counterpart in the - database and if it has not expired (after @change_email_validity_in_days). - The context must always start with "change:". - """ - def verify_change_email_token_query(token, "change:" <> _ = context) do - case Base.url_decode64(token, padding: false) do - {:ok, decoded_token} -> - hashed_token = :crypto.hash(@hash_algorithm, decoded_token) - - query = - from token in token_and_context_query(hashed_token, context), - where: token.inserted_at > ago(@change_email_validity_in_days, "day") - - {:ok, query} - - :error -> - :error - end - end - - @doc """ - Returns the token struct for the given token value and context. - """ - def token_and_context_query(token, context) do - from UserToken, where: [token: ^token, context: ^context] - end - - @doc """ - Gets all tokens for the given user for the given contexts. - """ - def user_and_contexts_query(user, :all) do - from t in UserToken, where: t.user_id == ^user.id - end - - def user_and_contexts_query(user, [_ | _] = contexts) do - from t in UserToken, where: t.user_id == ^user.id and t.context in ^contexts - end -end diff --git a/lib/link_shortener/application.ex b/lib/link_shortener/application.ex index b1d84ed..7f3a112 100644 --- a/lib/link_shortener/application.ex +++ b/lib/link_shortener/application.ex @@ -8,16 +8,16 @@ defmodule LinkShortener.Application do @impl true def start(_type, _args) do children = [ - # Start the Ecto repository - LinkShortener.Repo, - # Start the Telemetry supervisor LinkShortenerWeb.Telemetry, - # Start the PubSub system + LinkShortener.Repo, + {DNSCluster, query: Application.get_env(:link_shortener, :dns_cluster_query) || :ignore}, {Phoenix.PubSub, name: LinkShortener.PubSub}, - # Start the Endpoint (http/https) - LinkShortenerWeb.Endpoint + # Start the Finch HTTP client for sending emails + {Finch, name: LinkShortener.Finch}, # Start a worker by calling: LinkShortener.Worker.start_link(arg) - # {LinkShortener.Worker, arg} + # {LinkShortener.Worker, arg}, + # Start to serve requests, typically the last entry + LinkShortenerWeb.Endpoint ] # See https://hexdocs.pm/elixir/Supervisor.html diff --git a/lib/link_shortener_web.ex b/lib/link_shortener_web.ex index 19cb2ac..1c941ab 100644 --- a/lib/link_shortener_web.ex +++ b/lib/link_shortener_web.ex @@ -1,53 +1,60 @@ defmodule LinkShortenerWeb do @moduledoc """ The entrypoint for defining your web interface, such - as controllers, views, channels and so on. + as controllers, components, channels, and so on. This can be used in your application as: use LinkShortenerWeb, :controller - use LinkShortenerWeb, :view + use LinkShortenerWeb, :html - The definitions below will be executed for every view, - controller, etc, so keep them short and clean, focused + The definitions below will be executed for every controller, + component, etc, so keep them short and clean, focused on imports, uses and aliases. Do NOT define functions inside the quoted expressions - below. Instead, define any helper function in modules - and import those modules here. + below. Instead, define additional modules and import + those modules here. """ - def controller do + def static_paths, do: ~w(assets fonts images favicon.ico robots.txt) + + def router do quote do - use Phoenix.Controller, namespace: LinkShortenerWeb + use Phoenix.Router, helpers: false + # Import common connection and controller functions to use in pipelines import Plug.Conn - import LinkShortenerWeb.Gettext - alias LinkShortenerWeb.Router.Helpers, as: Routes + import Phoenix.Controller + import Phoenix.LiveView.Router + end + end + + def channel do + quote do + use Phoenix.Channel end end - def view do + def controller do quote do - use Phoenix.View, - root: "lib/link_shortener_web/templates", - namespace: LinkShortenerWeb + use Phoenix.Controller, + formats: [:html, :json], + layouts: [html: LinkShortenerWeb.Layouts] - # Import convenience functions from controllers - import Phoenix.Controller, - only: [get_flash: 1, get_flash: 2, view_module: 1, view_template: 1] + import Plug.Conn + import LinkShortenerWeb.Gettext - # Include shared imports and aliases for views - unquote(view_helpers()) + unquote(verified_routes()) end end def live_view do quote do use Phoenix.LiveView, - layout: {LinkShortenerWeb.LayoutView, "live.html"} + layout: {LinkShortenerWeb.Layouts, :app} - unquote(view_helpers()) + unquote(html_helpers()) end end @@ -55,54 +62,50 @@ defmodule LinkShortenerWeb do quote do use Phoenix.LiveComponent - unquote(view_helpers()) + unquote(html_helpers()) end end - def component do + def html do quote do use Phoenix.Component - unquote(view_helpers()) - end - end - - def router do - quote do - use Phoenix.Router + # Import convenience functions from controllers + import Phoenix.Controller, + only: [get_csrf_token: 0, view_module: 1, view_template: 1] - import Plug.Conn - import Phoenix.Controller - import Phoenix.LiveView.Router + # Include general helpers for rendering HTML + unquote(html_helpers()) end end - def channel do + defp html_helpers do quote do - use Phoenix.Channel + # HTML escaping functionality + import Phoenix.HTML + # Core UI components and translation + import LinkShortenerWeb.CoreComponents import LinkShortenerWeb.Gettext + + # Shortcut for generating JS commands + alias Phoenix.LiveView.JS + + # Routes generation with the ~p sigil + unquote(verified_routes()) end end - defp view_helpers do + def verified_routes do quote do - # Use all HTML functionality (forms, tags, etc) - use Phoenix.HTML - - # Import LiveView and .heex helpers (live_render, live_patch, <.form>, etc) - import Phoenix.LiveView.Helpers - - # Import basic rendering functionality (render, render_layout, etc) - import Phoenix.View - - import LinkShortenerWeb.ErrorHelpers - import LinkShortenerWeb.Gettext - alias LinkShortenerWeb.Router.Helpers, as: Routes + use Phoenix.VerifiedRoutes, + endpoint: LinkShortenerWeb.Endpoint, + router: LinkShortenerWeb.Router, + statics: LinkShortenerWeb.static_paths() end end @doc """ - When used, dispatch to the appropriate controller/view/etc. + When used, dispatch to the appropriate controller/live_view/etc. """ defmacro __using__(which) when is_atom(which) do apply(__MODULE__, which, []) diff --git a/lib/link_shortener_web/auth/error_handler.ex b/lib/link_shortener_web/auth/error_handler.ex deleted file mode 100644 index da9fd5e..0000000 --- a/lib/link_shortener_web/auth/error_handler.ex +++ /dev/null @@ -1,10 +0,0 @@ -defmodule LinkShortenerWeb.Auth.ErrorHandler do - import Plug.Conn - - def auth_error(conn, {type, _reason}, _opts) do - body = Poison.encode!(%{error: to_string(type)}) - conn - |> put_resp_content_type("application/json") - |> send_resp(401, body) - end -end diff --git a/lib/link_shortener_web/auth/guardian.ex b/lib/link_shortener_web/auth/guardian.ex deleted file mode 100644 index c53ec3c..0000000 --- a/lib/link_shortener_web/auth/guardian.ex +++ /dev/null @@ -1,31 +0,0 @@ -defmodule LinkShortenerWeb.Auth.Guardian do - use Guardian, otp_app: :link_shortener - - alias LinkShortener.Accounts - alias LinkShortener.Accounts.User - - def subject_for_token(user, _claims) do - sub = to_string(user.id) - {:ok, sub} - end - - def resource_from_claims(claims) do - id = claims["sub"] - resource = Accounts.get_user!(id) - {:ok, resource} - end - - def authenticate(email, password) do - with user <- Accounts.get_user_by_email_and_password(email, password) do - case user do - %User{} -> create_token(user) - nil -> {:error, :unauthorized} - end - end - end - - defp create_token(user) do - {:ok, token, _claims} = encode_and_sign(user) - {:ok, user, token} - end -end diff --git a/lib/link_shortener_web/auth/pipeline.ex b/lib/link_shortener_web/auth/pipeline.ex deleted file mode 100644 index 51e8332..0000000 --- a/lib/link_shortener_web/auth/pipeline.ex +++ /dev/null @@ -1,9 +0,0 @@ -defmodule LinkShortenerWeb.Auth.Pipeline do - use Guardian.Plug.Pipeline, otp_app: :link_shortener, - module: LinkShortenerWeb.Auth.Guardian, - error_handler: LinkShortenerWeb.Auth.ErrorHandler - - plug Guardian.Plug.VerifyHeader - plug Guardian.Plug.EnsureAuthenticated - plug Guardian.Plug.LoadResource -end diff --git a/lib/link_shortener_web/components/core_components.ex b/lib/link_shortener_web/components/core_components.ex new file mode 100644 index 0000000..3fa847c --- /dev/null +++ b/lib/link_shortener_web/components/core_components.ex @@ -0,0 +1,676 @@ +defmodule LinkShortenerWeb.CoreComponents do + @moduledoc """ + Provides core UI components. + + At first glance, this module may seem daunting, but its goal is to provide + core building blocks for your application, such as modals, tables, and + forms. The components consist mostly of markup and are well-documented + with doc strings and declarative assigns. You may customize and style + them in any way you want, based on your application growth and needs. + + The default components use Tailwind CSS, a utility-first CSS framework. + See the [Tailwind CSS documentation](https://tailwindcss.com) to learn + how to customize them or feel free to swap in another framework altogether. + + Icons are provided by [heroicons](https://heroicons.com). See `icon/1` for usage. + """ + use Phoenix.Component + + alias Phoenix.LiveView.JS + import LinkShortenerWeb.Gettext + + @doc """ + Renders a modal. + + ## Examples + + <.modal id="confirm-modal"> + This is a modal. + + + JS commands may be passed to the `:on_cancel` to configure + the closing/cancel event, for example: + + <.modal id="confirm" on_cancel={JS.navigate(~p"/posts")}> + This is another modal. + + + """ + attr :id, :string, required: true + attr :show, :boolean, default: false + attr :on_cancel, JS, default: %JS{} + slot :inner_block, required: true + + def modal(assigns) do + ~H""" + + """ + end + + def input(%{type: "select"} = assigns) do + ~H""" +
+ <.label for={@id}><%= @label %> + + <.error :for={msg <- @errors}><%= msg %> +
+ """ + end + + def input(%{type: "textarea"} = assigns) do + ~H""" +
+ <.label for={@id}><%= @label %> + + <.error :for={msg <- @errors}><%= msg %> +
+ """ + end + + # All other inputs text, datetime-local, url, password, etc. are handled here... + def input(assigns) do + ~H""" +
+ <.label for={@id}><%= @label %> + + <.error :for={msg <- @errors}><%= msg %> +
+ """ + end + + @doc """ + Renders a label. + """ + attr :for, :string, default: nil + slot :inner_block, required: true + + def label(assigns) do + ~H""" + + """ + end + + @doc """ + Generates a generic error message. + """ + slot :inner_block, required: true + + def error(assigns) do + ~H""" +

+ <.icon name="hero-exclamation-circle-mini" class="mt-0.5 h-5 w-5 flex-none" /> + <%= render_slot(@inner_block) %> +

+ """ + end + + @doc """ + Renders a header with title. + """ + attr :class, :string, default: nil + + slot :inner_block, required: true + slot :subtitle + slot :actions + + def header(assigns) do + ~H""" +
+
+

+ <%= render_slot(@inner_block) %> +

+

+ <%= render_slot(@subtitle) %> +

+
+
<%= render_slot(@actions) %>
+
+ """ + end + + @doc ~S""" + Renders a table with generic styling. + + ## Examples + + <.table id="users" rows={@users}> + <:col :let={user} label="id"><%= user.id %> + <:col :let={user} label="username"><%= user.username %> + + """ + attr :id, :string, required: true + attr :rows, :list, required: true + attr :row_id, :any, default: nil, doc: "the function for generating the row id" + attr :row_click, :any, default: nil, doc: "the function for handling phx-click on each row" + + attr :row_item, :any, + default: &Function.identity/1, + doc: "the function for mapping each row before calling the :col and :action slots" + + slot :col, required: true do + attr :label, :string + end + + slot :action, doc: "the slot for showing user actions in the last table column" + + def table(assigns) do + assigns = + with %{rows: %Phoenix.LiveView.LiveStream{}} <- assigns do + assign(assigns, row_id: assigns.row_id || fn {id, _item} -> id end) + end + + ~H""" +
+ + + + + + + + + + + + + +
<%= col[:label] %> + <%= gettext("Actions") %> +
+
+ + + <%= render_slot(col, @row_item.(row)) %> + +
+
+
+ + + <%= render_slot(action, @row_item.(row)) %> + +
+
+
+ """ + end + + @doc """ + Renders a data list. + + ## Examples + + <.list> + <:item title="Title"><%= @post.title %> + <:item title="Views"><%= @post.views %> + + """ + slot :item, required: true do + attr :title, :string, required: true + end + + def list(assigns) do + ~H""" +
+
+
+
<%= item.title %>
+
<%= render_slot(item) %>
+
+
+
+ """ + end + + @doc """ + Renders a back navigation link. + + ## Examples + + <.back navigate={~p"/posts"}>Back to posts + """ + attr :navigate, :any, required: true + slot :inner_block, required: true + + def back(assigns) do + ~H""" +
+ <.link + navigate={@navigate} + class="text-sm font-semibold leading-6 text-zinc-900 hover:text-zinc-700" + > + <.icon name="hero-arrow-left-solid" class="h-3 w-3" /> + <%= render_slot(@inner_block) %> + +
+ """ + end + + @doc """ + Renders a [Heroicon](https://heroicons.com). + + Heroicons come in three styles – outline, solid, and mini. + By default, the outline style is used, but solid and mini may + be applied by using the `-solid` and `-mini` suffix. + + You can customize the size and colors of the icons by setting + width, height, and background color classes. + + Icons are extracted from the `deps/heroicons` directory and bundled within + your compiled app.css by the plugin in your `assets/tailwind.config.js`. + + ## Examples + + <.icon name="hero-x-mark-solid" /> + <.icon name="hero-arrow-path" class="ml-1 w-3 h-3 animate-spin" /> + """ + attr :name, :string, required: true + attr :class, :string, default: nil + + def icon(%{name: "hero-" <> _} = assigns) do + ~H""" + + """ + end + + ## JS Commands + + def show(js \\ %JS{}, selector) do + JS.show(js, + to: selector, + time: 300, + transition: + {"transition-all transform ease-out duration-300", + "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95", + "opacity-100 translate-y-0 sm:scale-100"} + ) + end + + def hide(js \\ %JS{}, selector) do + JS.hide(js, + to: selector, + time: 200, + transition: + {"transition-all transform ease-in duration-200", + "opacity-100 translate-y-0 sm:scale-100", + "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"} + ) + end + + def show_modal(js \\ %JS{}, id) when is_binary(id) do + js + |> JS.show(to: "##{id}") + |> JS.show( + to: "##{id}-bg", + time: 300, + transition: {"transition-all transform ease-out duration-300", "opacity-0", "opacity-100"} + ) + |> show("##{id}-container") + |> JS.add_class("overflow-hidden", to: "body") + |> JS.focus_first(to: "##{id}-content") + end + + def hide_modal(js \\ %JS{}, id) do + js + |> JS.hide( + to: "##{id}-bg", + transition: {"transition-all transform ease-in duration-200", "opacity-100", "opacity-0"} + ) + |> hide("##{id}-container") + |> JS.hide(to: "##{id}", transition: {"block", "block", "hidden"}) + |> JS.remove_class("overflow-hidden", to: "body") + |> JS.pop_focus() + end + + @doc """ + Translates an error message using gettext. + """ + def translate_error({msg, opts}) do + # When using gettext, we typically pass the strings we want + # to translate as a static argument: + # + # # Translate the number of files with plural rules + # dngettext("errors", "1 file", "%{count} files", count) + # + # However the error messages in our forms and APIs are generated + # dynamically, so we need to translate them by calling Gettext + # with our gettext backend as first argument. Translations are + # available in the errors.po file (as we use the "errors" domain). + if count = opts[:count] do + Gettext.dngettext(LinkShortenerWeb.Gettext, "errors", msg, msg, count, opts) + else + Gettext.dgettext(LinkShortenerWeb.Gettext, "errors", msg, opts) + end + end + + @doc """ + Translates the errors for a field from a keyword list of errors. + """ + def translate_errors(errors, field) when is_list(errors) do + for {^field, {msg, opts}} <- errors, do: translate_error({msg, opts}) + end +end diff --git a/lib/link_shortener_web/components/layouts.ex b/lib/link_shortener_web/components/layouts.ex new file mode 100644 index 0000000..333b1af --- /dev/null +++ b/lib/link_shortener_web/components/layouts.ex @@ -0,0 +1,14 @@ +defmodule LinkShortenerWeb.Layouts do + @moduledoc """ + This module holds different layouts used by your application. + + See the `layouts` directory for all templates available. + The "root" layout is a skeleton rendered as part of the + application router. The "app" layout is set as the default + layout on both `use LinkShortenerWeb, :controller` and + `use LinkShortenerWeb, :live_view`. + """ + use LinkShortenerWeb, :html + + embed_templates "layouts/*" +end diff --git a/lib/link_shortener_web/components/layouts/app.html.heex b/lib/link_shortener_web/components/layouts/app.html.heex new file mode 100644 index 0000000..e23bfc8 --- /dev/null +++ b/lib/link_shortener_web/components/layouts/app.html.heex @@ -0,0 +1,32 @@ +
+
+
+ + + +

+ v<%= Application.spec(:phoenix, :vsn) %> +

+
+ +
+
+
+
+ <.flash_group flash={@flash} /> + <%= @inner_content %> +
+
diff --git a/lib/link_shortener_web/components/layouts/root.html.heex b/lib/link_shortener_web/components/layouts/root.html.heex new file mode 100644 index 0000000..2227416 --- /dev/null +++ b/lib/link_shortener_web/components/layouts/root.html.heex @@ -0,0 +1,17 @@ + + + + + + + <.live_title suffix=" · Phoenix Framework"> + <%= assigns[:page_title] || "LinkShortener" %> + + + + + + <%= @inner_content %> + + diff --git a/lib/link_shortener_web/controllers/api/v1/link_controller.ex b/lib/link_shortener_web/controllers/api/v1/link_controller.ex deleted file mode 100644 index 228e778..0000000 --- a/lib/link_shortener_web/controllers/api/v1/link_controller.ex +++ /dev/null @@ -1,43 +0,0 @@ -defmodule LinkShortenerWeb.Api.V1.LinkController do - use LinkShortenerWeb, :controller - - alias LinkShortener.Links - alias LinkShortener.Links.Link - - action_fallback LinkShortenerWeb.FallbackController - - def index(conn, _params) do - links = Links.get_all() - render(conn, "index.json", links: links) - end - - def create(conn, %{"link" => link_params}) do - with {:ok, %Link{} = link} <- Links.insert_one(link_params) do - conn - |> put_status(:created) - |> put_resp_header("location", Routes.v1_link_path(conn, :show, link)) - |> render("show.json", link: link) - end - end - - def show(conn, %{"id" => id}) do - link = Links.get_one!(id) - render(conn, "show.json", link: link) - end - - def update(conn, %{"id" => id, "link" => link_params}) do - link = Links.get_one!(id) - - with {:ok, %Link{} = link} <- Links.update_one(link, link_params) do - render(conn, "show.json", link: link) - end - end - - def delete(conn, %{"id" => id}) do - link = Links.get_one!(id) - - with {:ok, %Link{}} <- Links.delete_one(link) do - send_resp(conn, :no_content, "") - end - end -end diff --git a/lib/link_shortener_web/controllers/api/v1/user_controller.ex b/lib/link_shortener_web/controllers/api/v1/user_controller.ex deleted file mode 100644 index a3a8481..0000000 --- a/lib/link_shortener_web/controllers/api/v1/user_controller.ex +++ /dev/null @@ -1,26 +0,0 @@ -defmodule LinkShortenerWeb.Api.V1.UserController do - use LinkShortenerWeb, :controller - - alias LinkShortener.Accounts - alias LinkShortener.Accounts.User - alias LinkShortenerWeb.Auth.Guardian - - action_fallback LinkShortenerWeb.FallbackController - - def create(conn, %{"user" => user_params}) do - with {:ok, %User{} = user} <- Accounts.register_user(user_params), - {:ok, token, _claims} <- Guardian.encode_and_sign(user) do - conn - |> put_status(:created) - |> render("user.json", %{user: user, token: token}) - end - end - - def signin(conn, %{"email" => email, "password" => password}) do - with {:ok, user, token} <- Guardian.authenticate(email, password) do - conn - |> put_status(:created) - |> render("user.json", %{user: user, token: token}) - end - end -end diff --git a/lib/link_shortener_web/controllers/error_html.ex b/lib/link_shortener_web/controllers/error_html.ex new file mode 100644 index 0000000..b763810 --- /dev/null +++ b/lib/link_shortener_web/controllers/error_html.ex @@ -0,0 +1,24 @@ +defmodule LinkShortenerWeb.ErrorHTML do + @moduledoc """ + This module is invoked by your endpoint in case of errors on HTML requests. + + See config/config.exs. + """ + use LinkShortenerWeb, :html + + # If you want to customize your error pages, + # uncomment the embed_templates/1 call below + # and add pages to the error directory: + # + # * lib/link_shortener_web/controllers/error_html/404.html.heex + # * lib/link_shortener_web/controllers/error_html/500.html.heex + # + # embed_templates "error_html/*" + + # The default is to render a plain text page based on + # the template name. For example, "404.html" becomes + # "Not Found". + def render(template, _assigns) do + Phoenix.Controller.status_message_from_template(template) + end +end diff --git a/lib/link_shortener_web/controllers/error_json.ex b/lib/link_shortener_web/controllers/error_json.ex new file mode 100644 index 0000000..b54f2c1 --- /dev/null +++ b/lib/link_shortener_web/controllers/error_json.ex @@ -0,0 +1,21 @@ +defmodule LinkShortenerWeb.ErrorJSON do + @moduledoc """ + This module is invoked by your endpoint in case of errors on JSON requests. + + See config/config.exs. + """ + + # If you want to customize a particular status code, + # you may add your own clauses, such as: + # + # def render("500.json", _assigns) do + # %{errors: %{detail: "Internal Server Error"}} + # end + + # By default, Phoenix returns the status message from + # the template name. For example, "404.json" becomes + # "Not Found". + def render(template, _assigns) do + %{errors: %{detail: Phoenix.Controller.status_message_from_template(template)}} + end +end diff --git a/lib/link_shortener_web/controllers/fallback_controller.ex b/lib/link_shortener_web/controllers/fallback_controller.ex deleted file mode 100644 index c1a87df..0000000 --- a/lib/link_shortener_web/controllers/fallback_controller.ex +++ /dev/null @@ -1,30 +0,0 @@ -defmodule LinkShortenerWeb.FallbackController do - @moduledoc """ - Translates controller action results into valid `Plug.Conn` responses. - - See `Phoenix.Controller.action_fallback/1` for more details. - """ - use LinkShortenerWeb, :controller - - # This clause handles errors returned by Ecto's insert/update/delete. - def call(conn, {:error, %Ecto.Changeset{} = changeset}) do - conn - |> put_status(:unprocessable_entity) - |> put_view(LinkShortenerWeb.ChangesetView) - |> render("error.json", changeset: changeset) - end - - # This clause is an example of how to handle resources that cannot be found. - def call(conn, {:error, :not_found}) do - conn - |> put_status(:not_found) - |> put_view(LinkShortenerWeb.ErrorView) - |> render(:"404") - end - - def call(conn, {:error, :unauthorized}) do - conn - |> put_status(:unauthorized) - |> render(LinkShortenerWeb.ErrorView, :"401") - end -end diff --git a/lib/link_shortener_web/controllers/page_controller.ex b/lib/link_shortener_web/controllers/page_controller.ex index 48518cd..a714c13 100644 --- a/lib/link_shortener_web/controllers/page_controller.ex +++ b/lib/link_shortener_web/controllers/page_controller.ex @@ -1,7 +1,9 @@ defmodule LinkShortenerWeb.PageController do use LinkShortenerWeb, :controller - def index(conn, _params) do - render(conn, "index.html") + def home(conn, _params) do + # The home page is often custom made, + # so skip the default app layout. + render(conn, :home, layout: false) end end diff --git a/lib/link_shortener_web/controllers/page_html.ex b/lib/link_shortener_web/controllers/page_html.ex new file mode 100644 index 0000000..a4abf28 --- /dev/null +++ b/lib/link_shortener_web/controllers/page_html.ex @@ -0,0 +1,10 @@ +defmodule LinkShortenerWeb.PageHTML do + @moduledoc """ + This module contains pages rendered by PageController. + + See the `page_html` directory for all templates available. + """ + use LinkShortenerWeb, :html + + embed_templates "page_html/*" +end diff --git a/lib/link_shortener_web/controllers/page_html/home.html.heex b/lib/link_shortener_web/controllers/page_html/home.html.heex new file mode 100644 index 0000000..dc1820b --- /dev/null +++ b/lib/link_shortener_web/controllers/page_html/home.html.heex @@ -0,0 +1,222 @@ +<.flash_group flash={@flash} /> + +
+
+ +

+ Phoenix Framework + + v<%= Application.spec(:phoenix, :vsn) %> + +

+

+ Peace of mind from prototype to production. +

+

+ Build rich, interactive web applications quickly, with less code and fewer moving parts. Join our growing community of developers using Phoenix to craft APIs, HTML5 apps and more, for fun or at scale. +

+ +
+
diff --git a/lib/link_shortener_web/controllers/redirect_controller.ex b/lib/link_shortener_web/controllers/redirect_controller.ex deleted file mode 100644 index 37f7f15..0000000 --- a/lib/link_shortener_web/controllers/redirect_controller.ex +++ /dev/null @@ -1,9 +0,0 @@ -defmodule LinkShortenerWeb.RedirectController do - use LinkShortenerWeb, :controller - alias LinkShortener.Links - - def show(conn, %{"shorten" => shorten}) do - %{url: url} = Links.get_one_by_shorten(shorten) - redirect(conn, external: url) - end -end diff --git a/lib/link_shortener_web/controllers/user_auth.ex b/lib/link_shortener_web/controllers/user_auth.ex deleted file mode 100644 index 0be9693..0000000 --- a/lib/link_shortener_web/controllers/user_auth.ex +++ /dev/null @@ -1,149 +0,0 @@ -defmodule LinkShortenerWeb.UserAuth do - import Plug.Conn - import Phoenix.Controller - - alias LinkShortener.Accounts - alias LinkShortenerWeb.Router.Helpers, as: Routes - - # Make the remember me cookie valid for 60 days. - # If you want bump or reduce this value, also change - # the token expiry itself in UserToken. - @max_age 60 * 60 * 24 * 60 - @remember_me_cookie "_link_shortener_web_user_remember_me" - @remember_me_options [sign: true, max_age: @max_age, same_site: "Lax"] - - @doc """ - Logs the user in. - - It renews the session ID and clears the whole session - to avoid fixation attacks. See the renew_session - function to customize this behaviour. - - It also sets a `:live_socket_id` key in the session, - so LiveView sessions are identified and automatically - disconnected on log out. The line can be safely removed - if you are not using LiveView. - """ - def log_in_user(conn, user, params \\ %{}) do - token = Accounts.generate_user_session_token(user) - user_return_to = get_session(conn, :user_return_to) - - conn - |> renew_session() - |> put_session(:user_token, token) - |> put_session(:live_socket_id, "users_sessions:#{Base.url_encode64(token)}") - |> maybe_write_remember_me_cookie(token, params) - |> redirect(to: user_return_to || signed_in_path(conn)) - end - - defp maybe_write_remember_me_cookie(conn, token, %{"remember_me" => "true"}) do - put_resp_cookie(conn, @remember_me_cookie, token, @remember_me_options) - end - - defp maybe_write_remember_me_cookie(conn, _token, _params) do - conn - end - - # This function renews the session ID and erases the whole - # session to avoid fixation attacks. If there is any data - # in the session you may want to preserve after log in/log out, - # you must explicitly fetch the session data before clearing - # and then immediately set it after clearing, for example: - # - # defp renew_session(conn) do - # preferred_locale = get_session(conn, :preferred_locale) - # - # conn - # |> configure_session(renew: true) - # |> clear_session() - # |> put_session(:preferred_locale, preferred_locale) - # end - # - defp renew_session(conn) do - conn - |> configure_session(renew: true) - |> clear_session() - end - - @doc """ - Logs the user out. - - It clears all session data for safety. See renew_session. - """ - def log_out_user(conn) do - user_token = get_session(conn, :user_token) - user_token && Accounts.delete_session_token(user_token) - - if live_socket_id = get_session(conn, :live_socket_id) do - LinkShortenerWeb.Endpoint.broadcast(live_socket_id, "disconnect", %{}) - end - - conn - |> renew_session() - |> delete_resp_cookie(@remember_me_cookie) - |> redirect(to: "/") - end - - @doc """ - Authenticates the user by looking into the session - and remember me token. - """ - def fetch_current_user(conn, _opts) do - {user_token, conn} = ensure_user_token(conn) - user = user_token && Accounts.get_user_by_session_token(user_token) - assign(conn, :current_user, user) - end - - defp ensure_user_token(conn) do - if user_token = get_session(conn, :user_token) do - {user_token, conn} - else - conn = fetch_cookies(conn, signed: [@remember_me_cookie]) - - if user_token = conn.cookies[@remember_me_cookie] do - {user_token, put_session(conn, :user_token, user_token)} - else - {nil, conn} - end - end - end - - @doc """ - Used for routes that require the user to not be authenticated. - """ - def redirect_if_user_is_authenticated(conn, _opts) do - if conn.assigns[:current_user] do - conn - |> redirect(to: signed_in_path(conn)) - |> halt() - else - conn - end - end - - @doc """ - Used for routes that require the user to be authenticated. - - If you want to enforce the user email is confirmed before - they use the application at all, here would be a good place. - """ - def require_authenticated_user(conn, _opts) do - if conn.assigns[:current_user] do - conn - else - conn - |> put_flash(:error, "You must log in to access this page.") - |> maybe_store_return_to() - |> redirect(to: Routes.user_session_path(conn, :new)) - |> halt() - end - end - - defp maybe_store_return_to(%{method: "GET"} = conn) do - put_session(conn, :user_return_to, current_path(conn)) - end - - defp maybe_store_return_to(conn), do: conn - - defp signed_in_path(_conn), do: "/" -end diff --git a/lib/link_shortener_web/controllers/user_confirmation_controller.ex b/lib/link_shortener_web/controllers/user_confirmation_controller.ex deleted file mode 100644 index 57b3357..0000000 --- a/lib/link_shortener_web/controllers/user_confirmation_controller.ex +++ /dev/null @@ -1,56 +0,0 @@ -defmodule LinkShortenerWeb.UserConfirmationController do - use LinkShortenerWeb, :controller - - alias LinkShortener.Accounts - - def new(conn, _params) do - render(conn, "new.html") - end - - def create(conn, %{"user" => %{"email" => email}}) do - if user = Accounts.get_user_by_email(email) do - Accounts.deliver_user_confirmation_instructions( - user, - &Routes.user_confirmation_url(conn, :edit, &1) - ) - end - - conn - |> put_flash( - :info, - "If your email is in our system and it has not been confirmed yet, " <> - "you will receive an email with instructions shortly." - ) - |> redirect(to: "/") - end - - def edit(conn, %{"token" => token}) do - render(conn, "edit.html", token: token) - end - - # Do not log in the user after confirmation to avoid a - # leaked token giving the user access to the account. - def update(conn, %{"token" => token}) do - case Accounts.confirm_user(token) do - {:ok, _} -> - conn - |> put_flash(:info, "User confirmed successfully.") - |> redirect(to: "/") - - :error -> - # If there is a current user and the account was already confirmed, - # then odds are that the confirmation link was already visited, either - # by some automation or by the user themselves, so we redirect without - # a warning message. - case conn.assigns do - %{current_user: %{confirmed_at: confirmed_at}} when not is_nil(confirmed_at) -> - redirect(conn, to: "/") - - %{} -> - conn - |> put_flash(:error, "User confirmation link is invalid or it has expired.") - |> redirect(to: "/") - end - end - end -end diff --git a/lib/link_shortener_web/controllers/user_registration_controller.ex b/lib/link_shortener_web/controllers/user_registration_controller.ex deleted file mode 100644 index b1e29e5..0000000 --- a/lib/link_shortener_web/controllers/user_registration_controller.ex +++ /dev/null @@ -1,30 +0,0 @@ -defmodule LinkShortenerWeb.UserRegistrationController do - use LinkShortenerWeb, :controller - - alias LinkShortener.Accounts - alias LinkShortener.Accounts.User - alias LinkShortenerWeb.UserAuth - - def new(conn, _params) do - changeset = Accounts.change_user_registration(%User{}) - render(conn, "new.html", changeset: changeset) - end - - def create(conn, %{"user" => user_params}) do - case Accounts.register_user(user_params) do - {:ok, user} -> - {:ok, _} = - Accounts.deliver_user_confirmation_instructions( - user, - &Routes.user_confirmation_url(conn, :edit, &1) - ) - - conn - |> put_flash(:info, "User created successfully.") - |> UserAuth.log_in_user(user) - - {:error, %Ecto.Changeset{} = changeset} -> - render(conn, "new.html", changeset: changeset) - end - end -end diff --git a/lib/link_shortener_web/controllers/user_reset_password_controller.ex b/lib/link_shortener_web/controllers/user_reset_password_controller.ex deleted file mode 100644 index 6a09700..0000000 --- a/lib/link_shortener_web/controllers/user_reset_password_controller.ex +++ /dev/null @@ -1,58 +0,0 @@ -defmodule LinkShortenerWeb.UserResetPasswordController do - use LinkShortenerWeb, :controller - - alias LinkShortener.Accounts - - plug :get_user_by_reset_password_token when action in [:edit, :update] - - def new(conn, _params) do - render(conn, "new.html") - end - - def create(conn, %{"user" => %{"email" => email}}) do - if user = Accounts.get_user_by_email(email) do - Accounts.deliver_user_reset_password_instructions( - user, - &Routes.user_reset_password_url(conn, :edit, &1) - ) - end - - conn - |> put_flash( - :info, - "If your email is in our system, you will receive instructions to reset your password shortly." - ) - |> redirect(to: "/") - end - - def edit(conn, _params) do - render(conn, "edit.html", changeset: Accounts.change_user_password(conn.assigns.user)) - end - - # Do not log in the user after reset password to avoid a - # leaked token giving the user access to the account. - def update(conn, %{"user" => user_params}) do - case Accounts.reset_user_password(conn.assigns.user, user_params) do - {:ok, _} -> - conn - |> put_flash(:info, "Password reset successfully.") - |> redirect(to: Routes.user_session_path(conn, :new)) - - {:error, changeset} -> - render(conn, "edit.html", changeset: changeset) - end - end - - defp get_user_by_reset_password_token(conn, _opts) do - %{"token" => token} = conn.params - - if user = Accounts.get_user_by_reset_password_token(token) do - conn |> assign(:user, user) |> assign(:token, token) - else - conn - |> put_flash(:error, "Reset password link is invalid or it has expired.") - |> redirect(to: "/") - |> halt() - end - end -end diff --git a/lib/link_shortener_web/controllers/user_session_controller.ex b/lib/link_shortener_web/controllers/user_session_controller.ex deleted file mode 100644 index 630e5a2..0000000 --- a/lib/link_shortener_web/controllers/user_session_controller.ex +++ /dev/null @@ -1,27 +0,0 @@ -defmodule LinkShortenerWeb.UserSessionController do - use LinkShortenerWeb, :controller - - alias LinkShortener.Accounts - alias LinkShortenerWeb.UserAuth - - def new(conn, _params) do - render(conn, "new.html", error_message: nil) - end - - def create(conn, %{"user" => user_params}) do - %{"email" => email, "password" => password} = user_params - - if user = Accounts.get_user_by_email_and_password(email, password) do - UserAuth.log_in_user(conn, user, user_params) - else - # In order to prevent user enumeration attacks, don't disclose whether the email is registered. - render(conn, "new.html", error_message: "Invalid email or password") - end - end - - def delete(conn, _params) do - conn - |> put_flash(:info, "Logged out successfully.") - |> UserAuth.log_out_user() - end -end diff --git a/lib/link_shortener_web/controllers/user_settings_controller.ex b/lib/link_shortener_web/controllers/user_settings_controller.ex deleted file mode 100644 index 55f1c7e..0000000 --- a/lib/link_shortener_web/controllers/user_settings_controller.ex +++ /dev/null @@ -1,74 +0,0 @@ -defmodule LinkShortenerWeb.UserSettingsController do - use LinkShortenerWeb, :controller - - alias LinkShortener.Accounts - alias LinkShortenerWeb.UserAuth - - plug :assign_email_and_password_changesets - - def edit(conn, _params) do - render(conn, "edit.html") - end - - def update(conn, %{"action" => "update_email"} = params) do - %{"current_password" => password, "user" => user_params} = params - user = conn.assigns.current_user - - case Accounts.apply_user_email(user, password, user_params) do - {:ok, applied_user} -> - Accounts.deliver_update_email_instructions( - applied_user, - user.email, - &Routes.user_settings_url(conn, :confirm_email, &1) - ) - - conn - |> put_flash( - :info, - "A link to confirm your email change has been sent to the new address." - ) - |> redirect(to: Routes.user_settings_path(conn, :edit)) - - {:error, changeset} -> - render(conn, "edit.html", email_changeset: changeset) - end - end - - def update(conn, %{"action" => "update_password"} = params) do - %{"current_password" => password, "user" => user_params} = params - user = conn.assigns.current_user - - case Accounts.update_user_password(user, password, user_params) do - {:ok, user} -> - conn - |> put_flash(:info, "Password updated successfully.") - |> put_session(:user_return_to, Routes.user_settings_path(conn, :edit)) - |> UserAuth.log_in_user(user) - - {:error, changeset} -> - render(conn, "edit.html", password_changeset: changeset) - end - end - - def confirm_email(conn, %{"token" => token}) do - case Accounts.update_user_email(conn.assigns.current_user, token) do - :ok -> - conn - |> put_flash(:info, "Email changed successfully.") - |> redirect(to: Routes.user_settings_path(conn, :edit)) - - :error -> - conn - |> put_flash(:error, "Email change link is invalid or it has expired.") - |> redirect(to: Routes.user_settings_path(conn, :edit)) - end - end - - defp assign_email_and_password_changesets(conn, _opts) do - user = conn.assigns.current_user - - conn - |> assign(:email_changeset, Accounts.change_user_email(user)) - |> assign(:password_changeset, Accounts.change_user_password(user)) - end -end diff --git a/lib/link_shortener_web/endpoint.ex b/lib/link_shortener_web/endpoint.ex index 30daa64..7324f90 100644 --- a/lib/link_shortener_web/endpoint.ex +++ b/lib/link_shortener_web/endpoint.ex @@ -7,10 +7,13 @@ defmodule LinkShortenerWeb.Endpoint do @session_options [ store: :cookie, key: "_link_shortener_key", - signing_salt: "O0shzZgl" + signing_salt: "dEcSzKxO", + same_site: "Lax" ] - socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]] + socket "/live", Phoenix.LiveView.Socket, + websocket: [connect_info: [session: @session_options]], + longpoll: [connect_info: [session: @session_options]] # Serve at "/" the static files from "priv/static" directory. # @@ -20,7 +23,7 @@ defmodule LinkShortenerWeb.Endpoint do at: "/", from: :link_shortener, gzip: false, - only: ~w(assets fonts images favicon.ico robots.txt) + only: LinkShortenerWeb.static_paths() # Code reloading can be explicitly enabled under the # :code_reloader configuration of your endpoint. diff --git a/lib/link_shortener_web/router.ex b/lib/link_shortener_web/router.ex index d2ee15f..64ed714 100644 --- a/lib/link_shortener_web/router.ex +++ b/lib/link_shortener_web/router.ex @@ -1,110 +1,44 @@ defmodule LinkShortenerWeb.Router do use LinkShortenerWeb, :router - import LinkShortenerWeb.UserAuth - pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_live_flash - plug :put_root_layout, {LinkShortenerWeb.LayoutView, :root} + plug :put_root_layout, html: {LinkShortenerWeb.Layouts, :root} plug :protect_from_forgery plug :put_secure_browser_headers - plug :fetch_current_user end pipeline :api do plug :accepts, ["json"] end - pipeline :auth do - plug LinkShortenerWeb.Auth.Pipeline - end - scope "/", LinkShortenerWeb do pipe_through :browser - get "/", PageController, :index - get "/u/:shorten", RedirectController, :show + get "/", PageController, :home end # Other scopes may use custom stacks. - scope "/api", LinkShortenerWeb do - pipe_through :api - - scope "/v1", Api.V1, as: :v1 do - post "/users/signup", UserController, :create - post "/users/signin", UserController, :signin - end - end - - scope "/api", LinkShortenerWeb do - pipe_through [:api, :auth] - - scope "/v1", Api.V1, as: :v1 do - resources "/links", LinkController - end - end - - # Enables LiveDashboard only for development - # - # If you want to use the LiveDashboard in production, you should put - # it behind authentication and allow only admins to access it. - # If your application does not have an admins-only section yet, - # you can use Plug.BasicAuth to set up some basic authentication - # as long as you are also using SSL (which you should anyway). - if Mix.env() in [:dev, :test] do + # scope "/api", LinkShortenerWeb do + # pipe_through :api + # end + + # Enable LiveDashboard and Swoosh mailbox preview in development + if Application.compile_env(:link_shortener, :dev_routes) do + # If you want to use the LiveDashboard in production, you should put + # it behind authentication and allow only admins to access it. + # If your application does not have an admins-only section yet, + # you can use Plug.BasicAuth to set up some basic authentication + # as long as you are also using SSL (which you should anyway). import Phoenix.LiveDashboard.Router - scope "/" do - pipe_through :browser - - live_dashboard "/dashboard", metrics: LinkShortenerWeb.Telemetry - end - end - - # Enables the Swoosh mailbox preview in development. - # - # Note that preview only shows emails that were sent by the same - # node running the Phoenix server. - if Mix.env() == :dev do scope "/dev" do pipe_through :browser + live_dashboard "/dashboard", metrics: LinkShortenerWeb.Telemetry forward "/mailbox", Plug.Swoosh.MailboxPreview end end - - ## Authentication routes - - scope "/", LinkShortenerWeb do - pipe_through [:browser, :redirect_if_user_is_authenticated] - - get "/users/register", UserRegistrationController, :new - post "/users/register", UserRegistrationController, :create - get "/users/log_in", UserSessionController, :new - post "/users/log_in", UserSessionController, :create - get "/users/reset_password", UserResetPasswordController, :new - post "/users/reset_password", UserResetPasswordController, :create - get "/users/reset_password/:token", UserResetPasswordController, :edit - put "/users/reset_password/:token", UserResetPasswordController, :update - end - - scope "/", LinkShortenerWeb do - pipe_through [:browser, :require_authenticated_user] - - get "/users/settings", UserSettingsController, :edit - put "/users/settings", UserSettingsController, :update - get "/users/settings/confirm_email/:token", UserSettingsController, :confirm_email - end - - scope "/", LinkShortenerWeb do - pipe_through [:browser] - - delete "/users/log_out", UserSessionController, :delete - get "/users/confirm", UserConfirmationController, :new - post "/users/confirm", UserConfirmationController, :create - get "/users/confirm/:token", UserConfirmationController, :edit - post "/users/confirm/:token", UserConfirmationController, :update - end end diff --git a/lib/link_shortener_web/telemetry.ex b/lib/link_shortener_web/telemetry.ex index bab42eb..bb3ac2d 100644 --- a/lib/link_shortener_web/telemetry.ex +++ b/lib/link_shortener_web/telemetry.ex @@ -22,13 +22,34 @@ defmodule LinkShortenerWeb.Telemetry do def metrics do [ # Phoenix Metrics + summary("phoenix.endpoint.start.system_time", + unit: {:native, :millisecond} + ), summary("phoenix.endpoint.stop.duration", unit: {:native, :millisecond} ), + summary("phoenix.router_dispatch.start.system_time", + tags: [:route], + unit: {:native, :millisecond} + ), + summary("phoenix.router_dispatch.exception.duration", + tags: [:route], + unit: {:native, :millisecond} + ), summary("phoenix.router_dispatch.stop.duration", tags: [:route], unit: {:native, :millisecond} ), + summary("phoenix.socket_connected.duration", + unit: {:native, :millisecond} + ), + summary("phoenix.channel_joined.duration", + unit: {:native, :millisecond} + ), + summary("phoenix.channel_handled_in.duration", + tags: [:event], + unit: {:native, :millisecond} + ), # Database Metrics summary("link_shortener.repo.query.total_time", diff --git a/lib/link_shortener_web/templates/layout/_user_menu.html.heex b/lib/link_shortener_web/templates/layout/_user_menu.html.heex deleted file mode 100644 index f281cfc..0000000 --- a/lib/link_shortener_web/templates/layout/_user_menu.html.heex +++ /dev/null @@ -1,10 +0,0 @@ - diff --git a/lib/link_shortener_web/templates/layout/app.html.heex b/lib/link_shortener_web/templates/layout/app.html.heex deleted file mode 100644 index 169aed9..0000000 --- a/lib/link_shortener_web/templates/layout/app.html.heex +++ /dev/null @@ -1,5 +0,0 @@ -
- - - <%= @inner_content %> -
diff --git a/lib/link_shortener_web/templates/layout/live.html.heex b/lib/link_shortener_web/templates/layout/live.html.heex deleted file mode 100644 index a29d604..0000000 --- a/lib/link_shortener_web/templates/layout/live.html.heex +++ /dev/null @@ -1,11 +0,0 @@ -
- - - - - <%= @inner_content %> -
diff --git a/lib/link_shortener_web/templates/layout/root.html.heex b/lib/link_shortener_web/templates/layout/root.html.heex deleted file mode 100644 index 30c492f..0000000 --- a/lib/link_shortener_web/templates/layout/root.html.heex +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - <%= live_title_tag assigns[:page_title] || "LinkShortener", suffix: " · Phoenix Framework" %> - - - - -
-
- - -
-
- <%= @inner_content %> - - diff --git a/lib/link_shortener_web/templates/page/index.html.heex b/lib/link_shortener_web/templates/page/index.html.heex deleted file mode 100644 index 6f6e8cc..0000000 --- a/lib/link_shortener_web/templates/page/index.html.heex +++ /dev/null @@ -1,4 +0,0 @@ -
-

Usage

-

Go to a url like: "/u/{shorten name}".

-
diff --git a/lib/link_shortener_web/templates/user_confirmation/edit.html.heex b/lib/link_shortener_web/templates/user_confirmation/edit.html.heex deleted file mode 100644 index e9bf443..0000000 --- a/lib/link_shortener_web/templates/user_confirmation/edit.html.heex +++ /dev/null @@ -1,12 +0,0 @@ -

Confirm account

- -<.form let={_f} for={:user} action={Routes.user_confirmation_path(@conn, :update, @token)}> -
- <%= submit "Confirm my account" %> -
- - -

- <%= link "Register", to: Routes.user_registration_path(@conn, :new) %> | - <%= link "Log in", to: Routes.user_session_path(@conn, :new) %> -

diff --git a/lib/link_shortener_web/templates/user_confirmation/new.html.heex b/lib/link_shortener_web/templates/user_confirmation/new.html.heex deleted file mode 100644 index 4d9bee3..0000000 --- a/lib/link_shortener_web/templates/user_confirmation/new.html.heex +++ /dev/null @@ -1,15 +0,0 @@ -

Resend confirmation instructions

- -<.form let={f} for={:user} action={Routes.user_confirmation_path(@conn, :create)}> - <%= label f, :email %> - <%= email_input f, :email, required: true %> - -
- <%= submit "Resend confirmation instructions" %> -
- - -

- <%= link "Register", to: Routes.user_registration_path(@conn, :new) %> | - <%= link "Log in", to: Routes.user_session_path(@conn, :new) %> -

diff --git a/lib/link_shortener_web/templates/user_registration/new.html.heex b/lib/link_shortener_web/templates/user_registration/new.html.heex deleted file mode 100644 index fac2f16..0000000 --- a/lib/link_shortener_web/templates/user_registration/new.html.heex +++ /dev/null @@ -1,26 +0,0 @@ -

Register

- -<.form let={f} for={@changeset} action={Routes.user_registration_path(@conn, :create)}> - <%= if @changeset.action do %> -
-

Oops, something went wrong! Please check the errors below.

-
- <% end %> - - <%= label f, :email %> - <%= email_input f, :email, required: true %> - <%= error_tag f, :email %> - - <%= label f, :password %> - <%= password_input f, :password, required: true %> - <%= error_tag f, :password %> - -
- <%= submit "Register" %> -
- - -

- <%= link "Log in", to: Routes.user_session_path(@conn, :new) %> | - <%= link "Forgot your password?", to: Routes.user_reset_password_path(@conn, :new) %> -

diff --git a/lib/link_shortener_web/templates/user_reset_password/edit.html.heex b/lib/link_shortener_web/templates/user_reset_password/edit.html.heex deleted file mode 100644 index d8efb4b..0000000 --- a/lib/link_shortener_web/templates/user_reset_password/edit.html.heex +++ /dev/null @@ -1,26 +0,0 @@ -

Reset password

- -<.form let={f} for={@changeset} action={Routes.user_reset_password_path(@conn, :update, @token)}> - <%= if @changeset.action do %> -
-

Oops, something went wrong! Please check the errors below.

-
- <% end %> - - <%= label f, :password, "New password" %> - <%= password_input f, :password, required: true %> - <%= error_tag f, :password %> - - <%= label f, :password_confirmation, "Confirm new password" %> - <%= password_input f, :password_confirmation, required: true %> - <%= error_tag f, :password_confirmation %> - -
- <%= submit "Reset password" %> -
- - -

- <%= link "Register", to: Routes.user_registration_path(@conn, :new) %> | - <%= link "Log in", to: Routes.user_session_path(@conn, :new) %> -

diff --git a/lib/link_shortener_web/templates/user_reset_password/new.html.heex b/lib/link_shortener_web/templates/user_reset_password/new.html.heex deleted file mode 100644 index 126cdba..0000000 --- a/lib/link_shortener_web/templates/user_reset_password/new.html.heex +++ /dev/null @@ -1,15 +0,0 @@ -

Forgot your password?

- -<.form let={f} for={:user} action={Routes.user_reset_password_path(@conn, :create)}> - <%= label f, :email %> - <%= email_input f, :email, required: true %> - -
- <%= submit "Send instructions to reset password" %> -
- - -

- <%= link "Register", to: Routes.user_registration_path(@conn, :new) %> | - <%= link "Log in", to: Routes.user_session_path(@conn, :new) %> -

diff --git a/lib/link_shortener_web/templates/user_session/new.html.heex b/lib/link_shortener_web/templates/user_session/new.html.heex deleted file mode 100644 index 49a7d79..0000000 --- a/lib/link_shortener_web/templates/user_session/new.html.heex +++ /dev/null @@ -1,27 +0,0 @@ -

Log in

- -<.form let={f} for={@conn} action={Routes.user_session_path(@conn, :create)} as={:user}> - <%= if @error_message do %> -
-

<%= @error_message %>

-
- <% end %> - - <%= label f, :email %> - <%= email_input f, :email, required: true %> - - <%= label f, :password %> - <%= password_input f, :password, required: true %> - - <%= label f, :remember_me, "Keep me logged in for 60 days" %> - <%= checkbox f, :remember_me %> - -
- <%= submit "Log in" %> -
- - -

- <%= link "Register", to: Routes.user_registration_path(@conn, :new) %> | - <%= link "Forgot your password?", to: Routes.user_reset_password_path(@conn, :new) %> -

diff --git a/lib/link_shortener_web/templates/user_settings/edit.html.heex b/lib/link_shortener_web/templates/user_settings/edit.html.heex deleted file mode 100644 index 9863bc5..0000000 --- a/lib/link_shortener_web/templates/user_settings/edit.html.heex +++ /dev/null @@ -1,53 +0,0 @@ -

Settings

- -

Change email

- -<.form let={f} for={@email_changeset} action={Routes.user_settings_path(@conn, :update)} id="update_email"> - <%= if @email_changeset.action do %> -
-

Oops, something went wrong! Please check the errors below.

-
- <% end %> - - <%= hidden_input f, :action, name: "action", value: "update_email" %> - - <%= label f, :email %> - <%= email_input f, :email, required: true %> - <%= error_tag f, :email %> - - <%= label f, :current_password, for: "current_password_for_email" %> - <%= password_input f, :current_password, required: true, name: "current_password", id: "current_password_for_email" %> - <%= error_tag f, :current_password %> - -
- <%= submit "Change email" %> -
- - -

Change password

- -<.form let={f} for={@password_changeset} action={Routes.user_settings_path(@conn, :update)} id="update_password"> - <%= if @password_changeset.action do %> -
-

Oops, something went wrong! Please check the errors below.

-
- <% end %> - - <%= hidden_input f, :action, name: "action", value: "update_password" %> - - <%= label f, :password, "New password" %> - <%= password_input f, :password, required: true %> - <%= error_tag f, :password %> - - <%= label f, :password_confirmation, "Confirm new password" %> - <%= password_input f, :password_confirmation, required: true %> - <%= error_tag f, :password_confirmation %> - - <%= label f, :current_password, for: "current_password_for_password" %> - <%= password_input f, :current_password, required: true, name: "current_password", id: "current_password_for_password" %> - <%= error_tag f, :current_password %> - -
- <%= submit "Change password" %> -
- diff --git a/lib/link_shortener_web/views/api/v1/link_view.ex b/lib/link_shortener_web/views/api/v1/link_view.ex deleted file mode 100644 index 3998d6d..0000000 --- a/lib/link_shortener_web/views/api/v1/link_view.ex +++ /dev/null @@ -1,21 +0,0 @@ -defmodule LinkShortenerWeb.Api.V1.LinkView do - use LinkShortenerWeb, :view - alias LinkShortenerWeb.Api.V1.LinkView - - def render("index.json", %{links: links}) do - %{data: render_many(links, LinkView, "link.json")} - end - - def render("show.json", %{link: link}) do - %{data: render_one(link, LinkView, "link.json")} - end - - def render("link.json", %{link: link}) do - %{ - id: link.id, - name: link.name, - url: link.url, - shorten: link.shorten - } - end -end diff --git a/lib/link_shortener_web/views/api/v1/user_view.ex b/lib/link_shortener_web/views/api/v1/user_view.ex deleted file mode 100644 index dafa1f7..0000000 --- a/lib/link_shortener_web/views/api/v1/user_view.ex +++ /dev/null @@ -1,12 +0,0 @@ -defmodule LinkShortenerWeb.Api.V1.UserView do - use LinkShortenerWeb, :view - - alias LinkShortenerWeb.Api.V1.UserView - - def render("user.json", %{user: user, token: token}) do - %{ - email: user.email, - token: token - } - end -end diff --git a/lib/link_shortener_web/views/changeset_view.ex b/lib/link_shortener_web/views/changeset_view.ex deleted file mode 100644 index 594018b..0000000 --- a/lib/link_shortener_web/views/changeset_view.ex +++ /dev/null @@ -1,19 +0,0 @@ -defmodule LinkShortenerWeb.ChangesetView do - use LinkShortenerWeb, :view - - @doc """ - Traverses and translates changeset errors. - - See `Ecto.Changeset.traverse_errors/2` and - `LinkShortenerWeb.ErrorHelpers.translate_error/1` for more details. - """ - def translate_errors(changeset) do - Ecto.Changeset.traverse_errors(changeset, &translate_error/1) - end - - def render("error.json", %{changeset: changeset}) do - # When encoded, the changeset returns its errors - # as a JSON object. So we just pass it forward. - %{errors: translate_errors(changeset)} - end -end diff --git a/lib/link_shortener_web/views/error_helpers.ex b/lib/link_shortener_web/views/error_helpers.ex deleted file mode 100644 index bb0337b..0000000 --- a/lib/link_shortener_web/views/error_helpers.ex +++ /dev/null @@ -1,47 +0,0 @@ -defmodule LinkShortenerWeb.ErrorHelpers do - @moduledoc """ - Conveniences for translating and building error messages. - """ - - use Phoenix.HTML - - @doc """ - Generates tag for inlined form input errors. - """ - def error_tag(form, field) do - Enum.map(Keyword.get_values(form.errors, field), fn error -> - content_tag(:span, translate_error(error), - class: "invalid-feedback", - phx_feedback_for: input_name(form, field) - ) - end) - end - - @doc """ - Translates an error message using gettext. - """ - def translate_error({msg, opts}) do - # When using gettext, we typically pass the strings we want - # to translate as a static argument: - # - # # Translate "is invalid" in the "errors" domain - # dgettext("errors", "is invalid") - # - # # Translate the number of files with plural rules - # dngettext("errors", "1 file", "%{count} files", count) - # - # Because the error messages we show in our forms and APIs - # are defined inside Ecto, we need to translate them dynamically. - # This requires us to call the Gettext module passing our gettext - # backend as first argument. - # - # Note we use the "errors" domain, which means translations - # should be written to the errors.po file. The :count option is - # set by Ecto and indicates we should also apply plural rules. - if count = opts[:count] do - Gettext.dngettext(LinkShortenerWeb.Gettext, "errors", msg, msg, count, opts) - else - Gettext.dgettext(LinkShortenerWeb.Gettext, "errors", msg, opts) - end - end -end diff --git a/lib/link_shortener_web/views/error_view.ex b/lib/link_shortener_web/views/error_view.ex deleted file mode 100644 index ad5129c..0000000 --- a/lib/link_shortener_web/views/error_view.ex +++ /dev/null @@ -1,16 +0,0 @@ -defmodule LinkShortenerWeb.ErrorView do - use LinkShortenerWeb, :view - - # If you want to customize a particular status code - # for a certain format, you may uncomment below. - # def render("500.html", _assigns) do - # "Internal Server Error" - # end - - # By default, Phoenix returns the status message from - # the template name. For example, "404.html" becomes - # "Not Found". - def template_not_found(template, _assigns) do - Phoenix.Controller.status_message_from_template(template) - end -end diff --git a/lib/link_shortener_web/views/layout_view.ex b/lib/link_shortener_web/views/layout_view.ex deleted file mode 100644 index 7627e68..0000000 --- a/lib/link_shortener_web/views/layout_view.ex +++ /dev/null @@ -1,7 +0,0 @@ -defmodule LinkShortenerWeb.LayoutView do - use LinkShortenerWeb, :view - - # Phoenix LiveDashboard is available only in development by default, - # so we instruct Elixir to not warn if the dashboard route is missing. - @compile {:no_warn_undefined, {Routes, :live_dashboard_path, 2}} -end diff --git a/lib/link_shortener_web/views/page_view.ex b/lib/link_shortener_web/views/page_view.ex deleted file mode 100644 index 12f8ee7..0000000 --- a/lib/link_shortener_web/views/page_view.ex +++ /dev/null @@ -1,3 +0,0 @@ -defmodule LinkShortenerWeb.PageView do - use LinkShortenerWeb, :view -end diff --git a/lib/link_shortener_web/views/user_confirmation_view.ex b/lib/link_shortener_web/views/user_confirmation_view.ex deleted file mode 100644 index c6b6d11..0000000 --- a/lib/link_shortener_web/views/user_confirmation_view.ex +++ /dev/null @@ -1,3 +0,0 @@ -defmodule LinkShortenerWeb.UserConfirmationView do - use LinkShortenerWeb, :view -end diff --git a/lib/link_shortener_web/views/user_registration_view.ex b/lib/link_shortener_web/views/user_registration_view.ex deleted file mode 100644 index 6057bf5..0000000 --- a/lib/link_shortener_web/views/user_registration_view.ex +++ /dev/null @@ -1,3 +0,0 @@ -defmodule LinkShortenerWeb.UserRegistrationView do - use LinkShortenerWeb, :view -end diff --git a/lib/link_shortener_web/views/user_reset_password_view.ex b/lib/link_shortener_web/views/user_reset_password_view.ex deleted file mode 100644 index 7b039ce..0000000 --- a/lib/link_shortener_web/views/user_reset_password_view.ex +++ /dev/null @@ -1,3 +0,0 @@ -defmodule LinkShortenerWeb.UserResetPasswordView do - use LinkShortenerWeb, :view -end diff --git a/lib/link_shortener_web/views/user_session_view.ex b/lib/link_shortener_web/views/user_session_view.ex deleted file mode 100644 index ad802fe..0000000 --- a/lib/link_shortener_web/views/user_session_view.ex +++ /dev/null @@ -1,3 +0,0 @@ -defmodule LinkShortenerWeb.UserSessionView do - use LinkShortenerWeb, :view -end diff --git a/lib/link_shortener_web/views/user_settings_view.ex b/lib/link_shortener_web/views/user_settings_view.ex deleted file mode 100644 index 2d699fd..0000000 --- a/lib/link_shortener_web/views/user_settings_view.ex +++ /dev/null @@ -1,3 +0,0 @@ -defmodule LinkShortenerWeb.UserSettingsView do - use LinkShortenerWeb, :view -end diff --git a/mix.exs b/mix.exs index b8b9cb0..9fecbb6 100644 --- a/mix.exs +++ b/mix.exs @@ -5,9 +5,8 @@ defmodule LinkShortener.MixProject do [ app: :link_shortener, version: "0.3.2", - elixir: "~> 1.12", + elixir: "~> 1.14", elixirc_paths: elixirc_paths(Mix.env()), - compilers: [] ++ Mix.compilers(), start_permanent: Mix.env() == :prod, aliases: aliases(), deps: deps() @@ -33,26 +32,33 @@ defmodule LinkShortener.MixProject do # Type `mix help deps` for examples and options. defp deps do [ - {:bcrypt_elixir, "~> 3.0"}, - {:phoenix, "~> 1.6.15"}, - {:phoenix_ecto, "~> 4.4"}, - {:ecto_sql, "~> 3.6"}, + {:phoenix, "~> 1.7.14"}, + {:phoenix_ecto, "~> 4.5"}, + {:ecto_sql, "~> 3.10"}, {:postgrex, ">= 0.0.0"}, - {:phoenix_html, "~> 3.0"}, + {:phoenix_html, "~> 4.1"}, {:phoenix_live_reload, "~> 1.2", only: :dev}, - {:phoenix_live_view, "~> 0.17.5"}, + # TODO bump on release to {:phoenix_live_view, "~> 1.0.0"}, + {:phoenix_live_view, "~> 1.0.0-rc.1", override: true}, {:floki, ">= 0.30.0", only: :test}, - {:phoenix_live_dashboard, "~> 0.6"}, - {:esbuild, "~> 0.4", runtime: Mix.env() == :dev}, - {:swoosh, "~> 1.3"}, - {:telemetry_metrics, "~> 0.6"}, + {:phoenix_live_dashboard, "~> 0.8.3"}, + {:esbuild, "~> 0.8", runtime: Mix.env() == :dev}, + {:tailwind, "~> 0.2", runtime: Mix.env() == :dev}, + {:heroicons, + github: "tailwindlabs/heroicons", + tag: "v2.1.1", + sparse: "optimized", + app: false, + compile: false, + depth: 1}, + {:swoosh, "~> 1.5"}, + {:finch, "~> 0.13"}, + {:telemetry_metrics, "~> 1.0"}, {:telemetry_poller, "~> 1.0"}, - {:gettext, "~> 0.18"}, + {:gettext, "~> 0.20"}, {:jason, "~> 1.2"}, - {:plug_cowboy, "~> 2.5"}, - {:guardian, "~> 1.0"}, - {:comeonin, "~> 5.3"}, - {:poison, "~> 5.0"}, + {:dns_cluster, "~> 0.1.1"}, + {:bandit, "~> 1.5"} ] end @@ -64,11 +70,17 @@ defmodule LinkShortener.MixProject do # See the documentation for `Mix` for more info on aliases. defp aliases do [ - setup: ["deps.get", "ecto.setup"], + setup: ["deps.get", "ecto.setup", "assets.setup", "assets.build"], "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], "ecto.reset": ["ecto.drop", "ecto.setup"], test: ["ecto.create --quiet", "ecto.migrate --quiet", "test"], - "assets.deploy": ["esbuild default --minify", "phx.digest"] + "assets.setup": ["tailwind.install --if-missing", "esbuild.install --if-missing"], + "assets.build": ["tailwind link_shortener", "esbuild link_shortener"], + "assets.deploy": [ + "tailwind link_shortener --minify", + "esbuild link_shortener --minify", + "phx.digest" + ] ] end end diff --git a/mix.lock b/mix.lock index cad7105..03e2ceb 100644 --- a/mix.lock +++ b/mix.lock @@ -1,41 +1,41 @@ %{ - "bcrypt_elixir": {:hex, :bcrypt_elixir, "3.0.1", "9be815469e6bfefec40fa74658ecbbe6897acfb57614df1416eeccd4903f602c", [:make, :mix], [{:comeonin, "~> 5.3", [hex: :comeonin, repo: "hexpm", optional: false]}, {:elixir_make, "~> 0.6", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "486bb95efb645d1efc6794c1ddd776a186a9a713abf06f45708a6ce324fb96cf"}, - "castore": {:hex, :castore, "1.0.3", "7130ba6d24c8424014194676d608cb989f62ef8039efd50ff4b3f33286d06db8", [:mix], [], "hexpm", "680ab01ef5d15b161ed6a95449fac5c6b8f60055677a8e79acf01b27baa4390b"}, - "comeonin": {:hex, :comeonin, "5.3.3", "2c564dac95a35650e9b6acfe6d2952083d8a08e4a89b93a481acb552b325892e", [:mix], [], "hexpm", "3e38c9c2cb080828116597ca8807bb482618a315bfafd98c90bc22a821cc84df"}, - "cowboy": {:hex, :cowboy, "2.10.0", "ff9ffeff91dae4ae270dd975642997afe2a1179d94b1887863e43f681a203e26", [:make, :rebar3], [{:cowlib, "2.12.1", [hex: :cowlib, repo: "hexpm", optional: false]}, {:ranch, "1.8.0", [hex: :ranch, repo: "hexpm", optional: false]}], "hexpm", "3afdccb7183cc6f143cb14d3cf51fa00e53db9ec80cdcd525482f5e99bc41d6b"}, - "cowboy_telemetry": {:hex, :cowboy_telemetry, "0.4.0", "f239f68b588efa7707abce16a84d0d2acf3a0f50571f8bb7f56a15865aae820c", [:rebar3], [{:cowboy, "~> 2.7", [hex: :cowboy, repo: "hexpm", optional: false]}, {:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "7d98bac1ee4565d31b62d59f8823dfd8356a169e7fcbb83831b8a5397404c9de"}, - "cowlib": {:hex, :cowlib, "2.12.1", "a9fa9a625f1d2025fe6b462cb865881329b5caff8f1854d1cbc9f9533f00e1e1", [:make, :rebar3], [], "hexpm", "163b73f6367a7341b33c794c4e88e7dbfe6498ac42dcd69ef44c5bc5507c8db0"}, - "db_connection": {:hex, :db_connection, "2.5.0", "bb6d4f30d35ded97b29fe80d8bd6f928a1912ca1ff110831edcd238a1973652c", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "c92d5ba26cd69ead1ff7582dbb860adeedfff39774105a4f1c92cbb654b55aa2"}, + "bandit": {:hex, :bandit, "1.5.7", "6856b1e1df4f2b0cb3df1377eab7891bec2da6a7fd69dc78594ad3e152363a50", [:mix], [{:hpax, "~> 1.0.0", [hex: :hpax, repo: "hexpm", optional: false]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:thousand_island, "~> 1.0", [hex: :thousand_island, repo: "hexpm", optional: false]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "f2dd92ae87d2cbea2fa9aa1652db157b6cba6c405cb44d4f6dd87abba41371cd"}, + "castore": {:hex, :castore, "1.0.8", "dedcf20ea746694647f883590b82d9e96014057aff1d44d03ec90f36a5c0dc6e", [:mix], [], "hexpm", "0b2b66d2ee742cb1d9cb8c8be3b43c3a70ee8651f37b75a8b982e036752983f1"}, + "db_connection": {:hex, :db_connection, "2.7.0", "b99faa9291bb09892c7da373bb82cba59aefa9b36300f6145c5f201c7adf48ec", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "dcf08f31b2701f857dfc787fbad78223d61a32204f217f15e881dd93e4bdd3ff"}, "decimal": {:hex, :decimal, "2.1.1", "5611dca5d4b2c3dd497dec8f68751f1f1a54755e8ed2a966c2633cf885973ad6", [:mix], [], "hexpm", "53cfe5f497ed0e7771ae1a475575603d77425099ba5faef9394932b35020ffcc"}, - "ecto": {:hex, :ecto, "3.10.2", "6b887160281a61aa16843e47735b8a266caa437f80588c3ab80a8a960e6abe37", [:mix], [{:decimal, "~> 1.6 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "6a895778f0d7648a4b34b486af59a1c8009041fbdf2b17f1ac215eb829c60235"}, - "ecto_sql": {:hex, :ecto_sql, "3.10.1", "6ea6b3036a0b0ca94c2a02613fd9f742614b5cfe494c41af2e6571bb034dd94c", [:mix], [{:db_connection, "~> 2.5 or ~> 2.4.1", [hex: :db_connection, repo: "hexpm", optional: false]}, {:ecto, "~> 3.10.0", [hex: :ecto, repo: "hexpm", optional: false]}, {:myxql, "~> 0.6.0", [hex: :myxql, repo: "hexpm", optional: true]}, {:postgrex, "~> 0.16.0 or ~> 0.17.0 or ~> 1.0", [hex: :postgrex, repo: "hexpm", optional: true]}, {:tds, "~> 2.1.1 or ~> 2.2", [hex: :tds, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "f6a25bdbbd695f12c8171eaff0851fa4c8e72eec1e98c7364402dda9ce11c56b"}, - "elixir_make": {:hex, :elixir_make, "0.7.7", "7128c60c2476019ed978210c245badf08b03dbec4f24d05790ef791da11aa17c", [:mix], [{:castore, "~> 0.1 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}], "hexpm", "5bc19fff950fad52bbe5f211b12db9ec82c6b34a9647da0c2224b8b8464c7e6c"}, - "esbuild": {:hex, :esbuild, "0.7.1", "fa0947e8c3c3c2f86c9bf7e791a0a385007ccd42b86885e8e893bdb6631f5169", [:mix], [{:castore, ">= 0.0.0", [hex: :castore, repo: "hexpm", optional: false]}], "hexpm", "66661cdf70b1378ee4dc16573fcee67750b59761b2605a0207c267ab9d19f13c"}, - "expo": {:hex, :expo, "0.4.1", "1c61d18a5df197dfda38861673d392e642649a9cef7694d2f97a587b2cfb319b", [:mix], [], "hexpm", "2ff7ba7a798c8c543c12550fa0e2cbc81b95d4974c65855d8d15ba7b37a1ce47"}, - "file_system": {:hex, :file_system, "0.2.10", "fb082005a9cd1711c05b5248710f8826b02d7d1784e7c3451f9c1231d4fc162d", [:mix], [], "hexpm", "41195edbfb562a593726eda3b3e8b103a309b733ad25f3d642ba49696bf715dc"}, - "floki": {:hex, :floki, "0.34.3", "5e2dcaec5d7c228ce5b1d3501502e308b2d79eb655e4191751a1fe491c37feac", [:mix], [], "hexpm", "9577440eea5b97924b4bf3c7ea55f7b8b6dce589f9b28b096cc294a8dc342341"}, - "gettext": {:hex, :gettext, "0.22.3", "c8273e78db4a0bb6fba7e9f0fd881112f349a3117f7f7c598fa18c66c888e524", [:mix], [{:expo, "~> 0.4.0", [hex: :expo, repo: "hexpm", optional: false]}], "hexpm", "935f23447713954a6866f1bb28c3a878c4c011e802bcd68a726f5e558e4b64bd"}, - "guardian": {:hex, :guardian, "1.2.1", "bdc8dd3dbf0fb7216cb6f91c11831faa1a64d39cdaed9a611e37f2413e584983", [:mix], [{:jose, "~> 1.8", [hex: :jose, repo: "hexpm", optional: false]}, {:phoenix, "~> 1.3", [hex: :phoenix, repo: "hexpm", optional: true]}, {:plug, "~> 1.3.3 or ~> 1.4", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "723fc404edfb7bd5cba4cd83329b352037f102aa97468f44e58ac7f47c136a98"}, - "jason": {:hex, :jason, "1.4.0", "e855647bc964a44e2f67df589ccf49105ae039d4179db7f6271dfd3843dc27e6", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "79a3791085b2a0f743ca04cec0f7be26443738779d09302e01318f97bdb82121"}, - "jose": {:hex, :jose, "1.11.6", "613fda82552128aa6fb804682e3a616f4bc15565a048dabd05b1ebd5827ed965", [:mix, :rebar3], [], "hexpm", "6275cb75504f9c1e60eeacb771adfeee4905a9e182103aa59b53fed651ff9738"}, - "mime": {:hex, :mime, "2.0.5", "dc34c8efd439abe6ae0343edbb8556f4d63f178594894720607772a041b04b02", [:mix], [], "hexpm", "da0d64a365c45bc9935cc5c8a7fc5e49a0e0f9932a761c55d6c52b142780a05c"}, - "phoenix": {:hex, :phoenix, "1.6.16", "e5bdd18c7a06da5852a25c7befb72246de4ddc289182285f8685a40b7b5f5451", [:mix], [{:castore, ">= 0.0.0", [hex: :castore, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix_pubsub, "~> 2.0", [hex: :phoenix_pubsub, repo: "hexpm", optional: false]}, {:phoenix_view, "~> 1.0 or ~> 2.0", [hex: :phoenix_view, repo: "hexpm", optional: false]}, {:plug, "~> 1.10", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.2", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:plug_crypto, "~> 1.2", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "e15989ff34f670a96b95ef6d1d25bad0d9c50df5df40b671d8f4a669e050ac39"}, - "phoenix_ecto": {:hex, :phoenix_ecto, "4.4.2", "b21bd01fdeffcfe2fab49e4942aa938b6d3e89e93a480d4aee58085560a0bc0d", [:mix], [{:ecto, "~> 3.5", [hex: :ecto, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 2.14.2 or ~> 3.0", [hex: :phoenix_html, repo: "hexpm", optional: true]}, {:plug, "~> 1.9", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm", "70242edd4601d50b69273b057ecf7b684644c19ee750989fd555625ae4ce8f5d"}, - "phoenix_html": {:hex, :phoenix_html, "3.3.1", "4788757e804a30baac6b3fc9695bf5562465dd3f1da8eb8460ad5b404d9a2178", [:mix], [{:plug, "~> 1.5", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "bed1906edd4906a15fd7b412b85b05e521e1f67c9a85418c55999277e553d0d3"}, - "phoenix_live_dashboard": {:hex, :phoenix_live_dashboard, "0.6.5", "1495bb014be12c9a9252eca04b9af54246f6b5c1e4cd1f30210cd00ec540cf8e", [:mix], [{:ecto, "~> 3.6.2 or ~> 3.7", [hex: :ecto, repo: "hexpm", optional: true]}, {:ecto_mysql_extras, "~> 0.3", [hex: :ecto_mysql_extras, repo: "hexpm", optional: true]}, {:ecto_psql_extras, "~> 0.7", [hex: :ecto_psql_extras, repo: "hexpm", optional: true]}, {:mime, "~> 1.6 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:phoenix_live_view, "~> 0.17.7", [hex: :phoenix_live_view, repo: "hexpm", optional: false]}, {:telemetry_metrics, "~> 0.6.0", [hex: :telemetry_metrics, repo: "hexpm", optional: false]}], "hexpm", "ef4fa50dd78364409039c99cf6f98ab5209b4c5f8796c17f4db118324f0db852"}, - "phoenix_live_reload": {:hex, :phoenix_live_reload, "1.4.1", "2aff698f5e47369decde4357ba91fc9c37c6487a512b41732818f2204a8ef1d3", [:mix], [{:file_system, "~> 0.2.1 or ~> 0.3", [hex: :file_system, repo: "hexpm", optional: false]}, {:phoenix, "~> 1.4", [hex: :phoenix, repo: "hexpm", optional: false]}], "hexpm", "9bffb834e7ddf08467fe54ae58b5785507aaba6255568ae22b4d46e2bb3615ab"}, - "phoenix_live_view": {:hex, :phoenix_live_view, "0.17.14", "5ec615d4d61bf9d4755f158bd6c80372b715533fe6d6219e12d74fb5eedbeac1", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix, "~> 1.6.0 or ~> 1.7.0", [hex: :phoenix, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 3.1", [hex: :phoenix_html, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.2 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "afeb6ba43ce329a6f7fc1c9acdfc6d3039995345f025febb7f409a92f6faebd3"}, + "dns_cluster": {:hex, :dns_cluster, "0.1.3", "0bc20a2c88ed6cc494f2964075c359f8c2d00e1bf25518a6a6c7fd277c9b0c66", [:mix], [], "hexpm", "46cb7c4a1b3e52c7ad4cbe33ca5079fbde4840dedeafca2baf77996c2da1bc33"}, + "ecto": {:hex, :ecto, "3.12.1", "626765f7066589de6fa09e0876a253ff60c3d00870dd3a1cd696e2ba67bfceea", [:mix], [{:decimal, "~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "df0045ab9d87be947228e05a8d153f3e06e0d05ab10c3b3cc557d2f7243d1940"}, + "ecto_sql": {:hex, :ecto_sql, "3.12.0", "73cea17edfa54bde76ee8561b30d29ea08f630959685006d9c6e7d1e59113b7d", [:mix], [{:db_connection, "~> 2.5 or ~> 2.4.1", [hex: :db_connection, repo: "hexpm", optional: false]}, {:ecto, "~> 3.12", [hex: :ecto, repo: "hexpm", optional: false]}, {:myxql, "~> 0.7", [hex: :myxql, repo: "hexpm", optional: true]}, {:postgrex, "~> 0.19 or ~> 1.0", [hex: :postgrex, repo: "hexpm", optional: true]}, {:tds, "~> 2.1.1 or ~> 2.2", [hex: :tds, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "dc9e4d206f274f3947e96142a8fdc5f69a2a6a9abb4649ef5c882323b6d512f0"}, + "esbuild": {:hex, :esbuild, "0.8.1", "0cbf919f0eccb136d2eeef0df49c4acf55336de864e63594adcea3814f3edf41", [:mix], [{:castore, ">= 0.0.0", [hex: :castore, repo: "hexpm", optional: false]}, {:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "25fc876a67c13cb0a776e7b5d7974851556baeda2085296c14ab48555ea7560f"}, + "expo": {:hex, :expo, "1.0.0", "647639267e088717232f4d4451526e7a9de31a3402af7fcbda09b27e9a10395a", [:mix], [], "hexpm", "18d2093d344d97678e8a331ca0391e85d29816f9664a25653fd7e6166827827c"}, + "file_system": {:hex, :file_system, "1.0.1", "79e8ceaddb0416f8b8cd02a0127bdbababe7bf4a23d2a395b983c1f8b3f73edd", [:mix], [], "hexpm", "4414d1f38863ddf9120720cd976fce5bdde8e91d8283353f0e31850fa89feb9e"}, + "finch": {:hex, :finch, "0.18.0", "944ac7d34d0bd2ac8998f79f7a811b21d87d911e77a786bc5810adb75632ada4", [:mix], [{:castore, "~> 0.1 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: false]}, {:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.3", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 0.2.6 or ~> 1.0", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "69f5045b042e531e53edc2574f15e25e735b522c37e2ddb766e15b979e03aa65"}, + "floki": {:hex, :floki, "0.36.2", "a7da0193538c93f937714a6704369711998a51a6164a222d710ebd54020aa7a3", [:mix], [], "hexpm", "a8766c0bc92f074e5cb36c4f9961982eda84c5d2b8e979ca67f5c268ec8ed580"}, + "gettext": {:hex, :gettext, "0.26.1", "38e14ea5dcf962d1fc9f361b63ea07c0ce715a8ef1f9e82d3dfb8e67e0416715", [:mix], [{:expo, "~> 0.5.1 or ~> 1.0", [hex: :expo, repo: "hexpm", optional: false]}], "hexpm", "01ce56f188b9dc28780a52783d6529ad2bc7124f9744e571e1ee4ea88bf08734"}, + "heroicons": {:git, "https://github.com/tailwindlabs/heroicons.git", "88ab3a0d790e6a47404cba02800a6b25d2afae50", [tag: "v2.1.1", sparse: "optimized"]}, + "hpax": {:hex, :hpax, "1.0.0", "28dcf54509fe2152a3d040e4e3df5b265dcb6cb532029ecbacf4ce52caea3fd2", [:mix], [], "hexpm", "7f1314731d711e2ca5fdc7fd361296593fc2542570b3105595bb0bc6d0fad601"}, + "jason": {:hex, :jason, "1.4.4", "b9226785a9aa77b6857ca22832cffa5d5011a667207eb2a0ad56adb5db443b8a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "c5eb0cab91f094599f94d55bc63409236a8ec69a21a67814529e8d5f6cc90b3b"}, + "mime": {:hex, :mime, "2.0.6", "8f18486773d9b15f95f4f4f1e39b710045fa1de891fada4516559967276e4dc2", [:mix], [], "hexpm", "c9945363a6b26d747389aac3643f8e0e09d30499a138ad64fe8fd1d13d9b153e"}, + "mint": {:hex, :mint, "1.6.2", "af6d97a4051eee4f05b5500671d47c3a67dac7386045d87a904126fd4bbcea2e", [:mix], [{:castore, "~> 0.1.0 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:hpax, "~> 0.1.1 or ~> 0.2.0 or ~> 1.0", [hex: :hpax, repo: "hexpm", optional: false]}], "hexpm", "5ee441dffc1892f1ae59127f74afe8fd82fda6587794278d924e4d90ea3d63f9"}, + "nimble_options": {:hex, :nimble_options, "1.1.1", "e3a492d54d85fc3fd7c5baf411d9d2852922f66e69476317787a7b2bb000a61b", [:mix], [], "hexpm", "821b2470ca9442c4b6984882fe9bb0389371b8ddec4d45a9504f00a66f650b44"}, + "nimble_pool": {:hex, :nimble_pool, "1.1.0", "bf9c29fbdcba3564a8b800d1eeb5a3c58f36e1e11d7b7fb2e084a643f645f06b", [:mix], [], "hexpm", "af2e4e6b34197db81f7aad230c1118eac993acc0dae6bc83bac0126d4ae0813a"}, + "phoenix": {:hex, :phoenix, "1.7.14", "a7d0b3f1bc95987044ddada111e77bd7f75646a08518942c72a8440278ae7825", [:mix], [{:castore, ">= 0.0.0", [hex: :castore, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix_pubsub, "~> 2.1", [hex: :phoenix_pubsub, repo: "hexpm", optional: false]}, {:phoenix_template, "~> 1.0", [hex: :phoenix_template, repo: "hexpm", optional: false]}, {:phoenix_view, "~> 2.0", [hex: :phoenix_view, repo: "hexpm", optional: true]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.7", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:plug_crypto, "~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:websock_adapter, "~> 0.5.3", [hex: :websock_adapter, repo: "hexpm", optional: false]}], "hexpm", "c7859bc56cc5dfef19ecfc240775dae358cbaa530231118a9e014df392ace61a"}, + "phoenix_ecto": {:hex, :phoenix_ecto, "4.6.2", "3b83b24ab5a2eb071a20372f740d7118767c272db386831b2e77638c4dcc606d", [:mix], [{:ecto, "~> 3.5", [hex: :ecto, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 2.14.2 or ~> 3.0 or ~> 4.1", [hex: :phoenix_html, repo: "hexpm", optional: true]}, {:plug, "~> 1.9", [hex: :plug, repo: "hexpm", optional: false]}, {:postgrex, "~> 0.16 or ~> 1.0", [hex: :postgrex, repo: "hexpm", optional: true]}], "hexpm", "3f94d025f59de86be00f5f8c5dd7b5965a3298458d21ab1c328488be3b5fcd59"}, + "phoenix_html": {:hex, :phoenix_html, "4.1.1", "4c064fd3873d12ebb1388425a8f2a19348cef56e7289e1998e2d2fa758aa982e", [:mix], [], "hexpm", "f2f2df5a72bc9a2f510b21497fd7d2b86d932ec0598f0210fed4114adc546c6f"}, + "phoenix_live_dashboard": {:hex, :phoenix_live_dashboard, "0.8.4", "4508e481f791ce62ec6a096e13b061387158cbeefacca68c6c1928e1305e23ed", [:mix], [{:ecto, "~> 3.6.2 or ~> 3.7", [hex: :ecto, repo: "hexpm", optional: true]}, {:ecto_mysql_extras, "~> 0.5", [hex: :ecto_mysql_extras, repo: "hexpm", optional: true]}, {:ecto_psql_extras, "~> 0.7", [hex: :ecto_psql_extras, repo: "hexpm", optional: true]}, {:ecto_sqlite3_extras, "~> 1.1.7 or ~> 1.2.0", [hex: :ecto_sqlite3_extras, repo: "hexpm", optional: true]}, {:mime, "~> 1.6 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:phoenix_live_view, "~> 0.19 or ~> 1.0", [hex: :phoenix_live_view, repo: "hexpm", optional: false]}, {:telemetry_metrics, "~> 0.6 or ~> 1.0", [hex: :telemetry_metrics, repo: "hexpm", optional: false]}], "hexpm", "2984aae96994fbc5c61795a73b8fb58153b41ff934019cfb522343d2d3817d59"}, + "phoenix_live_reload": {:hex, :phoenix_live_reload, "1.5.3", "f2161c207fda0e4fb55165f650f7f8db23f02b29e3bff00ff7ef161d6ac1f09d", [:mix], [{:file_system, "~> 0.3 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:phoenix, "~> 1.4", [hex: :phoenix, repo: "hexpm", optional: false]}], "hexpm", "b4ec9cd73cb01ff1bd1cac92e045d13e7030330b74164297d1aee3907b54803c"}, + "phoenix_live_view": {:hex, :phoenix_live_view, "1.0.0-rc.6", "47d2669995ea326e5c71f5c1bc9177109cebf211385c638faa7b5862a401e516", [:mix], [{:floki, "~> 0.36", [hex: :floki, repo: "hexpm", optional: true]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix, "~> 1.6.15 or ~> 1.7.0", [hex: :phoenix, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 3.3 or ~> 4.0 or ~> 4.1", [hex: :phoenix_html, repo: "hexpm", optional: false]}, {:phoenix_template, "~> 1.0", [hex: :phoenix_template, repo: "hexpm", optional: false]}, {:phoenix_view, "~> 2.0", [hex: :phoenix_view, repo: "hexpm", optional: true]}, {:plug, "~> 1.15", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.2 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "e56e4f1642a0b20edc2488cab30e5439595e0d8b5b259f76ef98b1c4e2e5b527"}, "phoenix_pubsub": {:hex, :phoenix_pubsub, "2.1.3", "3168d78ba41835aecad272d5e8cd51aa87a7ac9eb836eabc42f6e57538e3731d", [:mix], [], "hexpm", "bba06bc1dcfd8cb086759f0edc94a8ba2bc8896d5331a1e2c2902bf8e36ee502"}, - "phoenix_template": {:hex, :phoenix_template, "1.0.1", "85f79e3ad1b0180abb43f9725973e3b8c2c3354a87245f91431eec60553ed3ef", [:mix], [{:phoenix_html, "~> 2.14.2 or ~> 3.0", [hex: :phoenix_html, repo: "hexpm", optional: true]}], "hexpm", "157dc078f6226334c91cb32c1865bf3911686f8bcd6bcff86736f6253e6993ee"}, - "phoenix_view": {:hex, :phoenix_view, "2.0.2", "6bd4d2fd595ef80d33b439ede6a19326b78f0f1d8d62b9a318e3d9c1af351098", [:mix], [{:phoenix_html, "~> 2.14.2 or ~> 3.0", [hex: :phoenix_html, repo: "hexpm", optional: true]}, {:phoenix_template, "~> 1.0", [hex: :phoenix_template, repo: "hexpm", optional: false]}], "hexpm", "a929e7230ea5c7ee0e149ffcf44ce7cf7f4b6d2bfe1752dd7c084cdff152d36f"}, - "plug": {:hex, :plug, "1.14.2", "cff7d4ec45b4ae176a227acd94a7ab536d9b37b942c8e8fa6dfc0fff98ff4d80", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "842fc50187e13cf4ac3b253d47d9474ed6c296a8732752835ce4a86acdf68d13"}, - "plug_cowboy": {:hex, :plug_cowboy, "2.6.1", "9a3bbfceeb65eff5f39dab529e5cd79137ac36e913c02067dba3963a26efe9b2", [:mix], [{:cowboy, "~> 2.7", [hex: :cowboy, repo: "hexpm", optional: false]}, {:cowboy_telemetry, "~> 0.3", [hex: :cowboy_telemetry, repo: "hexpm", optional: false]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm", "de36e1a21f451a18b790f37765db198075c25875c64834bcc82d90b309eb6613"}, - "plug_crypto": {:hex, :plug_crypto, "1.2.5", "918772575e48e81e455818229bf719d4ab4181fcbf7f85b68a35620f78d89ced", [:mix], [], "hexpm", "26549a1d6345e2172eb1c233866756ae44a9609bd33ee6f99147ab3fd87fd842"}, - "poison": {:hex, :poison, "5.0.0", "d2b54589ab4157bbb82ec2050757779bfed724463a544b6e20d79855a9e43b24", [:mix], [{:decimal, "~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "11dc6117c501b80c62a7594f941d043982a1bd05a1184280c0d9166eb4d8d3fc"}, - "postgrex": {:hex, :postgrex, "0.17.1", "01c29fd1205940ee55f7addb8f1dc25618ca63a8817e56fac4f6846fc2cddcbe", [:mix], [{:db_connection, "~> 2.1", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "14b057b488e73be2beee508fb1955d8db90d6485c6466428fe9ccf1d6692a555"}, - "ranch": {:hex, :ranch, "1.8.0", "8c7a100a139fd57f17327b6413e4167ac559fbc04ca7448e9be9057311597a1d", [:make, :rebar3], [], "hexpm", "49fbcfd3682fab1f5d109351b61257676da1a2fdbe295904176d5e521a2ddfe5"}, - "swoosh": {:hex, :swoosh, "1.11.2", "39dd1e44f75bc03a34366d5f830599d248de2b9caaf05704dc76c0507a58c6a1", [:mix], [{:cowboy, "~> 1.1 or ~> 2.4", [hex: :cowboy, repo: "hexpm", optional: true]}, {:ex_aws, "~> 2.1", [hex: :ex_aws, repo: "hexpm", optional: true]}, {:finch, "~> 0.6", [hex: :finch, repo: "hexpm", optional: true]}, {:gen_smtp, "~> 0.13 or ~> 1.0", [hex: :gen_smtp, repo: "hexpm", optional: true]}, {:hackney, "~> 1.9", [hex: :hackney, repo: "hexpm", optional: true]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mail, "~> 0.2", [hex: :mail, repo: "hexpm", optional: true]}, {:mime, "~> 1.1 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_cowboy, ">= 1.0.0", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.2 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "4c43f4591503e7d5bf028314af8ac7c06d1c4d340aa23faeefabfa2543fa726e"}, + "phoenix_template": {:hex, :phoenix_template, "1.0.4", "e2092c132f3b5e5b2d49c96695342eb36d0ed514c5b252a77048d5969330d639", [:mix], [{:phoenix_html, "~> 2.14.2 or ~> 3.0 or ~> 4.0", [hex: :phoenix_html, repo: "hexpm", optional: true]}], "hexpm", "2c0c81f0e5c6753faf5cca2f229c9709919aba34fab866d3bc05060c9c444206"}, + "plug": {:hex, :plug, "1.16.1", "40c74619c12f82736d2214557dedec2e9762029b2438d6d175c5074c933edc9d", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "a13ff6b9006b03d7e33874945b2755253841b238c34071ed85b0e86057f8cddc"}, + "plug_crypto": {:hex, :plug_crypto, "2.1.0", "f44309c2b06d249c27c8d3f65cfe08158ade08418cf540fd4f72d4d6863abb7b", [:mix], [], "hexpm", "131216a4b030b8f8ce0f26038bc4421ae60e4bb95c5cf5395e1421437824c4fa"}, + "postgrex": {:hex, :postgrex, "0.19.1", "73b498508b69aded53907fe48a1fee811be34cc720e69ef4ccd568c8715495ea", [:mix], [{:db_connection, "~> 2.1", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "8bac7885a18f381e091ec6caf41bda7bb8c77912bb0e9285212829afe5d8a8f8"}, + "swoosh": {:hex, :swoosh, "1.16.12", "cbb24ad512f2f7f24c7a469661c188a00a8c2cd64e0ab54acd1520f132092dfd", [:mix], [{:bandit, ">= 1.0.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:cowboy, "~> 1.1 or ~> 2.4", [hex: :cowboy, repo: "hexpm", optional: true]}, {:ex_aws, "~> 2.1", [hex: :ex_aws, repo: "hexpm", optional: true]}, {:finch, "~> 0.6", [hex: :finch, repo: "hexpm", optional: true]}, {:gen_smtp, "~> 0.13 or ~> 1.0", [hex: :gen_smtp, repo: "hexpm", optional: true]}, {:hackney, "~> 1.9", [hex: :hackney, repo: "hexpm", optional: true]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mail, "~> 0.2", [hex: :mail, repo: "hexpm", optional: true]}, {:mime, "~> 1.1 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mua, "~> 0.2.3", [hex: :mua, repo: "hexpm", optional: true]}, {:multipart, "~> 0.4", [hex: :multipart, repo: "hexpm", optional: true]}, {:plug, "~> 1.9", [hex: :plug, repo: "hexpm", optional: true]}, {:plug_cowboy, ">= 1.0.0", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:req, "~> 0.5 or ~> 1.0", [hex: :req, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.2 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "0e262df1ae510d59eeaaa3db42189a2aa1b3746f73771eb2616fc3f7ee63cc20"}, + "tailwind": {:hex, :tailwind, "0.2.3", "277f08145d407de49650d0a4685dc062174bdd1ae7731c5f1da86163a24dfcdb", [:mix], [{:castore, ">= 0.0.0", [hex: :castore, repo: "hexpm", optional: false]}], "hexpm", "8e45e7a34a676a7747d04f7913a96c770c85e6be810a1d7f91e713d3a3655b5d"}, "telemetry": {:hex, :telemetry, "1.2.1", "68fdfe8d8f05a8428483a97d7aab2f268aaff24b49e0f599faa091f1d4e7f61c", [:rebar3], [], "hexpm", "dad9ce9d8effc621708f99eac538ef1cbe05d6a874dd741de2e689c47feafed5"}, - "telemetry_metrics": {:hex, :telemetry_metrics, "0.6.1", "315d9163a1d4660aedc3fee73f33f1d355dcc76c5c3ab3d59e76e3edf80eef1f", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "7be9e0871c41732c233be71e4be11b96e56177bf15dde64a8ac9ce72ac9834c6"}, - "telemetry_poller": {:hex, :telemetry_poller, "1.0.0", "db91bb424e07f2bb6e73926fcafbfcbcb295f0193e0a00e825e589a0a47e8453", [:rebar3], [{:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "b3a24eafd66c3f42da30fc3ca7dda1e9d546c12250a2d60d7b81d264fbec4f6e"}, + "telemetry_metrics": {:hex, :telemetry_metrics, "1.0.0", "29f5f84991ca98b8eb02fc208b2e6de7c95f8bb2294ef244a176675adc7775df", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "f23713b3847286a534e005126d4c959ebcca68ae9582118ce436b521d1d47d5d"}, + "telemetry_poller": {:hex, :telemetry_poller, "1.1.0", "58fa7c216257291caaf8d05678c8d01bd45f4bdbc1286838a28c4bb62ef32999", [:rebar3], [{:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "9eb9d9cbfd81cbd7cdd24682f8711b6e2b691289a0de6826e58452f28c103c8f"}, + "thousand_island": {:hex, :thousand_island, "1.3.5", "6022b6338f1635b3d32406ff98d68b843ba73b3aa95cfc27154223244f3a6ca5", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "2be6954916fdfe4756af3239fb6b6d75d0b8063b5df03ba76fd8a4c87849e180"}, + "websock": {:hex, :websock, "0.5.3", "2f69a6ebe810328555b6fe5c831a851f485e303a7c8ce6c5f675abeb20ebdadc", [:mix], [], "hexpm", "6105453d7fac22c712ad66fab1d45abdf049868f253cf719b625151460b8b453"}, + "websock_adapter": {:hex, :websock_adapter, "0.5.7", "65fa74042530064ef0570b75b43f5c49bb8b235d6515671b3d250022cb8a1f9e", [:mix], [{:bandit, ">= 0.6.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.6", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "d0f478ee64deddfec64b800673fd6e0c8888b079d9f3444dd96d2a98383bdbd1"}, } diff --git a/priv/gettext/errors.pot b/priv/gettext/errors.pot index 39a220b..eef2de2 100644 --- a/priv/gettext/errors.pot +++ b/priv/gettext/errors.pot @@ -7,7 +7,6 @@ ## Run `mix gettext.extract` to bring this file up to ## date. Leave `msgstr`s empty as changing them here has no ## effect: edit them in PO (`.po`) files instead. - ## From Ecto.Changeset.cast/4 msgid "can't be blank" msgstr "" @@ -48,13 +47,23 @@ msgid "are still associated with this entry" msgstr "" ## From Ecto.Changeset.validate_length/3 +msgid "should have %{count} item(s)" +msgid_plural "should have %{count} item(s)" +msgstr[0] "" +msgstr[1] "" + msgid "should be %{count} character(s)" msgid_plural "should be %{count} character(s)" msgstr[0] "" msgstr[1] "" -msgid "should have %{count} item(s)" -msgid_plural "should have %{count} item(s)" +msgid "should be %{count} byte(s)" +msgid_plural "should be %{count} byte(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should have at least %{count} item(s)" +msgid_plural "should have at least %{count} item(s)" msgstr[0] "" msgstr[1] "" @@ -63,8 +72,13 @@ msgid_plural "should be at least %{count} character(s)" msgstr[0] "" msgstr[1] "" -msgid "should have at least %{count} item(s)" -msgid_plural "should have at least %{count} item(s)" +msgid "should be at least %{count} byte(s)" +msgid_plural "should be at least %{count} byte(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should have at most %{count} item(s)" +msgid_plural "should have at most %{count} item(s)" msgstr[0] "" msgstr[1] "" @@ -73,8 +87,8 @@ msgid_plural "should be at most %{count} character(s)" msgstr[0] "" msgstr[1] "" -msgid "should have at most %{count} item(s)" -msgid_plural "should have at most %{count} item(s)" +msgid "should be at most %{count} byte(s)" +msgid_plural "should be at most %{count} byte(s)" msgstr[0] "" msgstr[1] "" diff --git a/priv/repo/migrations/20230808170900_create_users_auth_tables.exs b/priv/repo/migrations/20230808170900_create_users_auth_tables.exs deleted file mode 100644 index 3220b9e..0000000 --- a/priv/repo/migrations/20230808170900_create_users_auth_tables.exs +++ /dev/null @@ -1,27 +0,0 @@ -defmodule LinkShortener.Repo.Migrations.CreateUsersAuthTables do - use Ecto.Migration - - def change do - execute "CREATE EXTENSION IF NOT EXISTS citext", "" - - create table(:users) do - add :email, :citext, null: false - add :hashed_password, :string, null: false - add :confirmed_at, :naive_datetime - timestamps() - end - - create unique_index(:users, [:email]) - - create table(:users_tokens) do - add :user_id, references(:users, on_delete: :delete_all), null: false - add :token, :binary, null: false - add :context, :string, null: false - add :sent_to, :string - timestamps(updated_at: false) - end - - create index(:users_tokens, [:user_id]) - create unique_index(:users_tokens, [:context, :token]) - end -end diff --git a/priv/static/favicon.ico b/priv/static/favicon.ico index 73de524..7f372bf 100644 Binary files a/priv/static/favicon.ico and b/priv/static/favicon.ico differ diff --git a/priv/static/images/logo.svg b/priv/static/images/logo.svg new file mode 100644 index 0000000..9f26bab --- /dev/null +++ b/priv/static/images/logo.svg @@ -0,0 +1,6 @@ + diff --git a/test/link_shortener/accounts/accounts_test.exs b/test/link_shortener/accounts/accounts_test.exs deleted file mode 100644 index 04c2fe4..0000000 --- a/test/link_shortener/accounts/accounts_test.exs +++ /dev/null @@ -1,508 +0,0 @@ -defmodule LinkShortener.AccountsTest do - use LinkShortener.DataCase - - alias LinkShortener.Accounts - - import LinkShortener.AccountsFixtures - alias LinkShortener.Accounts.{User, UserToken} - - describe "get_user_by_email/1" do - test "does not return the user if the email does not exist" do - refute Accounts.get_user_by_email("unknown@example.com") - end - - test "returns the user if the email exists" do - %{id: id} = user = user_fixture() - assert %User{id: ^id} = Accounts.get_user_by_email(user.email) - end - end - - describe "get_user_by_email_and_password/2" do - test "does not return the user if the email does not exist" do - refute Accounts.get_user_by_email_and_password("unknown@example.com", "hello world!") - end - - test "does not return the user if the password is not valid" do - user = user_fixture() - refute Accounts.get_user_by_email_and_password(user.email, "invalid") - end - - test "returns the user if the email and password are valid" do - %{id: id} = user = user_fixture() - - assert %User{id: ^id} = - Accounts.get_user_by_email_and_password(user.email, valid_user_password()) - end - end - - describe "get_user!/1" do - test "raises if id is invalid" do - assert_raise Ecto.NoResultsError, fn -> - Accounts.get_user!(-1) - end - end - - test "returns the user with the given id" do - %{id: id} = user = user_fixture() - assert %User{id: ^id} = Accounts.get_user!(user.id) - end - end - - describe "register_user/1" do - test "requires email and password to be set" do - {:error, changeset} = Accounts.register_user(%{}) - - assert %{ - password: ["can't be blank"], - email: ["can't be blank"] - } = errors_on(changeset) - end - - test "validates email and password when given" do - {:error, changeset} = Accounts.register_user(%{email: "not valid", password: "not valid"}) - - assert %{ - email: ["must have the @ sign and no spaces"], - password: ["should be at least 12 character(s)"] - } = errors_on(changeset) - end - - test "validates maximum values for email and password for security" do - too_long = String.duplicate("db", 100) - {:error, changeset} = Accounts.register_user(%{email: too_long, password: too_long}) - assert "should be at most 160 character(s)" in errors_on(changeset).email - assert "should be at most 72 character(s)" in errors_on(changeset).password - end - - test "validates email uniqueness" do - %{email: email} = user_fixture() - {:error, changeset} = Accounts.register_user(%{email: email}) - assert "has already been taken" in errors_on(changeset).email - - # Now try with the upper cased email too, to check that email case is ignored. - {:error, changeset} = Accounts.register_user(%{email: String.upcase(email)}) - assert "has already been taken" in errors_on(changeset).email - end - - test "registers users with a hashed password" do - email = unique_user_email() - {:ok, user} = Accounts.register_user(valid_user_attributes(email: email)) - assert user.email == email - assert is_binary(user.hashed_password) - assert is_nil(user.confirmed_at) - assert is_nil(user.password) - end - end - - describe "change_user_registration/2" do - test "returns a changeset" do - assert %Ecto.Changeset{} = changeset = Accounts.change_user_registration(%User{}) - assert changeset.required == [:password, :email] - end - - test "allows fields to be set" do - email = unique_user_email() - password = valid_user_password() - - changeset = - Accounts.change_user_registration( - %User{}, - valid_user_attributes(email: email, password: password) - ) - - assert changeset.valid? - assert get_change(changeset, :email) == email - assert get_change(changeset, :password) == password - assert is_nil(get_change(changeset, :hashed_password)) - end - end - - describe "change_user_email/2" do - test "returns a user changeset" do - assert %Ecto.Changeset{} = changeset = Accounts.change_user_email(%User{}) - assert changeset.required == [:email] - end - end - - describe "apply_user_email/3" do - setup do - %{user: user_fixture()} - end - - test "requires email to change", %{user: user} do - {:error, changeset} = Accounts.apply_user_email(user, valid_user_password(), %{}) - assert %{email: ["did not change"]} = errors_on(changeset) - end - - test "validates email", %{user: user} do - {:error, changeset} = - Accounts.apply_user_email(user, valid_user_password(), %{email: "not valid"}) - - assert %{email: ["must have the @ sign and no spaces"]} = errors_on(changeset) - end - - test "validates maximum value for email for security", %{user: user} do - too_long = String.duplicate("db", 100) - - {:error, changeset} = - Accounts.apply_user_email(user, valid_user_password(), %{email: too_long}) - - assert "should be at most 160 character(s)" in errors_on(changeset).email - end - - test "validates email uniqueness", %{user: user} do - %{email: email} = user_fixture() - - {:error, changeset} = - Accounts.apply_user_email(user, valid_user_password(), %{email: email}) - - assert "has already been taken" in errors_on(changeset).email - end - - test "validates current password", %{user: user} do - {:error, changeset} = - Accounts.apply_user_email(user, "invalid", %{email: unique_user_email()}) - - assert %{current_password: ["is not valid"]} = errors_on(changeset) - end - - test "applies the email without persisting it", %{user: user} do - email = unique_user_email() - {:ok, user} = Accounts.apply_user_email(user, valid_user_password(), %{email: email}) - assert user.email == email - assert Accounts.get_user!(user.id).email != email - end - end - - describe "deliver_update_email_instructions/3" do - setup do - %{user: user_fixture()} - end - - test "sends token through notification", %{user: user} do - token = - extract_user_token(fn url -> - Accounts.deliver_update_email_instructions(user, "current@example.com", url) - end) - - {:ok, token} = Base.url_decode64(token, padding: false) - assert user_token = Repo.get_by(UserToken, token: :crypto.hash(:sha256, token)) - assert user_token.user_id == user.id - assert user_token.sent_to == user.email - assert user_token.context == "change:current@example.com" - end - end - - describe "update_user_email/2" do - setup do - user = user_fixture() - email = unique_user_email() - - token = - extract_user_token(fn url -> - Accounts.deliver_update_email_instructions(%{user | email: email}, user.email, url) - end) - - %{user: user, token: token, email: email} - end - - test "updates the email with a valid token", %{user: user, token: token, email: email} do - assert Accounts.update_user_email(user, token) == :ok - changed_user = Repo.get!(User, user.id) - assert changed_user.email != user.email - assert changed_user.email == email - assert changed_user.confirmed_at - assert changed_user.confirmed_at != user.confirmed_at - refute Repo.get_by(UserToken, user_id: user.id) - end - - test "does not update email with invalid token", %{user: user} do - assert Accounts.update_user_email(user, "oops") == :error - assert Repo.get!(User, user.id).email == user.email - assert Repo.get_by(UserToken, user_id: user.id) - end - - test "does not update email if user email changed", %{user: user, token: token} do - assert Accounts.update_user_email(%{user | email: "current@example.com"}, token) == :error - assert Repo.get!(User, user.id).email == user.email - assert Repo.get_by(UserToken, user_id: user.id) - end - - test "does not update email if token expired", %{user: user, token: token} do - {1, nil} = Repo.update_all(UserToken, set: [inserted_at: ~N[2020-01-01 00:00:00]]) - assert Accounts.update_user_email(user, token) == :error - assert Repo.get!(User, user.id).email == user.email - assert Repo.get_by(UserToken, user_id: user.id) - end - end - - describe "change_user_password/2" do - test "returns a user changeset" do - assert %Ecto.Changeset{} = changeset = Accounts.change_user_password(%User{}) - assert changeset.required == [:password] - end - - test "allows fields to be set" do - changeset = - Accounts.change_user_password(%User{}, %{ - "password" => "new valid password" - }) - - assert changeset.valid? - assert get_change(changeset, :password) == "new valid password" - assert is_nil(get_change(changeset, :hashed_password)) - end - end - - describe "update_user_password/3" do - setup do - %{user: user_fixture()} - end - - test "validates password", %{user: user} do - {:error, changeset} = - Accounts.update_user_password(user, valid_user_password(), %{ - password: "not valid", - password_confirmation: "another" - }) - - assert %{ - password: ["should be at least 12 character(s)"], - password_confirmation: ["does not match password"] - } = errors_on(changeset) - end - - test "validates maximum values for password for security", %{user: user} do - too_long = String.duplicate("db", 100) - - {:error, changeset} = - Accounts.update_user_password(user, valid_user_password(), %{password: too_long}) - - assert "should be at most 72 character(s)" in errors_on(changeset).password - end - - test "validates current password", %{user: user} do - {:error, changeset} = - Accounts.update_user_password(user, "invalid", %{password: valid_user_password()}) - - assert %{current_password: ["is not valid"]} = errors_on(changeset) - end - - test "updates the password", %{user: user} do - {:ok, user} = - Accounts.update_user_password(user, valid_user_password(), %{ - password: "new valid password" - }) - - assert is_nil(user.password) - assert Accounts.get_user_by_email_and_password(user.email, "new valid password") - end - - test "deletes all tokens for the given user", %{user: user} do - _ = Accounts.generate_user_session_token(user) - - {:ok, _} = - Accounts.update_user_password(user, valid_user_password(), %{ - password: "new valid password" - }) - - refute Repo.get_by(UserToken, user_id: user.id) - end - end - - describe "generate_user_session_token/1" do - setup do - %{user: user_fixture()} - end - - test "generates a token", %{user: user} do - token = Accounts.generate_user_session_token(user) - assert user_token = Repo.get_by(UserToken, token: token) - assert user_token.context == "session" - - # Creating the same token for another user should fail - assert_raise Ecto.ConstraintError, fn -> - Repo.insert!(%UserToken{ - token: user_token.token, - user_id: user_fixture().id, - context: "session" - }) - end - end - end - - describe "get_user_by_session_token/1" do - setup do - user = user_fixture() - token = Accounts.generate_user_session_token(user) - %{user: user, token: token} - end - - test "returns user by token", %{user: user, token: token} do - assert session_user = Accounts.get_user_by_session_token(token) - assert session_user.id == user.id - end - - test "does not return user for invalid token" do - refute Accounts.get_user_by_session_token("oops") - end - - test "does not return user for expired token", %{token: token} do - {1, nil} = Repo.update_all(UserToken, set: [inserted_at: ~N[2020-01-01 00:00:00]]) - refute Accounts.get_user_by_session_token(token) - end - end - - describe "delete_session_token/1" do - test "deletes the token" do - user = user_fixture() - token = Accounts.generate_user_session_token(user) - assert Accounts.delete_session_token(token) == :ok - refute Accounts.get_user_by_session_token(token) - end - end - - describe "deliver_user_confirmation_instructions/2" do - setup do - %{user: user_fixture()} - end - - test "sends token through notification", %{user: user} do - token = - extract_user_token(fn url -> - Accounts.deliver_user_confirmation_instructions(user, url) - end) - - {:ok, token} = Base.url_decode64(token, padding: false) - assert user_token = Repo.get_by(UserToken, token: :crypto.hash(:sha256, token)) - assert user_token.user_id == user.id - assert user_token.sent_to == user.email - assert user_token.context == "confirm" - end - end - - describe "confirm_user/1" do - setup do - user = user_fixture() - - token = - extract_user_token(fn url -> - Accounts.deliver_user_confirmation_instructions(user, url) - end) - - %{user: user, token: token} - end - - test "confirms the email with a valid token", %{user: user, token: token} do - assert {:ok, confirmed_user} = Accounts.confirm_user(token) - assert confirmed_user.confirmed_at - assert confirmed_user.confirmed_at != user.confirmed_at - assert Repo.get!(User, user.id).confirmed_at - refute Repo.get_by(UserToken, user_id: user.id) - end - - test "does not confirm with invalid token", %{user: user} do - assert Accounts.confirm_user("oops") == :error - refute Repo.get!(User, user.id).confirmed_at - assert Repo.get_by(UserToken, user_id: user.id) - end - - test "does not confirm email if token expired", %{user: user, token: token} do - {1, nil} = Repo.update_all(UserToken, set: [inserted_at: ~N[2020-01-01 00:00:00]]) - assert Accounts.confirm_user(token) == :error - refute Repo.get!(User, user.id).confirmed_at - assert Repo.get_by(UserToken, user_id: user.id) - end - end - - describe "deliver_user_reset_password_instructions/2" do - setup do - %{user: user_fixture()} - end - - test "sends token through notification", %{user: user} do - token = - extract_user_token(fn url -> - Accounts.deliver_user_reset_password_instructions(user, url) - end) - - {:ok, token} = Base.url_decode64(token, padding: false) - assert user_token = Repo.get_by(UserToken, token: :crypto.hash(:sha256, token)) - assert user_token.user_id == user.id - assert user_token.sent_to == user.email - assert user_token.context == "reset_password" - end - end - - describe "get_user_by_reset_password_token/1" do - setup do - user = user_fixture() - - token = - extract_user_token(fn url -> - Accounts.deliver_user_reset_password_instructions(user, url) - end) - - %{user: user, token: token} - end - - test "returns the user with valid token", %{user: %{id: id}, token: token} do - assert %User{id: ^id} = Accounts.get_user_by_reset_password_token(token) - assert Repo.get_by(UserToken, user_id: id) - end - - test "does not return the user with invalid token", %{user: user} do - refute Accounts.get_user_by_reset_password_token("oops") - assert Repo.get_by(UserToken, user_id: user.id) - end - - test "does not return the user if token expired", %{user: user, token: token} do - {1, nil} = Repo.update_all(UserToken, set: [inserted_at: ~N[2020-01-01 00:00:00]]) - refute Accounts.get_user_by_reset_password_token(token) - assert Repo.get_by(UserToken, user_id: user.id) - end - end - - describe "reset_user_password/2" do - setup do - %{user: user_fixture()} - end - - test "validates password", %{user: user} do - {:error, changeset} = - Accounts.reset_user_password(user, %{ - password: "not valid", - password_confirmation: "another" - }) - - assert %{ - password: ["should be at least 12 character(s)"], - password_confirmation: ["does not match password"] - } = errors_on(changeset) - end - - test "validates maximum values for password for security", %{user: user} do - too_long = String.duplicate("db", 100) - {:error, changeset} = Accounts.reset_user_password(user, %{password: too_long}) - assert "should be at most 72 character(s)" in errors_on(changeset).password - end - - test "updates the password", %{user: user} do - {:ok, updated_user} = Accounts.reset_user_password(user, %{password: "new valid password"}) - assert is_nil(updated_user.password) - assert Accounts.get_user_by_email_and_password(user.email, "new valid password") - end - - test "deletes all tokens for the given user", %{user: user} do - _ = Accounts.generate_user_session_token(user) - {:ok, _} = Accounts.reset_user_password(user, %{password: "new valid password"}) - refute Repo.get_by(UserToken, user_id: user.id) - end - end - - describe "inspect/2" do - test "does not include password" do - refute inspect(%User{password: "123456"}) =~ "password: \"123456\"" - end - end -end diff --git a/test/link_shortener_web/controllers/api/v1/link_controller_test.exs b/test/link_shortener_web/controllers/api/v1/link_controller_test.exs deleted file mode 100644 index f342233..0000000 --- a/test/link_shortener_web/controllers/api/v1/link_controller_test.exs +++ /dev/null @@ -1,109 +0,0 @@ -defmodule LinkShortenerWeb.Api.V1.LinkControllerTest do - use LinkShortenerWeb.ConnCase - - import LinkShortener.LinksFixtures - import LinkShortener.AccountsFixtures - - alias LinkShortener.Links.Link - alias LinkShortener.Links - - @create_attrs %{ - name: "some link name", - url: "https://gitlab.com/KKlochko/link_shortener", - shorten: "git_repo", - } - @update_attrs %{ - name: "some updated link name", - url: "https://gitlab.com/KKlochko/link_shortener2", - shorten: "new_git_repo", - } - @invalid_attrs %{ - name: nil, - url: nil, - shorten: nil, - } - - setup %{conn: conn} do - %{token: token} = create_user_token() - - conn = conn - |> put_req_header("accept", "application/json") - |> put_req_header("authorization", "Bearer #{token}") - - {:ok, conn: conn} - end - - describe "index" do - test "lists all links", %{conn: conn} do - conn = get(conn, Routes.v1_link_path(conn, :index)) - assert json_response(conn, 200)["data"] == [] - end - end - - describe "create link" do - test "renders link when data is valid", %{conn: conn} do - conn = post(conn, Routes.v1_link_path(conn, :create), link: @create_attrs) - assert %{"id" => id} = json_response(conn, 201)["data"] - - conn = get(conn, Routes.v1_link_path(conn, :show, id)) - - assert %{ - "id" => ^id, - "name" => "some link name", - "url" => "https://gitlab.com/KKlochko/link_shortener", - "shorten" => "git_repo", - } = json_response(conn, 200)["data"] - end - - test "renders errors when data is invalid", %{conn: conn} do - conn = post(conn, Routes.v1_link_path(conn, :create), link: @invalid_attrs) - assert json_response(conn, 422)["errors"] != %{} - end - end - - describe "update link" do - setup [:create_link] - - test "renders link when data is valid", %{conn: conn, link: %Link{id: id} = link} do - conn = put(conn, Routes.v1_link_path(conn, :update, link), link: @update_attrs) - assert %{"id" => ^id} = json_response(conn, 200)["data"] - - conn = get(conn, Routes.v1_link_path(conn, :show, id)) - - assert %{ - "id" => ^id, - "name" => "some updated link name", - "url" => "https://gitlab.com/KKlochko/link_shortener2", - "shorten" => "new_git_repo", - } = json_response(conn, 200)["data"] - end - - test "renders errors when data is invalid", %{conn: conn, link: link} do - conn = put(conn, Routes.v1_link_path(conn, :update, link), link: @invalid_attrs) - assert json_response(conn, 422)["errors"] != %{} - end - end - - describe "delete link" do - setup [:create_link] - - test "deletes chosen link", %{conn: conn, link: link} do - conn = delete(conn, Routes.v1_link_path(conn, :delete, link)) - assert response(conn, 204) - - assert_error_sent 404, fn -> - get(conn, Routes.v1_link_path(conn, :show, link)) - end - end - end - - defp create_user_token() do - token = user_token_fixture() - %{token: token} - end - - defp create_link(_) do - link = link_fixture() - %{link: link} - end -end diff --git a/test/link_shortener_web/controllers/api/v1/user_controller_test.exs b/test/link_shortener_web/controllers/api/v1/user_controller_test.exs deleted file mode 100644 index 961cd6e..0000000 --- a/test/link_shortener_web/controllers/api/v1/user_controller_test.exs +++ /dev/null @@ -1,69 +0,0 @@ -defmodule LinkShortenerWeb.Api.V1.UserControllerTest do - use LinkShortenerWeb.ConnCase - - import LinkShortener.AccountsFixtures - - alias LinkShortener.Accounts.User - - @create_attrs %{ - email: "user@mail.com", - password: "some password" - } - - @update_attrs %{ - email: "some updated email", - password: "some updated password" - } - - @invalid_password_attrs %{ - email: "user@mail.com", - password: "" - } - - @invalid_attrs %{ - email: nil, - encrypted_password: nil - } - - setup %{conn: conn} do - {:ok, conn: put_req_header(conn, "accept", "application/json")} - end - - describe "create user with sign up" do - test "renders user when data is valid", %{conn: conn} do - conn = post(conn, Routes.v1_user_path(conn, :create), user: @create_attrs) - assert %{ - "email" => "user@mail.com", - "token" => token - } = json_response(conn, 201) - end - - test "renders errors when data is invalid", %{conn: conn} do - conn = post(conn, Routes.v1_user_path(conn, :create), user: @invalid_attrs) - assert json_response(conn, 422)["errors"] != %{} - end - end - - describe "user sign in" do - setup [:create_user] - - test "renders user when data is valid", %{conn: conn} do - conn = post(conn, Routes.v1_user_path(conn, :signin), @create_attrs) - - assert %{ - "email" => email, - "token" => token, - } = json_response(conn, 201) - end - - test "renders errors when data is invalid", %{conn: conn} do - conn = post(conn, Routes.v1_user_path(conn, :signin), @invalid_password_attrs) - assert "Unauthorized" == json_response(conn, 401) - end - end - - defp create_user(_) do - user = user_fixture(@create_attrs) - %{user: user} - end -end diff --git a/test/link_shortener_web/controllers/error_html_test.exs b/test/link_shortener_web/controllers/error_html_test.exs new file mode 100644 index 0000000..3384106 --- /dev/null +++ b/test/link_shortener_web/controllers/error_html_test.exs @@ -0,0 +1,14 @@ +defmodule LinkShortenerWeb.ErrorHTMLTest do + use LinkShortenerWeb.ConnCase, async: true + + # Bring render_to_string/4 for testing custom views + import Phoenix.Template + + test "renders 404.html" do + assert render_to_string(LinkShortenerWeb.ErrorHTML, "404", "html", []) == "Not Found" + end + + test "renders 500.html" do + assert render_to_string(LinkShortenerWeb.ErrorHTML, "500", "html", []) == "Internal Server Error" + end +end diff --git a/test/link_shortener_web/controllers/error_json_test.exs b/test/link_shortener_web/controllers/error_json_test.exs new file mode 100644 index 0000000..80f1261 --- /dev/null +++ b/test/link_shortener_web/controllers/error_json_test.exs @@ -0,0 +1,12 @@ +defmodule LinkShortenerWeb.ErrorJSONTest do + use LinkShortenerWeb.ConnCase, async: true + + test "renders 404" do + assert LinkShortenerWeb.ErrorJSON.render("404.json", %{}) == %{errors: %{detail: "Not Found"}} + end + + test "renders 500" do + assert LinkShortenerWeb.ErrorJSON.render("500.json", %{}) == + %{errors: %{detail: "Internal Server Error"}} + end +end diff --git a/test/link_shortener_web/controllers/page_controller_test.exs b/test/link_shortener_web/controllers/page_controller_test.exs index a11164b..f6bb1a2 100644 --- a/test/link_shortener_web/controllers/page_controller_test.exs +++ b/test/link_shortener_web/controllers/page_controller_test.exs @@ -2,7 +2,7 @@ defmodule LinkShortenerWeb.PageControllerTest do use LinkShortenerWeb.ConnCase test "GET /", %{conn: conn} do - conn = get(conn, "/") - assert html_response(conn, 200) =~ "Usage" + conn = get(conn, ~p"/") + assert html_response(conn, 200) =~ "Peace of mind from prototype to production" end end diff --git a/test/link_shortener_web/controllers/user_auth_test.exs b/test/link_shortener_web/controllers/user_auth_test.exs deleted file mode 100644 index c20efb3..0000000 --- a/test/link_shortener_web/controllers/user_auth_test.exs +++ /dev/null @@ -1,170 +0,0 @@ -defmodule LinkShortenerWeb.UserAuthTest do - use LinkShortenerWeb.ConnCase, async: true - - alias LinkShortener.Accounts - alias LinkShortenerWeb.UserAuth - import LinkShortener.AccountsFixtures - - @remember_me_cookie "_link_shortener_web_user_remember_me" - - setup %{conn: conn} do - conn = - conn - |> Map.replace!(:secret_key_base, LinkShortenerWeb.Endpoint.config(:secret_key_base)) - |> init_test_session(%{}) - - %{user: user_fixture(), conn: conn} - end - - describe "log_in_user/3" do - test "stores the user token in the session", %{conn: conn, user: user} do - conn = UserAuth.log_in_user(conn, user) - assert token = get_session(conn, :user_token) - assert get_session(conn, :live_socket_id) == "users_sessions:#{Base.url_encode64(token)}" - assert redirected_to(conn) == "/" - assert Accounts.get_user_by_session_token(token) - end - - test "clears everything previously stored in the session", %{conn: conn, user: user} do - conn = conn |> put_session(:to_be_removed, "value") |> UserAuth.log_in_user(user) - refute get_session(conn, :to_be_removed) - end - - test "redirects to the configured path", %{conn: conn, user: user} do - conn = conn |> put_session(:user_return_to, "/hello") |> UserAuth.log_in_user(user) - assert redirected_to(conn) == "/hello" - end - - test "writes a cookie if remember_me is configured", %{conn: conn, user: user} do - conn = conn |> fetch_cookies() |> UserAuth.log_in_user(user, %{"remember_me" => "true"}) - assert get_session(conn, :user_token) == conn.cookies[@remember_me_cookie] - - assert %{value: signed_token, max_age: max_age} = conn.resp_cookies[@remember_me_cookie] - assert signed_token != get_session(conn, :user_token) - assert max_age == 5_184_000 - end - end - - describe "logout_user/1" do - test "erases session and cookies", %{conn: conn, user: user} do - user_token = Accounts.generate_user_session_token(user) - - conn = - conn - |> put_session(:user_token, user_token) - |> put_req_cookie(@remember_me_cookie, user_token) - |> fetch_cookies() - |> UserAuth.log_out_user() - - refute get_session(conn, :user_token) - refute conn.cookies[@remember_me_cookie] - assert %{max_age: 0} = conn.resp_cookies[@remember_me_cookie] - assert redirected_to(conn) == "/" - refute Accounts.get_user_by_session_token(user_token) - end - - test "broadcasts to the given live_socket_id", %{conn: conn} do - live_socket_id = "users_sessions:abcdef-token" - LinkShortenerWeb.Endpoint.subscribe(live_socket_id) - - conn - |> put_session(:live_socket_id, live_socket_id) - |> UserAuth.log_out_user() - - assert_receive %Phoenix.Socket.Broadcast{event: "disconnect", topic: ^live_socket_id} - end - - test "works even if user is already logged out", %{conn: conn} do - conn = conn |> fetch_cookies() |> UserAuth.log_out_user() - refute get_session(conn, :user_token) - assert %{max_age: 0} = conn.resp_cookies[@remember_me_cookie] - assert redirected_to(conn) == "/" - end - end - - describe "fetch_current_user/2" do - test "authenticates user from session", %{conn: conn, user: user} do - user_token = Accounts.generate_user_session_token(user) - conn = conn |> put_session(:user_token, user_token) |> UserAuth.fetch_current_user([]) - assert conn.assigns.current_user.id == user.id - end - - test "authenticates user from cookies", %{conn: conn, user: user} do - logged_in_conn = - conn |> fetch_cookies() |> UserAuth.log_in_user(user, %{"remember_me" => "true"}) - - user_token = logged_in_conn.cookies[@remember_me_cookie] - %{value: signed_token} = logged_in_conn.resp_cookies[@remember_me_cookie] - - conn = - conn - |> put_req_cookie(@remember_me_cookie, signed_token) - |> UserAuth.fetch_current_user([]) - - assert get_session(conn, :user_token) == user_token - assert conn.assigns.current_user.id == user.id - end - - test "does not authenticate if data is missing", %{conn: conn, user: user} do - _ = Accounts.generate_user_session_token(user) - conn = UserAuth.fetch_current_user(conn, []) - refute get_session(conn, :user_token) - refute conn.assigns.current_user - end - end - - describe "redirect_if_user_is_authenticated/2" do - test "redirects if user is authenticated", %{conn: conn, user: user} do - conn = conn |> assign(:current_user, user) |> UserAuth.redirect_if_user_is_authenticated([]) - assert conn.halted - assert redirected_to(conn) == "/" - end - - test "does not redirect if user is not authenticated", %{conn: conn} do - conn = UserAuth.redirect_if_user_is_authenticated(conn, []) - refute conn.halted - refute conn.status - end - end - - describe "require_authenticated_user/2" do - test "redirects if user is not authenticated", %{conn: conn} do - conn = conn |> fetch_flash() |> UserAuth.require_authenticated_user([]) - assert conn.halted - assert redirected_to(conn) == Routes.user_session_path(conn, :new) - assert get_flash(conn, :error) == "You must log in to access this page." - end - - test "stores the path to redirect to on GET", %{conn: conn} do - halted_conn = - %{conn | path_info: ["foo"], query_string: ""} - |> fetch_flash() - |> UserAuth.require_authenticated_user([]) - - assert halted_conn.halted - assert get_session(halted_conn, :user_return_to) == "/foo" - - halted_conn = - %{conn | path_info: ["foo"], query_string: "bar=baz"} - |> fetch_flash() - |> UserAuth.require_authenticated_user([]) - - assert halted_conn.halted - assert get_session(halted_conn, :user_return_to) == "/foo?bar=baz" - - halted_conn = - %{conn | path_info: ["foo"], query_string: "bar", method: "POST"} - |> fetch_flash() - |> UserAuth.require_authenticated_user([]) - - assert halted_conn.halted - refute get_session(halted_conn, :user_return_to) - end - - test "does not redirect if user is authenticated", %{conn: conn, user: user} do - conn = conn |> assign(:current_user, user) |> UserAuth.require_authenticated_user([]) - refute conn.halted - refute conn.status - end - end -end diff --git a/test/link_shortener_web/controllers/user_confirmation_controller_test.exs b/test/link_shortener_web/controllers/user_confirmation_controller_test.exs deleted file mode 100644 index aa2db23..0000000 --- a/test/link_shortener_web/controllers/user_confirmation_controller_test.exs +++ /dev/null @@ -1,105 +0,0 @@ -defmodule LinkShortenerWeb.UserConfirmationControllerTest do - use LinkShortenerWeb.ConnCase, async: true - - alias LinkShortener.Accounts - alias LinkShortener.Repo - import LinkShortener.AccountsFixtures - - setup do - %{user: user_fixture()} - end - - describe "GET /users/confirm" do - test "renders the resend confirmation page", %{conn: conn} do - conn = get(conn, Routes.user_confirmation_path(conn, :new)) - response = html_response(conn, 200) - assert response =~ "

Resend confirmation instructions

" - end - end - - describe "POST /users/confirm" do - @tag :capture_log - test "sends a new confirmation token", %{conn: conn, user: user} do - conn = - post(conn, Routes.user_confirmation_path(conn, :create), %{ - "user" => %{"email" => user.email} - }) - - assert redirected_to(conn) == "/" - assert get_flash(conn, :info) =~ "If your email is in our system" - assert Repo.get_by!(Accounts.UserToken, user_id: user.id).context == "confirm" - end - - test "does not send confirmation token if User is confirmed", %{conn: conn, user: user} do - Repo.update!(Accounts.User.confirm_changeset(user)) - - conn = - post(conn, Routes.user_confirmation_path(conn, :create), %{ - "user" => %{"email" => user.email} - }) - - assert redirected_to(conn) == "/" - assert get_flash(conn, :info) =~ "If your email is in our system" - refute Repo.get_by(Accounts.UserToken, user_id: user.id) - end - - test "does not send confirmation token if email is invalid", %{conn: conn} do - conn = - post(conn, Routes.user_confirmation_path(conn, :create), %{ - "user" => %{"email" => "unknown@example.com"} - }) - - assert redirected_to(conn) == "/" - assert get_flash(conn, :info) =~ "If your email is in our system" - assert Repo.all(Accounts.UserToken) == [] - end - end - - describe "GET /users/confirm/:token" do - test "renders the confirmation page", %{conn: conn} do - conn = get(conn, Routes.user_confirmation_path(conn, :edit, "some-token")) - response = html_response(conn, 200) - assert response =~ "

Confirm account

" - - form_action = Routes.user_confirmation_path(conn, :update, "some-token") - assert response =~ "action=\"#{form_action}\"" - end - end - - describe "POST /users/confirm/:token" do - test "confirms the given token once", %{conn: conn, user: user} do - token = - extract_user_token(fn url -> - Accounts.deliver_user_confirmation_instructions(user, url) - end) - - conn = post(conn, Routes.user_confirmation_path(conn, :update, token)) - assert redirected_to(conn) == "/" - assert get_flash(conn, :info) =~ "User confirmed successfully" - assert Accounts.get_user!(user.id).confirmed_at - refute get_session(conn, :user_token) - assert Repo.all(Accounts.UserToken) == [] - - # When not logged in - conn = post(conn, Routes.user_confirmation_path(conn, :update, token)) - assert redirected_to(conn) == "/" - assert get_flash(conn, :error) =~ "User confirmation link is invalid or it has expired" - - # When logged in - conn = - build_conn() - |> log_in_user(user) - |> post(Routes.user_confirmation_path(conn, :update, token)) - - assert redirected_to(conn) == "/" - refute get_flash(conn, :error) - end - - test "does not confirm email with invalid token", %{conn: conn, user: user} do - conn = post(conn, Routes.user_confirmation_path(conn, :update, "oops")) - assert redirected_to(conn) == "/" - assert get_flash(conn, :error) =~ "User confirmation link is invalid or it has expired" - refute Accounts.get_user!(user.id).confirmed_at - end - end -end diff --git a/test/link_shortener_web/controllers/user_registration_controller_test.exs b/test/link_shortener_web/controllers/user_registration_controller_test.exs deleted file mode 100644 index 5597bcb..0000000 --- a/test/link_shortener_web/controllers/user_registration_controller_test.exs +++ /dev/null @@ -1,54 +0,0 @@ -defmodule LinkShortenerWeb.UserRegistrationControllerTest do - use LinkShortenerWeb.ConnCase, async: true - - import LinkShortener.AccountsFixtures - - describe "GET /users/register" do - test "renders registration page", %{conn: conn} do - conn = get(conn, Routes.user_registration_path(conn, :new)) - response = html_response(conn, 200) - assert response =~ "

Register

" - assert response =~ "Log in" - assert response =~ "Register" - end - - test "redirects if already logged in", %{conn: conn} do - conn = conn |> log_in_user(user_fixture()) |> get(Routes.user_registration_path(conn, :new)) - assert redirected_to(conn) == "/" - end - end - - describe "POST /users/register" do - @tag :capture_log - test "creates account and logs the user in", %{conn: conn} do - email = unique_user_email() - - conn = - post(conn, Routes.user_registration_path(conn, :create), %{ - "user" => valid_user_attributes(email: email) - }) - - assert get_session(conn, :user_token) - assert redirected_to(conn) == "/" - - # Now do a logged in request and assert on the menu - conn = get(conn, "/") - response = html_response(conn, 200) - assert response =~ email - assert response =~ "Settings" - assert response =~ "Log out" - end - - test "render errors for invalid data", %{conn: conn} do - conn = - post(conn, Routes.user_registration_path(conn, :create), %{ - "user" => %{"email" => "with spaces", "password" => "too short"} - }) - - response = html_response(conn, 200) - assert response =~ "

Register

" - assert response =~ "must have the @ sign and no spaces" - assert response =~ "should be at least 12 character" - end - end -end diff --git a/test/link_shortener_web/controllers/user_reset_password_controller_test.exs b/test/link_shortener_web/controllers/user_reset_password_controller_test.exs deleted file mode 100644 index 62058c5..0000000 --- a/test/link_shortener_web/controllers/user_reset_password_controller_test.exs +++ /dev/null @@ -1,113 +0,0 @@ -defmodule LinkShortenerWeb.UserResetPasswordControllerTest do - use LinkShortenerWeb.ConnCase, async: true - - alias LinkShortener.Accounts - alias LinkShortener.Repo - import LinkShortener.AccountsFixtures - - setup do - %{user: user_fixture()} - end - - describe "GET /users/reset_password" do - test "renders the reset password page", %{conn: conn} do - conn = get(conn, Routes.user_reset_password_path(conn, :new)) - response = html_response(conn, 200) - assert response =~ "

Forgot your password?

" - end - end - - describe "POST /users/reset_password" do - @tag :capture_log - test "sends a new reset password token", %{conn: conn, user: user} do - conn = - post(conn, Routes.user_reset_password_path(conn, :create), %{ - "user" => %{"email" => user.email} - }) - - assert redirected_to(conn) == "/" - assert get_flash(conn, :info) =~ "If your email is in our system" - assert Repo.get_by!(Accounts.UserToken, user_id: user.id).context == "reset_password" - end - - test "does not send reset password token if email is invalid", %{conn: conn} do - conn = - post(conn, Routes.user_reset_password_path(conn, :create), %{ - "user" => %{"email" => "unknown@example.com"} - }) - - assert redirected_to(conn) == "/" - assert get_flash(conn, :info) =~ "If your email is in our system" - assert Repo.all(Accounts.UserToken) == [] - end - end - - describe "GET /users/reset_password/:token" do - setup %{user: user} do - token = - extract_user_token(fn url -> - Accounts.deliver_user_reset_password_instructions(user, url) - end) - - %{token: token} - end - - test "renders reset password", %{conn: conn, token: token} do - conn = get(conn, Routes.user_reset_password_path(conn, :edit, token)) - assert html_response(conn, 200) =~ "

Reset password

" - end - - test "does not render reset password with invalid token", %{conn: conn} do - conn = get(conn, Routes.user_reset_password_path(conn, :edit, "oops")) - assert redirected_to(conn) == "/" - assert get_flash(conn, :error) =~ "Reset password link is invalid or it has expired" - end - end - - describe "PUT /users/reset_password/:token" do - setup %{user: user} do - token = - extract_user_token(fn url -> - Accounts.deliver_user_reset_password_instructions(user, url) - end) - - %{token: token} - end - - test "resets password once", %{conn: conn, user: user, token: token} do - conn = - put(conn, Routes.user_reset_password_path(conn, :update, token), %{ - "user" => %{ - "password" => "new valid password", - "password_confirmation" => "new valid password" - } - }) - - assert redirected_to(conn) == Routes.user_session_path(conn, :new) - refute get_session(conn, :user_token) - assert get_flash(conn, :info) =~ "Password reset successfully" - assert Accounts.get_user_by_email_and_password(user.email, "new valid password") - end - - test "does not reset password on invalid data", %{conn: conn, token: token} do - conn = - put(conn, Routes.user_reset_password_path(conn, :update, token), %{ - "user" => %{ - "password" => "too short", - "password_confirmation" => "does not match" - } - }) - - response = html_response(conn, 200) - assert response =~ "

Reset password

" - assert response =~ "should be at least 12 character(s)" - assert response =~ "does not match password" - end - - test "does not reset password with invalid token", %{conn: conn} do - conn = put(conn, Routes.user_reset_password_path(conn, :update, "oops")) - assert redirected_to(conn) == "/" - assert get_flash(conn, :error) =~ "Reset password link is invalid or it has expired" - end - end -end diff --git a/test/link_shortener_web/controllers/user_session_controller_test.exs b/test/link_shortener_web/controllers/user_session_controller_test.exs deleted file mode 100644 index 65a7650..0000000 --- a/test/link_shortener_web/controllers/user_session_controller_test.exs +++ /dev/null @@ -1,98 +0,0 @@ -defmodule LinkShortenerWeb.UserSessionControllerTest do - use LinkShortenerWeb.ConnCase, async: true - - import LinkShortener.AccountsFixtures - - setup do - %{user: user_fixture()} - end - - describe "GET /users/log_in" do - test "renders log in page", %{conn: conn} do - conn = get(conn, Routes.user_session_path(conn, :new)) - response = html_response(conn, 200) - assert response =~ "

Log in

" - assert response =~ "Register" - assert response =~ "Forgot your password?" - end - - test "redirects if already logged in", %{conn: conn, user: user} do - conn = conn |> log_in_user(user) |> get(Routes.user_session_path(conn, :new)) - assert redirected_to(conn) == "/" - end - end - - describe "POST /users/log_in" do - test "logs the user in", %{conn: conn, user: user} do - conn = - post(conn, Routes.user_session_path(conn, :create), %{ - "user" => %{"email" => user.email, "password" => valid_user_password()} - }) - - assert get_session(conn, :user_token) - assert redirected_to(conn) == "/" - - # Now do a logged in request and assert on the menu - conn = get(conn, "/") - response = html_response(conn, 200) - assert response =~ user.email - assert response =~ "Settings" - assert response =~ "Log out" - end - - test "logs the user in with remember me", %{conn: conn, user: user} do - conn = - post(conn, Routes.user_session_path(conn, :create), %{ - "user" => %{ - "email" => user.email, - "password" => valid_user_password(), - "remember_me" => "true" - } - }) - - assert conn.resp_cookies["_link_shortener_web_user_remember_me"] - assert redirected_to(conn) == "/" - end - - test "logs the user in with return to", %{conn: conn, user: user} do - conn = - conn - |> init_test_session(user_return_to: "/foo/bar") - |> post(Routes.user_session_path(conn, :create), %{ - "user" => %{ - "email" => user.email, - "password" => valid_user_password() - } - }) - - assert redirected_to(conn) == "/foo/bar" - end - - test "emits error message with invalid credentials", %{conn: conn, user: user} do - conn = - post(conn, Routes.user_session_path(conn, :create), %{ - "user" => %{"email" => user.email, "password" => "invalid_password"} - }) - - response = html_response(conn, 200) - assert response =~ "

Log in

" - assert response =~ "Invalid email or password" - end - end - - describe "DELETE /users/log_out" do - test "logs the user out", %{conn: conn, user: user} do - conn = conn |> log_in_user(user) |> delete(Routes.user_session_path(conn, :delete)) - assert redirected_to(conn) == "/" - refute get_session(conn, :user_token) - assert get_flash(conn, :info) =~ "Logged out successfully" - end - - test "succeeds even if the user is not logged in", %{conn: conn} do - conn = delete(conn, Routes.user_session_path(conn, :delete)) - assert redirected_to(conn) == "/" - refute get_session(conn, :user_token) - assert get_flash(conn, :info) =~ "Logged out successfully" - end - end -end diff --git a/test/link_shortener_web/controllers/user_settings_controller_test.exs b/test/link_shortener_web/controllers/user_settings_controller_test.exs deleted file mode 100644 index edb6f24..0000000 --- a/test/link_shortener_web/controllers/user_settings_controller_test.exs +++ /dev/null @@ -1,129 +0,0 @@ -defmodule LinkShortenerWeb.UserSettingsControllerTest do - use LinkShortenerWeb.ConnCase, async: true - - alias LinkShortener.Accounts - import LinkShortener.AccountsFixtures - - setup :register_and_log_in_user - - describe "GET /users/settings" do - test "renders settings page", %{conn: conn} do - conn = get(conn, Routes.user_settings_path(conn, :edit)) - response = html_response(conn, 200) - assert response =~ "

Settings

" - end - - test "redirects if user is not logged in" do - conn = build_conn() - conn = get(conn, Routes.user_settings_path(conn, :edit)) - assert redirected_to(conn) == Routes.user_session_path(conn, :new) - end - end - - describe "PUT /users/settings (change password form)" do - test "updates the user password and resets tokens", %{conn: conn, user: user} do - new_password_conn = - put(conn, Routes.user_settings_path(conn, :update), %{ - "action" => "update_password", - "current_password" => valid_user_password(), - "user" => %{ - "password" => "new valid password", - "password_confirmation" => "new valid password" - } - }) - - assert redirected_to(new_password_conn) == Routes.user_settings_path(conn, :edit) - assert get_session(new_password_conn, :user_token) != get_session(conn, :user_token) - assert get_flash(new_password_conn, :info) =~ "Password updated successfully" - assert Accounts.get_user_by_email_and_password(user.email, "new valid password") - end - - test "does not update password on invalid data", %{conn: conn} do - old_password_conn = - put(conn, Routes.user_settings_path(conn, :update), %{ - "action" => "update_password", - "current_password" => "invalid", - "user" => %{ - "password" => "too short", - "password_confirmation" => "does not match" - } - }) - - response = html_response(old_password_conn, 200) - assert response =~ "

Settings

" - assert response =~ "should be at least 12 character(s)" - assert response =~ "does not match password" - assert response =~ "is not valid" - - assert get_session(old_password_conn, :user_token) == get_session(conn, :user_token) - end - end - - describe "PUT /users/settings (change email form)" do - @tag :capture_log - test "updates the user email", %{conn: conn, user: user} do - conn = - put(conn, Routes.user_settings_path(conn, :update), %{ - "action" => "update_email", - "current_password" => valid_user_password(), - "user" => %{"email" => unique_user_email()} - }) - - assert redirected_to(conn) == Routes.user_settings_path(conn, :edit) - assert get_flash(conn, :info) =~ "A link to confirm your email" - assert Accounts.get_user_by_email(user.email) - end - - test "does not update email on invalid data", %{conn: conn} do - conn = - put(conn, Routes.user_settings_path(conn, :update), %{ - "action" => "update_email", - "current_password" => "invalid", - "user" => %{"email" => "with spaces"} - }) - - response = html_response(conn, 200) - assert response =~ "

Settings

" - assert response =~ "must have the @ sign and no spaces" - assert response =~ "is not valid" - end - end - - describe "GET /users/settings/confirm_email/:token" do - setup %{user: user} do - email = unique_user_email() - - token = - extract_user_token(fn url -> - Accounts.deliver_update_email_instructions(%{user | email: email}, user.email, url) - end) - - %{token: token, email: email} - end - - test "updates the user email once", %{conn: conn, user: user, token: token, email: email} do - conn = get(conn, Routes.user_settings_path(conn, :confirm_email, token)) - assert redirected_to(conn) == Routes.user_settings_path(conn, :edit) - assert get_flash(conn, :info) =~ "Email changed successfully" - refute Accounts.get_user_by_email(user.email) - assert Accounts.get_user_by_email(email) - - conn = get(conn, Routes.user_settings_path(conn, :confirm_email, token)) - assert redirected_to(conn) == Routes.user_settings_path(conn, :edit) - assert get_flash(conn, :error) =~ "Email change link is invalid or it has expired" - end - - test "does not update email with invalid token", %{conn: conn, user: user} do - conn = get(conn, Routes.user_settings_path(conn, :confirm_email, "oops")) - assert redirected_to(conn) == Routes.user_settings_path(conn, :edit) - assert get_flash(conn, :error) =~ "Email change link is invalid or it has expired" - assert Accounts.get_user_by_email(user.email) - end - - test "redirects if user is not logged in", %{token: token} do - conn = build_conn() - conn = get(conn, Routes.user_settings_path(conn, :confirm_email, token)) - assert redirected_to(conn) == Routes.user_session_path(conn, :new) - end - end -end diff --git a/test/link_shortener_web/views/error_view_test.exs b/test/link_shortener_web/views/error_view_test.exs deleted file mode 100644 index 796b732..0000000 --- a/test/link_shortener_web/views/error_view_test.exs +++ /dev/null @@ -1,14 +0,0 @@ -defmodule LinkShortenerWeb.ErrorViewTest do - use LinkShortenerWeb.ConnCase, async: true - - # Bring render/3 and render_to_string/3 for testing custom views - import Phoenix.View - - test "renders 404.html" do - assert render_to_string(LinkShortenerWeb.ErrorView, "404.html", []) == "Not Found" - end - - test "renders 500.html" do - assert render_to_string(LinkShortenerWeb.ErrorView, "500.html", []) == "Internal Server Error" - end -end diff --git a/test/link_shortener_web/views/layout_view_test.exs b/test/link_shortener_web/views/layout_view_test.exs deleted file mode 100644 index 1c2276f..0000000 --- a/test/link_shortener_web/views/layout_view_test.exs +++ /dev/null @@ -1,8 +0,0 @@ -defmodule LinkShortenerWeb.LayoutViewTest do - use LinkShortenerWeb.ConnCase, async: true - - # When testing helpers, you may want to import Phoenix.HTML and - # use functions such as safe_to_string() to convert the helper - # result into an HTML string. - # import Phoenix.HTML -end diff --git a/test/link_shortener_web/views/page_view_test.exs b/test/link_shortener_web/views/page_view_test.exs deleted file mode 100644 index 5d6cc0e..0000000 --- a/test/link_shortener_web/views/page_view_test.exs +++ /dev/null @@ -1,3 +0,0 @@ -defmodule LinkShortenerWeb.PageViewTest do - use LinkShortenerWeb.ConnCase, async: true -end diff --git a/test/support/conn_case.ex b/test/support/conn_case.ex index 68c1073..4e74853 100644 --- a/test/support/conn_case.ex +++ b/test/support/conn_case.ex @@ -19,15 +19,15 @@ defmodule LinkShortenerWeb.ConnCase do using do quote do + # The default endpoint for testing + @endpoint LinkShortenerWeb.Endpoint + + use LinkShortenerWeb, :verified_routes + # Import conveniences for testing with connections import Plug.Conn import Phoenix.ConnTest import LinkShortenerWeb.ConnCase - - alias LinkShortenerWeb.Router.Helpers, as: Routes - - # The default endpoint for testing - @endpoint LinkShortenerWeb.Endpoint end end @@ -35,30 +35,4 @@ defmodule LinkShortenerWeb.ConnCase do LinkShortener.DataCase.setup_sandbox(tags) {:ok, conn: Phoenix.ConnTest.build_conn()} end - - @doc """ - Setup helper that registers and logs in users. - - setup :register_and_log_in_user - - It stores an updated connection and a registered user in the - test context. - """ - def register_and_log_in_user(%{conn: conn}) do - user = LinkShortener.AccountsFixtures.user_fixture() - %{conn: log_in_user(conn, user), user: user} - end - - @doc """ - Logs the given `user` into the `conn`. - - It returns an updated `conn`. - """ - def log_in_user(conn, user) do - token = LinkShortener.Accounts.generate_user_session_token(user) - - conn - |> Phoenix.ConnTest.init_test_session(%{}) - |> Plug.Conn.put_session(:user_token, token) - end end diff --git a/test/support/fixtures/accounts_fixtures.ex b/test/support/fixtures/accounts_fixtures.ex deleted file mode 100644 index 96bc2e7..0000000 --- a/test/support/fixtures/accounts_fixtures.ex +++ /dev/null @@ -1,50 +0,0 @@ -defmodule LinkShortener.AccountsFixtures do - @moduledoc """ - This module defines test helpers for creating - entities via the `LinkShortener.Accounts` context. - """ - - alias LinkShortener.Accounts - alias LinkShortener.Accounts.User - alias LinkShortenerWeb.Auth.Guardian - - @doc """ - Generate a unique user email. - """ - def unique_user_email, do: "user#{System.unique_integer()}@example.com" - def valid_user_password, do: "hello world!" - - def valid_user_attributes(attrs \\ %{}) do - Enum.into(attrs, %{ - email: unique_user_email(), - password: valid_user_password() - }) - end - - def user_fixture(attrs \\ %{}) do - {:ok, user} = - attrs - |> valid_user_attributes() - |> LinkShortener.Accounts.register_user() - - user - end - - def user_token_fixture(attrs \\ %{}) do - user_params = %{ - email: "user@mail.com", - password: "some password" - } - - {:ok, %User{} = user} = Accounts.register_user(user_params) - {:ok, token, _claims} = Guardian.encode_and_sign(user) - - token - end - - def extract_user_token(fun) do - {:ok, captured_email} = fun.(&"[TOKEN]#{&1}[TOKEN]") - [_, token | _] = String.split(captured_email.text_body, "[TOKEN]") - token - end -end