Resources
9 |-
10 |
- 11 | Guides & Docs 12 | 13 |
- 14 | Source 15 | 16 |
- 17 | v1.6 Changelog 18 | 19 |
├── .formatter.exs ├── .gitignore ├── README.md ├── assets ├── css │ ├── app.css │ └── phoenix.css ├── js │ └── app.js └── vendor │ └── topbar.js ├── config ├── config.exs ├── dev.exs ├── prod.exs ├── runtime.exs └── test.exs ├── lib ├── sqlite_scale.ex ├── sqlite_scale │ ├── accounts.ex │ ├── accounts │ │ ├── user.ex │ │ ├── user_notifier.ex │ │ └── user_token.ex │ ├── application.ex │ ├── dynamic_repo_supervisor.ex │ ├── dynamic_repo_supervisor │ │ ├── repo_hydrator.ex │ │ ├── repo_registry.ex │ │ └── repo_supervisor.ex │ ├── mailer.ex │ ├── repo.ex │ ├── todo_items.ex │ ├── todo_items │ │ └── todo_item.ex │ └── user_repo.ex ├── sqlite_scale_web.ex └── sqlite_scale_web │ ├── controllers │ ├── page_controller.ex │ ├── todo_item_controller.ex │ ├── user_auth.ex │ ├── user_confirmation_controller.ex │ ├── user_registration_controller.ex │ ├── user_reset_password_controller.ex │ ├── user_session_controller.ex │ └── user_settings_controller.ex │ ├── endpoint.ex │ ├── gettext.ex │ ├── router.ex │ ├── telemetry.ex │ ├── templates │ ├── layout │ │ ├── _user_menu.html.heex │ │ ├── app.html.heex │ │ ├── live.html.heex │ │ └── root.html.heex │ ├── page │ │ └── index.html.heex │ ├── todo_item │ │ ├── edit.html.heex │ │ ├── form.html.heex │ │ ├── index.html.heex │ │ ├── new.html.heex │ │ └── show.html.heex │ ├── user_confirmation │ │ ├── edit.html.heex │ │ └── new.html.heex │ ├── user_registration │ │ └── new.html.heex │ ├── user_reset_password │ │ ├── edit.html.heex │ │ └── new.html.heex │ ├── user_session │ │ └── new.html.heex │ └── user_settings │ │ └── edit.html.heex │ └── views │ ├── error_helpers.ex │ ├── error_view.ex │ ├── layout_view.ex │ ├── page_view.ex │ ├── todo_item_view.ex │ ├── user_confirmation_view.ex │ ├── user_registration_view.ex │ ├── user_reset_password_view.ex │ ├── user_session_view.ex │ └── user_settings_view.ex ├── mix.exs ├── mix.lock ├── priv ├── gettext │ ├── en │ │ └── LC_MESSAGES │ │ │ └── errors.po │ └── errors.pot ├── repo │ ├── migrations │ │ ├── .formatter.exs │ │ └── 20220221061920_create_users_auth_tables.exs │ └── seeds.exs ├── static │ ├── favicon.ico │ ├── images │ │ └── phoenix.png │ └── robots.txt └── user_repo │ └── migrations │ └── 20220221192607_add_todo_list_table.exs └── test ├── sqlite_scale ├── accounts_test.exs └── todo_items_test.exs ├── sqlite_scale_web ├── controllers │ ├── page_controller_test.exs │ ├── todo_item_controller_test.exs │ ├── user_auth_test.exs │ ├── user_confirmation_controller_test.exs │ ├── user_registration_controller_test.exs │ ├── user_reset_password_controller_test.exs │ ├── user_session_controller_test.exs │ └── user_settings_controller_test.exs └── views │ ├── error_view_test.exs │ ├── layout_view_test.exs │ └── page_view_test.exs ├── support ├── channel_case.ex ├── conn_case.ex ├── data_case.ex └── fixtures │ ├── accounts_fixtures.ex │ └── todo_items_fixtures.ex └── test_helper.exs /.formatter.exs: -------------------------------------------------------------------------------- 1 | [ 2 | import_deps: [:ecto, :phoenix], 3 | line_length: 120, 4 | inputs: ["*.{ex,exs}", "priv/*/seeds.exs", "{config,lib,test}/**/*.{ex,exs}"], 5 | subdirectories: ["priv/*/migrations"] 6 | ] 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where 3rd-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | sqlite_scale-*.tar 24 | 25 | # Ignore assets that are produced by build tools. 26 | /priv/static/assets/ 27 | 28 | # Ignore digested assets cache. 29 | /priv/static/cache_manifest.json 30 | 31 | # In case you use Node.js/npm, you want to ignore these. 32 | npm-debug.log 33 | /assets/node_modules/ 34 | 35 | # Database files 36 | *.db 37 | *.db-* 38 | 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SqliteScale 2 | 3 | To start your Phoenix server: 4 | 5 | * Install dependencies with `mix deps.get` 6 | * Create and migrate your database with `mix ecto.setup` 7 | * Start Phoenix endpoint with `mix phx.server` or inside IEx with `iex -S mix phx.server` 8 | 9 | Now you can visit [`localhost:4000`](http://localhost:4000) from your browser. 10 | 11 | Ready to run in production? Please [check our deployment guides](https://hexdocs.pm/phoenix/deployment.html). 12 | 13 | ## Learn more 14 | 15 | * Official website: https://www.phoenixframework.org/ 16 | * Guides: https://hexdocs.pm/phoenix/overview.html 17 | * Docs: https://hexdocs.pm/phoenix 18 | * Forum: https://elixirforum.com/c/phoenix-forum 19 | * Source: https://github.com/phoenixframework/phoenix 20 | -------------------------------------------------------------------------------- /assets/css/app.css: -------------------------------------------------------------------------------- 1 | /* This file is for your main application CSS */ 2 | @import "./phoenix.css"; 3 | 4 | /* Alerts and form errors used by phx.new */ 5 | .alert { 6 | padding: 15px; 7 | margin-bottom: 20px; 8 | border: 1px solid transparent; 9 | border-radius: 4px; 10 | } 11 | .alert-info { 12 | color: #31708f; 13 | background-color: #d9edf7; 14 | border-color: #bce8f1; 15 | } 16 | .alert-warning { 17 | color: #8a6d3b; 18 | background-color: #fcf8e3; 19 | border-color: #faebcc; 20 | } 21 | .alert-danger { 22 | color: #a94442; 23 | background-color: #f2dede; 24 | border-color: #ebccd1; 25 | } 26 | .alert p { 27 | margin-bottom: 0; 28 | } 29 | .alert:empty { 30 | display: none; 31 | } 32 | .invalid-feedback { 33 | color: #a94442; 34 | display: block; 35 | margin: -1rem 0 2rem; 36 | } 37 | 38 | /* LiveView specific classes for your customization */ 39 | .phx-no-feedback.invalid-feedback, 40 | .phx-no-feedback .invalid-feedback { 41 | display: none; 42 | } 43 | 44 | .phx-click-loading { 45 | opacity: 0.5; 46 | transition: opacity 1s ease-out; 47 | } 48 | 49 | .phx-loading{ 50 | cursor: wait; 51 | } 52 | 53 | .phx-modal { 54 | opacity: 1!important; 55 | position: fixed; 56 | z-index: 1; 57 | left: 0; 58 | top: 0; 59 | width: 100%; 60 | height: 100%; 61 | overflow: auto; 62 | background-color: rgba(0,0,0,0.4); 63 | } 64 | 65 | .phx-modal-content { 66 | background-color: #fefefe; 67 | margin: 15vh auto; 68 | padding: 20px; 69 | border: 1px solid #888; 70 | width: 80%; 71 | } 72 | 73 | .phx-modal-close { 74 | color: #aaa; 75 | float: right; 76 | font-size: 28px; 77 | font-weight: bold; 78 | } 79 | 80 | .phx-modal-close:hover, 81 | .phx-modal-close:focus { 82 | color: black; 83 | text-decoration: none; 84 | cursor: pointer; 85 | } 86 | 87 | .fade-in-scale { 88 | animation: 0.2s ease-in 0s normal forwards 1 fade-in-scale-keys; 89 | } 90 | 91 | .fade-out-scale { 92 | animation: 0.2s ease-out 0s normal forwards 1 fade-out-scale-keys; 93 | } 94 | 95 | .fade-in { 96 | animation: 0.2s ease-out 0s normal forwards 1 fade-in-keys; 97 | } 98 | .fade-out { 99 | animation: 0.2s ease-out 0s normal forwards 1 fade-out-keys; 100 | } 101 | 102 | @keyframes fade-in-scale-keys{ 103 | 0% { scale: 0.95; opacity: 0; } 104 | 100% { scale: 1.0; opacity: 1; } 105 | } 106 | 107 | @keyframes fade-out-scale-keys{ 108 | 0% { scale: 1.0; opacity: 1; } 109 | 100% { scale: 0.95; opacity: 0; } 110 | } 111 | 112 | @keyframes fade-in-keys{ 113 | 0% { opacity: 0; } 114 | 100% { opacity: 1; } 115 | } 116 | 117 | @keyframes fade-out-keys{ 118 | 0% { opacity: 1; } 119 | 100% { opacity: 0; } 120 | } 121 | -------------------------------------------------------------------------------- /assets/css/phoenix.css: -------------------------------------------------------------------------------- 1 | /* Includes some default style for the starter application. 2 | * This can be safely deleted to start fresh. 3 | */ 4 | 5 | /* Milligram v1.4.1 https://milligram.github.io 6 | * Copyright (c) 2020 CJ Patoilo Licensed under the MIT license 7 | */ 8 | 9 | *,*: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} 10 | 11 | /* General style */ 12 | h1{font-size: 3.6rem; line-height: 1.25} 13 | h2{font-size: 2.8rem; line-height: 1.3} 14 | h3{font-size: 2.2rem; letter-spacing: -.08rem; line-height: 1.35} 15 | h4{font-size: 1.8rem; letter-spacing: -.05rem; line-height: 1.5} 16 | h5{font-size: 1.6rem; letter-spacing: 0; line-height: 1.4} 17 | h6{font-size: 1.4rem; letter-spacing: 0; line-height: 1.2} 18 | pre{padding: 1em;} 19 | 20 | .container{ 21 | margin: 0 auto; 22 | max-width: 80.0rem; 23 | padding: 0 2.0rem; 24 | position: relative; 25 | width: 100% 26 | } 27 | select { 28 | width: auto; 29 | } 30 | 31 | /* Phoenix promo and logo */ 32 | .phx-hero { 33 | text-align: center; 34 | border-bottom: 1px solid #e3e3e3; 35 | background: #eee; 36 | border-radius: 6px; 37 | padding: 3em 3em 1em; 38 | margin-bottom: 3rem; 39 | font-weight: 200; 40 | font-size: 120%; 41 | } 42 | .phx-hero input { 43 | background: #ffffff; 44 | } 45 | .phx-logo { 46 | min-width: 300px; 47 | margin: 1rem; 48 | display: block; 49 | } 50 | .phx-logo img { 51 | width: auto; 52 | display: block; 53 | } 54 | 55 | /* Headers */ 56 | header { 57 | width: 100%; 58 | background: #fdfdfd; 59 | border-bottom: 1px solid #eaeaea; 60 | margin-bottom: 2rem; 61 | } 62 | header section { 63 | align-items: center; 64 | display: flex; 65 | flex-direction: column; 66 | justify-content: space-between; 67 | } 68 | header section :first-child { 69 | order: 2; 70 | } 71 | header section :last-child { 72 | order: 1; 73 | } 74 | header nav ul, 75 | header nav li { 76 | margin: 0; 77 | padding: 0; 78 | display: block; 79 | text-align: right; 80 | white-space: nowrap; 81 | } 82 | header nav ul { 83 | margin: 1rem; 84 | margin-top: 0; 85 | } 86 | header nav a { 87 | display: block; 88 | } 89 | 90 | @media (min-width: 40.0rem) { /* Small devices (landscape phones, 576px and up) */ 91 | header section { 92 | flex-direction: row; 93 | } 94 | header nav ul { 95 | margin: 1rem; 96 | } 97 | .phx-logo { 98 | flex-basis: 527px; 99 | margin: 2rem 1rem; 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /assets/js/app.js: -------------------------------------------------------------------------------- 1 | // We import the CSS which is extracted to its own file by esbuild. 2 | // Remove this line if you add a your own CSS build pipeline (e.g postcss). 3 | import "../css/app.css" 4 | 5 | // If you want to use Phoenix channels, run `mix help phx.gen.channel` 6 | // to get started and then uncomment the line below. 7 | // import "./user_socket.js" 8 | 9 | // You can include dependencies in two ways. 10 | // 11 | // The simplest option is to put them in assets/vendor and 12 | // import them using relative paths: 13 | // 14 | // import "../vendor/some-package.js" 15 | // 16 | // Alternatively, you can `npm install some-package --prefix assets` and import 17 | // them using a path starting with the package name: 18 | // 19 | // import "some-package" 20 | // 21 | 22 | // Include phoenix_html to handle method=PUT/DELETE in forms and buttons. 23 | import "phoenix_html" 24 | // Establish Phoenix Socket and LiveView configuration. 25 | import {Socket} from "phoenix" 26 | import {LiveSocket} from "phoenix_live_view" 27 | import topbar from "../vendor/topbar" 28 | 29 | let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content") 30 | let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}}) 31 | 32 | // Show progress bar on live navigation and form submits 33 | topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"}) 34 | window.addEventListener("phx:page-loading-start", info => topbar.show()) 35 | window.addEventListener("phx:page-loading-stop", info => topbar.hide()) 36 | 37 | // connect if there are any LiveViews on the page 38 | liveSocket.connect() 39 | 40 | // expose liveSocket on window for web console debug logs and latency simulation: 41 | // >> liveSocket.enableDebug() 42 | // >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session 43 | // >> liveSocket.disableLatencySim() 44 | window.liveSocket = liveSocket 45 | 46 | -------------------------------------------------------------------------------- /assets/vendor/topbar.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @license MIT 3 | * topbar 1.0.0, 2021-01-06 4 | * https://buunguyen.github.io/topbar 5 | * Copyright (c) 2021 Buu Nguyen 6 | */ 7 | (function (window, document) { 8 | "use strict"; 9 | 10 | // https://gist.github.com/paulirish/1579671 11 | (function () { 12 | var lastTime = 0; 13 | var vendors = ["ms", "moz", "webkit", "o"]; 14 | for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { 15 | window.requestAnimationFrame = 16 | window[vendors[x] + "RequestAnimationFrame"]; 17 | window.cancelAnimationFrame = 18 | window[vendors[x] + "CancelAnimationFrame"] || 19 | window[vendors[x] + "CancelRequestAnimationFrame"]; 20 | } 21 | if (!window.requestAnimationFrame) 22 | window.requestAnimationFrame = function (callback, element) { 23 | var currTime = new Date().getTime(); 24 | var timeToCall = Math.max(0, 16 - (currTime - lastTime)); 25 | var id = window.setTimeout(function () { 26 | callback(currTime + timeToCall); 27 | }, timeToCall); 28 | lastTime = currTime + timeToCall; 29 | return id; 30 | }; 31 | if (!window.cancelAnimationFrame) 32 | window.cancelAnimationFrame = function (id) { 33 | clearTimeout(id); 34 | }; 35 | })(); 36 | 37 | var canvas, 38 | progressTimerId, 39 | fadeTimerId, 40 | currentProgress, 41 | showing, 42 | addEvent = function (elem, type, handler) { 43 | if (elem.addEventListener) elem.addEventListener(type, handler, false); 44 | else if (elem.attachEvent) elem.attachEvent("on" + type, handler); 45 | else elem["on" + type] = handler; 46 | }, 47 | options = { 48 | autoRun: true, 49 | barThickness: 3, 50 | barColors: { 51 | 0: "rgba(26, 188, 156, .9)", 52 | ".25": "rgba(52, 152, 219, .9)", 53 | ".50": "rgba(241, 196, 15, .9)", 54 | ".75": "rgba(230, 126, 34, .9)", 55 | "1.0": "rgba(211, 84, 0, .9)", 56 | }, 57 | shadowBlur: 10, 58 | shadowColor: "rgba(0, 0, 0, .6)", 59 | className: null, 60 | }, 61 | repaint = function () { 62 | canvas.width = window.innerWidth; 63 | canvas.height = options.barThickness * 5; // need space for shadow 64 | 65 | var ctx = canvas.getContext("2d"); 66 | ctx.shadowBlur = options.shadowBlur; 67 | ctx.shadowColor = options.shadowColor; 68 | 69 | var lineGradient = ctx.createLinearGradient(0, 0, canvas.width, 0); 70 | for (var stop in options.barColors) 71 | lineGradient.addColorStop(stop, options.barColors[stop]); 72 | ctx.lineWidth = options.barThickness; 73 | ctx.beginPath(); 74 | ctx.moveTo(0, options.barThickness / 2); 75 | ctx.lineTo( 76 | Math.ceil(currentProgress * canvas.width), 77 | options.barThickness / 2 78 | ); 79 | ctx.strokeStyle = lineGradient; 80 | ctx.stroke(); 81 | }, 82 | createCanvas = function () { 83 | canvas = document.createElement("canvas"); 84 | var style = canvas.style; 85 | style.position = "fixed"; 86 | style.top = style.left = style.right = style.margin = style.padding = 0; 87 | style.zIndex = 100001; 88 | style.display = "none"; 89 | if (options.className) canvas.classList.add(options.className); 90 | document.body.appendChild(canvas); 91 | addEvent(window, "resize", repaint); 92 | }, 93 | topbar = { 94 | config: function (opts) { 95 | for (var key in opts) 96 | if (options.hasOwnProperty(key)) options[key] = opts[key]; 97 | }, 98 | show: function () { 99 | if (showing) return; 100 | showing = true; 101 | if (fadeTimerId !== null) window.cancelAnimationFrame(fadeTimerId); 102 | if (!canvas) createCanvas(); 103 | canvas.style.opacity = 1; 104 | canvas.style.display = "block"; 105 | topbar.progress(0); 106 | if (options.autoRun) { 107 | (function loop() { 108 | progressTimerId = window.requestAnimationFrame(loop); 109 | topbar.progress( 110 | "+" + 0.05 * Math.pow(1 - Math.sqrt(currentProgress), 2) 111 | ); 112 | })(); 113 | } 114 | }, 115 | progress: function (to) { 116 | if (typeof to === "undefined") return currentProgress; 117 | if (typeof to === "string") { 118 | to = 119 | (to.indexOf("+") >= 0 || to.indexOf("-") >= 0 120 | ? currentProgress 121 | : 0) + parseFloat(to); 122 | } 123 | currentProgress = to > 1 ? 1 : to; 124 | repaint(); 125 | return currentProgress; 126 | }, 127 | hide: function () { 128 | if (!showing) return; 129 | showing = false; 130 | if (progressTimerId != null) { 131 | window.cancelAnimationFrame(progressTimerId); 132 | progressTimerId = null; 133 | } 134 | (function loop() { 135 | if (topbar.progress("+.1") >= 1) { 136 | canvas.style.opacity -= 0.05; 137 | if (canvas.style.opacity <= 0.05) { 138 | canvas.style.display = "none"; 139 | fadeTimerId = null; 140 | return; 141 | } 142 | } 143 | fadeTimerId = window.requestAnimationFrame(loop); 144 | })(); 145 | }, 146 | }; 147 | 148 | if (typeof module === "object" && typeof module.exports === "object") { 149 | module.exports = topbar; 150 | } else if (typeof define === "function" && define.amd) { 151 | define(function () { 152 | return topbar; 153 | }); 154 | } else { 155 | this.topbar = topbar; 156 | } 157 | }.call(this, window, document)); 158 | -------------------------------------------------------------------------------- /config/config.exs: -------------------------------------------------------------------------------- 1 | # This file is responsible for configuring your application 2 | # and its dependencies with the aid of the Config module. 3 | # 4 | # This configuration file is loaded before any dependency and 5 | # is restricted to this project. 6 | 7 | # General application configuration 8 | import Config 9 | 10 | config :sqlite_scale, 11 | ecto_repos: [SqliteScale.Repo], 12 | generators: [binary_id: true] 13 | 14 | # Configures the endpoint 15 | config :sqlite_scale, SqliteScaleWeb.Endpoint, 16 | url: [host: "localhost"], 17 | render_errors: [view: SqliteScaleWeb.ErrorView, accepts: ~w(html json), layout: false], 18 | pubsub_server: SqliteScale.PubSub, 19 | live_view: [signing_salt: "xDOGAAu1"] 20 | 21 | # Configures the mailer 22 | # 23 | # By default it uses the "Local" adapter which stores the emails 24 | # locally. You can see the emails in your browser, at "/dev/mailbox". 25 | # 26 | # For production it's recommended to configure a different adapter 27 | # at the `config/runtime.exs`. 28 | config :sqlite_scale, SqliteScale.Mailer, adapter: Swoosh.Adapters.Local 29 | 30 | # Swoosh API client is needed for adapters other than SMTP. 31 | config :swoosh, :api_client, false 32 | 33 | # Configure esbuild (the version is required) 34 | config :esbuild, 35 | version: "0.14.0", 36 | default: [ 37 | args: 38 | ~w(js/app.js --bundle --target=es2017 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*), 39 | cd: Path.expand("../assets", __DIR__), 40 | env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)} 41 | ] 42 | 43 | # Configures Elixir's Logger 44 | config :logger, :console, 45 | format: "$time $metadata[$level] $message\n", 46 | metadata: [:request_id] 47 | 48 | # Use Jason for JSON parsing in Phoenix 49 | config :phoenix, :json_library, Jason 50 | 51 | # Import environment specific config. This must remain at the bottom 52 | # of this file so it overrides the configuration defined above. 53 | import_config "#{config_env()}.exs" 54 | -------------------------------------------------------------------------------- /config/dev.exs: -------------------------------------------------------------------------------- 1 | import Config 2 | 3 | # Configure your database 4 | config :sqlite_scale, SqliteScale.Repo, 5 | database: Path.expand("../sqlite_scale_dev.db", Path.dirname(__ENV__.file)), 6 | pool_size: 5, 7 | show_sensitive_data_on_connection_error: true 8 | 9 | # For development, we disable any cache and enable 10 | # debugging and code reloading. 11 | # 12 | # The watchers configuration can be used to run external 13 | # watchers to your application. For example, we use it 14 | # with esbuild to bundle .js and .css sources. 15 | config :sqlite_scale, SqliteScaleWeb.Endpoint, 16 | # Binding to loopback ipv4 address prevents access from other machines. 17 | # Change to `ip: {0, 0, 0, 0}` to allow access from other machines. 18 | http: [ip: {127, 0, 0, 1}, port: 4000], 19 | check_origin: false, 20 | code_reloader: true, 21 | debug_errors: true, 22 | secret_key_base: "8DrS/TWI0/+eEjZdgdcFo/3qDyWe2/i4dHHnbFsm+hWfbSkfuEAjeFBXQtZNxB1h", 23 | watchers: [ 24 | # Start the esbuild watcher by calling Esbuild.install_and_run(:default, args) 25 | esbuild: {Esbuild, :install_and_run, [:default, ~w(--sourcemap=inline --watch)]} 26 | ] 27 | 28 | # ## SSL Support 29 | # 30 | # In order to use HTTPS in development, a self-signed 31 | # certificate can be generated by running the following 32 | # Mix task: 33 | # 34 | # mix phx.gen.cert 35 | # 36 | # Note that this task requires Erlang/OTP 20 or later. 37 | # Run `mix help phx.gen.cert` for more information. 38 | # 39 | # The `http:` config above can be replaced with: 40 | # 41 | # https: [ 42 | # port: 4001, 43 | # cipher_suite: :strong, 44 | # keyfile: "priv/cert/selfsigned_key.pem", 45 | # certfile: "priv/cert/selfsigned.pem" 46 | # ], 47 | # 48 | # If desired, both `http:` and `https:` keys can be 49 | # configured to run both http and https servers on 50 | # different ports. 51 | 52 | # Watch static and templates for browser reloading. 53 | config :sqlite_scale, SqliteScaleWeb.Endpoint, 54 | live_reload: [ 55 | patterns: [ 56 | ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$", 57 | ~r"priv/gettext/.*(po)$", 58 | ~r"lib/sqlite_scale_web/(live|views)/.*(ex)$", 59 | ~r"lib/sqlite_scale_web/templates/.*(eex)$" 60 | ] 61 | ] 62 | 63 | # Do not include metadata nor timestamps in development logs 64 | config :logger, :console, format: "[$level] $message\n" 65 | 66 | # Set a higher stacktrace during development. Avoid configuring such 67 | # in production as building large stacktraces may be expensive. 68 | config :phoenix, :stacktrace_depth, 20 69 | 70 | # Initialize plugs at runtime for faster development compilation 71 | config :phoenix, :plug_init_mode, :runtime 72 | -------------------------------------------------------------------------------- /config/prod.exs: -------------------------------------------------------------------------------- 1 | import Config 2 | 3 | # For production, don't forget to configure the url host 4 | # to something meaningful, Phoenix uses this information 5 | # when generating URLs. 6 | # 7 | # Note we also include the path to a cache manifest 8 | # containing the digested version of static files. This 9 | # manifest is generated by the `mix phx.digest` task, 10 | # which you should run after static files are built and 11 | # before starting your production server. 12 | config :sqlite_scale, SqliteScaleWeb.Endpoint, cache_static_manifest: "priv/static/cache_manifest.json" 13 | 14 | # Do not print debug messages in production 15 | config :logger, level: :info 16 | 17 | # ## SSL Support 18 | # 19 | # To get SSL working, you will need to add the `https` key 20 | # to the previous section and set your `:url` port to 443: 21 | # 22 | # config :sqlite_scale, SqliteScaleWeb.Endpoint, 23 | # ..., 24 | # url: [host: "example.com", port: 443], 25 | # https: [ 26 | # ..., 27 | # port: 443, 28 | # cipher_suite: :strong, 29 | # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), 30 | # certfile: System.get_env("SOME_APP_SSL_CERT_PATH") 31 | # ] 32 | # 33 | # The `cipher_suite` is set to `:strong` to support only the 34 | # latest and more secure SSL ciphers. This means old browsers 35 | # and clients may not be supported. You can set it to 36 | # `:compatible` for wider support. 37 | # 38 | # `:keyfile` and `:certfile` expect an absolute path to the key 39 | # and cert in disk or a relative path inside priv, for example 40 | # "priv/ssl/server.key". For all supported SSL configuration 41 | # options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 42 | # 43 | # We also recommend setting `force_ssl` in your endpoint, ensuring 44 | # no data is ever sent via http, always redirecting to https: 45 | # 46 | # config :sqlite_scale, SqliteScaleWeb.Endpoint, 47 | # force_ssl: [hsts: true] 48 | # 49 | # Check `Plug.SSL` for all available options in `force_ssl`. 50 | -------------------------------------------------------------------------------- /config/runtime.exs: -------------------------------------------------------------------------------- 1 | import Config 2 | 3 | # config/runtime.exs is executed for all environments, including 4 | # during releases. It is executed after compilation and before the 5 | # system starts, so it is typically used to load production configuration 6 | # and secrets from environment variables or elsewhere. Do not define 7 | # any compile-time configuration in here, as it won't be applied. 8 | # The block below contains prod specific runtime configuration. 9 | 10 | # Start the phoenix server if environment is set and running in a release 11 | if System.get_env("PHX_SERVER") && System.get_env("RELEASE_NAME") do 12 | config :sqlite_scale, SqliteScaleWeb.Endpoint, server: true 13 | end 14 | 15 | if config_env() == :prod do 16 | database_path = 17 | System.get_env("DATABASE_PATH") || 18 | raise """ 19 | environment variable DATABASE_PATH is missing. 20 | For example: /etc/sqlite_scale/sqlite_scale.db 21 | """ 22 | 23 | config :sqlite_scale, SqliteScale.Repo, 24 | database: database_path, 25 | pool_size: String.to_integer(System.get_env("POOL_SIZE") || "5") 26 | 27 | # The secret key base is used to sign/encrypt cookies and other secrets. 28 | # A default value is used in config/dev.exs and config/test.exs but you 29 | # want to use a different value for prod and you most likely don't want 30 | # to check this value into version control, so we use an environment 31 | # variable instead. 32 | secret_key_base = 33 | System.get_env("SECRET_KEY_BASE") || 34 | raise """ 35 | environment variable SECRET_KEY_BASE is missing. 36 | You can generate one by calling: mix phx.gen.secret 37 | """ 38 | 39 | host = System.get_env("PHX_HOST") || "example.com" 40 | port = String.to_integer(System.get_env("PORT") || "4000") 41 | 42 | config :sqlite_scale, SqliteScaleWeb.Endpoint, 43 | url: [host: host, port: 443], 44 | http: [ 45 | # Enable IPv6 and bind on all interfaces. 46 | # Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access. 47 | # See the documentation on https://hexdocs.pm/plug_cowboy/Plug.Cowboy.html 48 | # for details about using IPv6 vs IPv4 and loopback vs public addresses. 49 | ip: {0, 0, 0, 0, 0, 0, 0, 0}, 50 | port: port 51 | ], 52 | secret_key_base: secret_key_base 53 | 54 | # ## Using releases 55 | # 56 | # If you are doing OTP releases, you need to instruct Phoenix 57 | # to start each relevant endpoint: 58 | # 59 | # config :sqlite_scale, SqliteScaleWeb.Endpoint, server: true 60 | # 61 | # Then you can assemble a release by calling `mix release`. 62 | # See `mix help release` for more information. 63 | 64 | # ## Configuring the mailer 65 | # 66 | # In production you need to configure the mailer to use a different adapter. 67 | # Also, you may need to configure the Swoosh API client of your choice if you 68 | # are not using SMTP. Here is an example of the configuration: 69 | # 70 | # config :sqlite_scale, SqliteScale.Mailer, 71 | # adapter: Swoosh.Adapters.Mailgun, 72 | # api_key: System.get_env("MAILGUN_API_KEY"), 73 | # domain: System.get_env("MAILGUN_DOMAIN") 74 | # 75 | # For this example you need include a HTTP client required by Swoosh API client. 76 | # Swoosh supports Hackney and Finch out of the box: 77 | # 78 | # config :swoosh, :api_client, Swoosh.ApiClient.Hackney 79 | # 80 | # See https://hexdocs.pm/swoosh/Swoosh.html#module-installation for details. 81 | end 82 | -------------------------------------------------------------------------------- /config/test.exs: -------------------------------------------------------------------------------- 1 | import Config 2 | 3 | # Only in tests, remove the complexity from the password hashing algorithm 4 | config :bcrypt_elixir, :log_rounds, 1 5 | 6 | # Configure your database 7 | # 8 | # The MIX_TEST_PARTITION environment variable can be used 9 | # to provide built-in test partitioning in CI environment. 10 | # Run `mix help test` for more information. 11 | config :sqlite_scale, SqliteScale.Repo, 12 | database: Path.expand("../sqlite_scale_test.db", Path.dirname(__ENV__.file)), 13 | pool_size: 5, 14 | pool: Ecto.Adapters.SQL.Sandbox 15 | 16 | # We don't run a server during test. If one is required, 17 | # you can enable the server option below. 18 | config :sqlite_scale, SqliteScaleWeb.Endpoint, 19 | http: [ip: {127, 0, 0, 1}, port: 4002], 20 | secret_key_base: "sNdZ77z6pLPXUxggxPytffLPO7FcTTVeGGwYatqaEGBzaUDB1QZNimxgGyc9IYWu", 21 | server: false 22 | 23 | # In test we don't send emails. 24 | config :sqlite_scale, SqliteScale.Mailer, adapter: Swoosh.Adapters.Test 25 | 26 | # Print only warnings and errors during test 27 | config :logger, level: :warn 28 | 29 | # Initialize plugs at runtime for faster test compilation 30 | config :phoenix, :plug_init_mode, :runtime 31 | -------------------------------------------------------------------------------- /lib/sqlite_scale.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScale do 2 | @moduledoc """ 3 | SqliteScale keeps the contexts that define your domain 4 | and business logic. 5 | 6 | Contexts are also responsible for managing your data, regardless 7 | if it comes from the database, an external API or others. 8 | """ 9 | end 10 | -------------------------------------------------------------------------------- /lib/sqlite_scale/accounts.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScale.Accounts do 2 | @moduledoc """ 3 | The Accounts context. 4 | """ 5 | 6 | import Ecto.Query, warn: false 7 | 8 | alias SqliteScale.Accounts.{User, UserToken, UserNotifier} 9 | alias SqliteScale.DynamicRepoSupervisor.RepoSupervisor 10 | alias SqliteScale.Repo 11 | 12 | ## Database getters 13 | 14 | @doc """ 15 | Gets a user by email. 16 | 17 | ## Examples 18 | 19 | iex> get_user_by_email("foo@example.com") 20 | %User{} 21 | 22 | iex> get_user_by_email("unknown@example.com") 23 | nil 24 | 25 | """ 26 | def get_user_by_email(email) when is_binary(email) do 27 | Repo.get_by(User, email: email) 28 | end 29 | 30 | def list_users do 31 | Repo.all(User) 32 | end 33 | 34 | @doc """ 35 | Gets a user by email and password. 36 | 37 | ## Examples 38 | 39 | iex> get_user_by_email_and_password("foo@example.com", "correct_password") 40 | %User{} 41 | 42 | iex> get_user_by_email_and_password("foo@example.com", "invalid_password") 43 | nil 44 | 45 | """ 46 | def get_user_by_email_and_password(email, password) 47 | when is_binary(email) and is_binary(password) do 48 | user = Repo.get_by(User, email: email) 49 | if User.valid_password?(user, password), do: user 50 | end 51 | 52 | @doc """ 53 | Gets a single user. 54 | 55 | Raises `Ecto.NoResultsError` if the User does not exist. 56 | 57 | ## Examples 58 | 59 | iex> get_user!(123) 60 | %User{} 61 | 62 | iex> get_user!(456) 63 | ** (Ecto.NoResultsError) 64 | 65 | """ 66 | def get_user!(id), do: Repo.get!(User, id) 67 | 68 | ## User registration 69 | 70 | @doc """ 71 | Registers a user. 72 | 73 | ## Examples 74 | 75 | iex> register_user(%{field: value}) 76 | {:ok, %User{}} 77 | 78 | iex> register_user(%{field: bad_value}) 79 | {:error, %Ecto.Changeset{}} 80 | 81 | """ 82 | def register_user(attrs) do 83 | %User{} 84 | |> User.registration_changeset(attrs) 85 | |> Repo.insert() 86 | |> case do 87 | {:ok, %User{} = user} = result -> 88 | RepoSupervisor.add_repo_to_supervisor(user) 89 | result 90 | 91 | error -> 92 | error 93 | end 94 | end 95 | 96 | @doc """ 97 | Returns an `%Ecto.Changeset{}` for tracking user changes. 98 | 99 | ## Examples 100 | 101 | iex> change_user_registration(user) 102 | %Ecto.Changeset{data: %User{}} 103 | 104 | """ 105 | def change_user_registration(%User{} = user, attrs \\ %{}) do 106 | User.registration_changeset(user, attrs, hash_password: false) 107 | end 108 | 109 | ## Settings 110 | 111 | @doc """ 112 | Returns an `%Ecto.Changeset{}` for changing the user email. 113 | 114 | ## Examples 115 | 116 | iex> change_user_email(user) 117 | %Ecto.Changeset{data: %User{}} 118 | 119 | """ 120 | def change_user_email(user, attrs \\ %{}) do 121 | User.email_changeset(user, attrs) 122 | end 123 | 124 | @doc """ 125 | Emulates that the email will change without actually changing 126 | it in the database. 127 | 128 | ## Examples 129 | 130 | iex> apply_user_email(user, "valid password", %{email: ...}) 131 | {:ok, %User{}} 132 | 133 | iex> apply_user_email(user, "invalid password", %{email: ...}) 134 | {:error, %Ecto.Changeset{}} 135 | 136 | """ 137 | def apply_user_email(user, password, attrs) do 138 | user 139 | |> User.email_changeset(attrs) 140 | |> User.validate_current_password(password) 141 | |> Ecto.Changeset.apply_action(:update) 142 | end 143 | 144 | @doc """ 145 | Updates the user email using the given token. 146 | 147 | If the token matches, the user email is updated and the token is deleted. 148 | The confirmed_at date is also updated to the current time. 149 | """ 150 | def update_user_email(user, token) do 151 | context = "change:#{user.email}" 152 | 153 | with {:ok, query} <- UserToken.verify_change_email_token_query(token, context), 154 | %UserToken{sent_to: email} <- Repo.one(query), 155 | {:ok, _} <- Repo.transaction(user_email_multi(user, email, context)) do 156 | :ok 157 | else 158 | _ -> :error 159 | end 160 | end 161 | 162 | defp user_email_multi(user, email, context) do 163 | changeset = 164 | user 165 | |> User.email_changeset(%{email: email}) 166 | |> User.confirm_changeset() 167 | 168 | Ecto.Multi.new() 169 | |> Ecto.Multi.update(:user, changeset) 170 | |> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, [context])) 171 | end 172 | 173 | @doc """ 174 | Delivers the update email instructions to the given user. 175 | 176 | ## Examples 177 | 178 | iex> deliver_update_email_instructions(user, current_email, &Routes.user_update_email_url(conn, :edit, &1)) 179 | {:ok, %{to: ..., body: ...}} 180 | 181 | """ 182 | def deliver_update_email_instructions(%User{} = user, current_email, update_email_url_fun) 183 | when is_function(update_email_url_fun, 1) do 184 | {encoded_token, user_token} = UserToken.build_email_token(user, "change:#{current_email}") 185 | 186 | Repo.insert!(user_token) 187 | UserNotifier.deliver_update_email_instructions(user, update_email_url_fun.(encoded_token)) 188 | end 189 | 190 | @doc """ 191 | Returns an `%Ecto.Changeset{}` for changing the user password. 192 | 193 | ## Examples 194 | 195 | iex> change_user_password(user) 196 | %Ecto.Changeset{data: %User{}} 197 | 198 | """ 199 | def change_user_password(user, attrs \\ %{}) do 200 | User.password_changeset(user, attrs, hash_password: false) 201 | end 202 | 203 | @doc """ 204 | Updates the user password. 205 | 206 | ## Examples 207 | 208 | iex> update_user_password(user, "valid password", %{password: ...}) 209 | {:ok, %User{}} 210 | 211 | iex> update_user_password(user, "invalid password", %{password: ...}) 212 | {:error, %Ecto.Changeset{}} 213 | 214 | """ 215 | def update_user_password(user, password, attrs) do 216 | changeset = 217 | user 218 | |> User.password_changeset(attrs) 219 | |> User.validate_current_password(password) 220 | 221 | Ecto.Multi.new() 222 | |> Ecto.Multi.update(:user, changeset) 223 | |> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, :all)) 224 | |> Repo.transaction() 225 | |> case do 226 | {:ok, %{user: user}} -> {:ok, user} 227 | {:error, :user, changeset, _} -> {:error, changeset} 228 | end 229 | end 230 | 231 | ## Session 232 | 233 | @doc """ 234 | Generates a session token. 235 | """ 236 | def generate_user_session_token(user) do 237 | {token, user_token} = UserToken.build_session_token(user) 238 | Repo.insert!(user_token) 239 | token 240 | end 241 | 242 | @doc """ 243 | Gets the user with the given signed token. 244 | """ 245 | def get_user_by_session_token(token) do 246 | {:ok, query} = UserToken.verify_session_token_query(token) 247 | Repo.one(query) 248 | end 249 | 250 | @doc """ 251 | Deletes the signed token with the given context. 252 | """ 253 | def delete_session_token(token) do 254 | Repo.delete_all(UserToken.token_and_context_query(token, "session")) 255 | :ok 256 | end 257 | 258 | ## Confirmation 259 | 260 | @doc """ 261 | Delivers the confirmation email instructions to the given user. 262 | 263 | ## Examples 264 | 265 | iex> deliver_user_confirmation_instructions(user, &Routes.user_confirmation_url(conn, :edit, &1)) 266 | {:ok, %{to: ..., body: ...}} 267 | 268 | iex> deliver_user_confirmation_instructions(confirmed_user, &Routes.user_confirmation_url(conn, :edit, &1)) 269 | {:error, :already_confirmed} 270 | 271 | """ 272 | def deliver_user_confirmation_instructions(%User{} = user, confirmation_url_fun) 273 | when is_function(confirmation_url_fun, 1) do 274 | if user.confirmed_at do 275 | {:error, :already_confirmed} 276 | else 277 | {encoded_token, user_token} = UserToken.build_email_token(user, "confirm") 278 | Repo.insert!(user_token) 279 | UserNotifier.deliver_confirmation_instructions(user, confirmation_url_fun.(encoded_token)) 280 | end 281 | end 282 | 283 | @doc """ 284 | Confirms a user by the given token. 285 | 286 | If the token matches, the user account is marked as confirmed 287 | and the token is deleted. 288 | """ 289 | def confirm_user(token) do 290 | with {:ok, query} <- UserToken.verify_email_token_query(token, "confirm"), 291 | %User{} = user <- Repo.one(query), 292 | {:ok, %{user: user}} <- Repo.transaction(confirm_user_multi(user)) do 293 | {:ok, user} 294 | else 295 | _ -> :error 296 | end 297 | end 298 | 299 | defp confirm_user_multi(user) do 300 | Ecto.Multi.new() 301 | |> Ecto.Multi.update(:user, User.confirm_changeset(user)) 302 | |> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, ["confirm"])) 303 | end 304 | 305 | ## Reset password 306 | 307 | @doc """ 308 | Delivers the reset password email to the given user. 309 | 310 | ## Examples 311 | 312 | iex> deliver_user_reset_password_instructions(user, &Routes.user_reset_password_url(conn, :edit, &1)) 313 | {:ok, %{to: ..., body: ...}} 314 | 315 | """ 316 | def deliver_user_reset_password_instructions(%User{} = user, reset_password_url_fun) 317 | when is_function(reset_password_url_fun, 1) do 318 | {encoded_token, user_token} = UserToken.build_email_token(user, "reset_password") 319 | Repo.insert!(user_token) 320 | UserNotifier.deliver_reset_password_instructions(user, reset_password_url_fun.(encoded_token)) 321 | end 322 | 323 | @doc """ 324 | Gets the user by reset password token. 325 | 326 | ## Examples 327 | 328 | iex> get_user_by_reset_password_token("validtoken") 329 | %User{} 330 | 331 | iex> get_user_by_reset_password_token("invalidtoken") 332 | nil 333 | 334 | """ 335 | def get_user_by_reset_password_token(token) do 336 | with {:ok, query} <- UserToken.verify_email_token_query(token, "reset_password"), 337 | %User{} = user <- Repo.one(query) do 338 | user 339 | else 340 | _ -> nil 341 | end 342 | end 343 | 344 | @doc """ 345 | Resets the user password. 346 | 347 | ## Examples 348 | 349 | iex> reset_user_password(user, %{password: "new long password", password_confirmation: "new long password"}) 350 | {:ok, %User{}} 351 | 352 | iex> reset_user_password(user, %{password: "valid", password_confirmation: "not the same"}) 353 | {:error, %Ecto.Changeset{}} 354 | 355 | """ 356 | def reset_user_password(user, attrs) do 357 | Ecto.Multi.new() 358 | |> Ecto.Multi.update(:user, User.password_changeset(user, attrs)) 359 | |> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, :all)) 360 | |> Repo.transaction() 361 | |> case do 362 | {:ok, %{user: user}} -> {:ok, user} 363 | {:error, :user, changeset, _} -> {:error, changeset} 364 | end 365 | end 366 | end 367 | -------------------------------------------------------------------------------- /lib/sqlite_scale/accounts/user.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScale.Accounts.User do 2 | @moduledoc """ 3 | The user Ecto schema 4 | """ 5 | 6 | use Ecto.Schema 7 | 8 | import Ecto.Changeset 9 | 10 | @primary_key {:id, :binary_id, autogenerate: true} 11 | @foreign_key_type :binary_id 12 | schema "users" do 13 | field :email, :string 14 | field :password, :string, virtual: true, redact: true 15 | field :hashed_password, :string, redact: true 16 | field :confirmed_at, :naive_datetime 17 | 18 | timestamps() 19 | end 20 | 21 | @doc """ 22 | A user changeset for registration. 23 | 24 | It is important to validate the length of both email and password. 25 | Otherwise databases may truncate the email without warnings, which 26 | could lead to unpredictable or insecure behaviour. Long passwords may 27 | also be very expensive to hash for certain algorithms. 28 | 29 | ## Options 30 | 31 | * `:hash_password` - Hashes the password so it can be stored securely 32 | in the database and ensures the password field is cleared to prevent 33 | leaks in the logs. If password hashing is not needed and clearing the 34 | password field is not desired (like when using this changeset for 35 | validations on a LiveView form), this option can be set to `false`. 36 | Defaults to `true`. 37 | """ 38 | def registration_changeset(user, attrs, opts \\ []) do 39 | user 40 | |> cast(attrs, [:email, :password]) 41 | |> validate_email() 42 | |> validate_password(opts) 43 | end 44 | 45 | defp validate_email(changeset) do 46 | changeset 47 | |> validate_required([:email]) 48 | |> validate_format(:email, ~r/^[^\s]+@[^\s]+$/, message: "must have the @ sign and no spaces") 49 | |> validate_length(:email, max: 160) 50 | |> unsafe_validate_unique(:email, SqliteScale.Repo) 51 | |> unique_constraint(:email) 52 | end 53 | 54 | defp validate_password(changeset, opts) do 55 | changeset 56 | |> validate_required([:password]) 57 | |> validate_length(:password, min: 12, max: 72) 58 | # |> validate_format(:password, ~r/[a-z]/, message: "at least one lower case character") 59 | # |> validate_format(:password, ~r/[A-Z]/, message: "at least one upper case character") 60 | # |> validate_format(:password, ~r/[!?@#$%^&*_0-9]/, message: "at least one digit or punctuation character") 61 | |> maybe_hash_password(opts) 62 | end 63 | 64 | defp maybe_hash_password(changeset, opts) do 65 | hash_password? = Keyword.get(opts, :hash_password, true) 66 | password = get_change(changeset, :password) 67 | 68 | if hash_password? && password && changeset.valid? do 69 | changeset 70 | # If using Bcrypt, then further validate it is at most 72 bytes long 71 | |> validate_length(:password, max: 72, count: :bytes) 72 | |> put_change(:hashed_password, Bcrypt.hash_pwd_salt(password)) 73 | |> delete_change(:password) 74 | else 75 | changeset 76 | end 77 | end 78 | 79 | @doc """ 80 | A user changeset for changing the email. 81 | 82 | It requires the email to change otherwise an error is added. 83 | """ 84 | def email_changeset(user, attrs) do 85 | user 86 | |> cast(attrs, [:email]) 87 | |> validate_email() 88 | |> case do 89 | %{changes: %{email: _}} = changeset -> changeset 90 | %{} = changeset -> add_error(changeset, :email, "did not change") 91 | end 92 | end 93 | 94 | @doc """ 95 | A user changeset for changing the password. 96 | 97 | ## Options 98 | 99 | * `:hash_password` - Hashes the password so it can be stored securely 100 | in the database and ensures the password field is cleared to prevent 101 | leaks in the logs. If password hashing is not needed and clearing the 102 | password field is not desired (like when using this changeset for 103 | validations on a LiveView form), this option can be set to `false`. 104 | Defaults to `true`. 105 | """ 106 | def password_changeset(user, attrs, opts \\ []) do 107 | user 108 | |> cast(attrs, [:password]) 109 | |> validate_confirmation(:password, message: "does not match password") 110 | |> validate_password(opts) 111 | end 112 | 113 | @doc """ 114 | Confirms the account by setting `confirmed_at`. 115 | """ 116 | def confirm_changeset(user) do 117 | now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second) 118 | change(user, confirmed_at: now) 119 | end 120 | 121 | @doc """ 122 | Verifies the password. 123 | 124 | If there is no user or the user doesn't have a password, we call 125 | `Bcrypt.no_user_verify/0` to avoid timing attacks. 126 | """ 127 | def valid_password?(%SqliteScale.Accounts.User{hashed_password: hashed_password}, password) 128 | when is_binary(hashed_password) and byte_size(password) > 0 do 129 | Bcrypt.verify_pass(password, hashed_password) 130 | end 131 | 132 | def valid_password?(_, _) do 133 | Bcrypt.no_user_verify() 134 | false 135 | end 136 | 137 | @doc """ 138 | Validates the current password otherwise adds an error to the changeset. 139 | """ 140 | def validate_current_password(changeset, password) do 141 | if valid_password?(changeset.data, password) do 142 | changeset 143 | else 144 | add_error(changeset, :current_password, "is not valid") 145 | end 146 | end 147 | end 148 | -------------------------------------------------------------------------------- /lib/sqlite_scale/accounts/user_notifier.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScale.Accounts.UserNotifier do 2 | import Swoosh.Email 3 | 4 | alias SqliteScale.Mailer 5 | 6 | # Delivers the email using the application mailer. 7 | defp deliver(recipient, subject, body) do 8 | email = 9 | new() 10 | |> to(recipient) 11 | |> from({"MyApp", "contact@example.com"}) 12 | |> subject(subject) 13 | |> text_body(body) 14 | 15 | with {:ok, _metadata} <- Mailer.deliver(email) do 16 | {:ok, email} 17 | end 18 | end 19 | 20 | @doc """ 21 | Deliver instructions to confirm account. 22 | """ 23 | def deliver_confirmation_instructions(user, url) do 24 | deliver(user.email, "Confirmation instructions", """ 25 | 26 | ============================== 27 | 28 | Hi #{user.email}, 29 | 30 | You can confirm your account by visiting the URL below: 31 | 32 | #{url} 33 | 34 | If you didn't create an account with us, please ignore this. 35 | 36 | ============================== 37 | """) 38 | end 39 | 40 | @doc """ 41 | Deliver instructions to reset a user password. 42 | """ 43 | def deliver_reset_password_instructions(user, url) do 44 | deliver(user.email, "Reset password instructions", """ 45 | 46 | ============================== 47 | 48 | Hi #{user.email}, 49 | 50 | You can reset your password by visiting the URL below: 51 | 52 | #{url} 53 | 54 | If you didn't request this change, please ignore this. 55 | 56 | ============================== 57 | """) 58 | end 59 | 60 | @doc """ 61 | Deliver instructions to update a user email. 62 | """ 63 | def deliver_update_email_instructions(user, url) do 64 | deliver(user.email, "Update email instructions", """ 65 | 66 | ============================== 67 | 68 | Hi #{user.email}, 69 | 70 | You can change your email by visiting the URL below: 71 | 72 | #{url} 73 | 74 | If you didn't request this change, please ignore this. 75 | 76 | ============================== 77 | """) 78 | end 79 | end 80 | -------------------------------------------------------------------------------- /lib/sqlite_scale/accounts/user_token.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScale.Accounts.UserToken do 2 | use Ecto.Schema 3 | import Ecto.Query 4 | 5 | @hash_algorithm :sha256 6 | @rand_size 32 7 | 8 | # It is very important to keep the reset password token expiry short, 9 | # since someone with access to the email may take over the account. 10 | @reset_password_validity_in_days 1 11 | @confirm_validity_in_days 7 12 | @change_email_validity_in_days 7 13 | @session_validity_in_days 60 14 | 15 | @primary_key {:id, :binary_id, autogenerate: true} 16 | @foreign_key_type :binary_id 17 | schema "users_tokens" do 18 | field :token, :binary 19 | field :context, :string 20 | field :sent_to, :string 21 | belongs_to :user, SqliteScale.Accounts.User 22 | 23 | timestamps(updated_at: false) 24 | end 25 | 26 | @doc """ 27 | Generates a token that will be stored in a signed place, 28 | such as session or cookie. As they are signed, those 29 | tokens do not need to be hashed. 30 | 31 | The reason why we store session tokens in the database, even 32 | though Phoenix already provides a session cookie, is because 33 | Phoenix' default session cookies are not persisted, they are 34 | simply signed and potentially encrypted. This means they are 35 | valid indefinitely, unless you change the signing/encryption 36 | salt. 37 | 38 | Therefore, storing them allows individual user 39 | sessions to be expired. The token system can also be extended 40 | to store additional data, such as the device used for logging in. 41 | You could then use this information to display all valid sessions 42 | and devices in the UI and allow users to explicitly expire any 43 | session they deem invalid. 44 | """ 45 | def build_session_token(user) do 46 | token = :crypto.strong_rand_bytes(@rand_size) 47 | {token, %SqliteScale.Accounts.UserToken{token: token, context: "session", user_id: user.id}} 48 | end 49 | 50 | @doc """ 51 | Checks if the token is valid and returns its underlying lookup query. 52 | 53 | The query returns the user found by the token, if any. 54 | 55 | The token is valid if it matches the value in the database and it has 56 | not expired (after @session_validity_in_days). 57 | """ 58 | def verify_session_token_query(token) do 59 | query = 60 | from token in token_and_context_query(token, "session"), 61 | join: user in assoc(token, :user), 62 | where: token.inserted_at > ago(@session_validity_in_days, "day"), 63 | select: user 64 | 65 | {:ok, query} 66 | end 67 | 68 | @doc """ 69 | Builds a token and its hash to be delivered to the user's email. 70 | 71 | The non-hashed token is sent to the user email while the 72 | hashed part is stored in the database. The original token cannot be reconstructed, 73 | which means anyone with read-only access to the database cannot directly use 74 | the token in the application to gain access. Furthermore, if the user changes 75 | their email in the system, the tokens sent to the previous email are no longer 76 | valid. 77 | 78 | Users can easily adapt the existing code to provide other types of delivery methods, 79 | for example, by phone numbers. 80 | """ 81 | def build_email_token(user, context) do 82 | build_hashed_token(user, context, user.email) 83 | end 84 | 85 | defp build_hashed_token(user, context, sent_to) do 86 | token = :crypto.strong_rand_bytes(@rand_size) 87 | hashed_token = :crypto.hash(@hash_algorithm, token) 88 | 89 | {Base.url_encode64(token, padding: false), 90 | %SqliteScale.Accounts.UserToken{ 91 | token: hashed_token, 92 | context: context, 93 | sent_to: sent_to, 94 | user_id: user.id 95 | }} 96 | end 97 | 98 | @doc """ 99 | Checks if the token is valid and returns its underlying lookup query. 100 | 101 | The query returns the user found by the token, if any. 102 | 103 | The given token is valid if it matches its hashed counterpart in the 104 | database and the user email has not changed. This function also checks 105 | if the token is being used within a certain period, depending on the 106 | context. The default contexts supported by this function are either 107 | "confirm", for account confirmation emails, and "reset_password", 108 | for resetting the password. For verifying requests to change the email, 109 | see `verify_change_email_token_query/2`. 110 | """ 111 | def verify_email_token_query(token, context) do 112 | case Base.url_decode64(token, padding: false) do 113 | {:ok, decoded_token} -> 114 | hashed_token = :crypto.hash(@hash_algorithm, decoded_token) 115 | days = days_for_context(context) 116 | 117 | query = 118 | from token in token_and_context_query(hashed_token, context), 119 | join: user in assoc(token, :user), 120 | where: token.inserted_at > ago(^days, "day") and token.sent_to == user.email, 121 | select: user 122 | 123 | {:ok, query} 124 | 125 | :error -> 126 | :error 127 | end 128 | end 129 | 130 | defp days_for_context("confirm"), do: @confirm_validity_in_days 131 | defp days_for_context("reset_password"), do: @reset_password_validity_in_days 132 | 133 | @doc """ 134 | Checks if the token is valid and returns its underlying lookup query. 135 | 136 | The query returns the user found by the token, if any. 137 | 138 | This is used to validate requests to change the user 139 | email. It is different from `verify_email_token_query/2` precisely because 140 | `verify_email_token_query/2` validates the email has not changed, which is 141 | the starting point by this function. 142 | 143 | The given token is valid if it matches its hashed counterpart in the 144 | database and if it has not expired (after @change_email_validity_in_days). 145 | The context must always start with "change:". 146 | """ 147 | def verify_change_email_token_query(token, "change:" <> _ = context) do 148 | case Base.url_decode64(token, padding: false) do 149 | {:ok, decoded_token} -> 150 | hashed_token = :crypto.hash(@hash_algorithm, decoded_token) 151 | 152 | query = 153 | from token in token_and_context_query(hashed_token, context), 154 | where: token.inserted_at > ago(@change_email_validity_in_days, "day") 155 | 156 | {:ok, query} 157 | 158 | :error -> 159 | :error 160 | end 161 | end 162 | 163 | @doc """ 164 | Returns the token struct for the given token value and context. 165 | """ 166 | def token_and_context_query(token, context) do 167 | from SqliteScale.Accounts.UserToken, where: [token: ^token, context: ^context] 168 | end 169 | 170 | @doc """ 171 | Gets all tokens for the given user for the given contexts. 172 | """ 173 | def user_and_contexts_query(user, :all) do 174 | from t in SqliteScale.Accounts.UserToken, where: t.user_id == ^user.id 175 | end 176 | 177 | def user_and_contexts_query(user, [_ | _] = contexts) do 178 | from t in SqliteScale.Accounts.UserToken, where: t.user_id == ^user.id and t.context in ^contexts 179 | end 180 | end 181 | -------------------------------------------------------------------------------- /lib/sqlite_scale/application.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScale.Application do 2 | # See https://hexdocs.pm/elixir/Application.html 3 | # for more information on OTP Applications 4 | @moduledoc false 5 | 6 | use Application 7 | 8 | @impl true 9 | def start(_type, _args) do 10 | children = [ 11 | # Start the Ecto repository 12 | SqliteScale.Repo, 13 | 14 | # Start the split SQLite supervision tree 15 | SqliteScale.DynamicRepoSupervisor, 16 | 17 | # Start the Telemetry supervisor 18 | SqliteScaleWeb.Telemetry, 19 | 20 | # Start the PubSub system 21 | {Phoenix.PubSub, name: SqliteScale.PubSub}, 22 | 23 | # Start the Endpoint (http/https) 24 | SqliteScaleWeb.Endpoint 25 | ] 26 | 27 | # See https://hexdocs.pm/elixir/Supervisor.html 28 | # for other strategies and supported options 29 | opts = [strategy: :one_for_one, name: SqliteScale.Supervisor] 30 | Supervisor.start_link(children, opts) 31 | end 32 | 33 | # Tell Phoenix to update the endpoint configuration 34 | # whenever the application is updated. 35 | @impl true 36 | def config_change(changed, _new, removed) do 37 | SqliteScaleWeb.Endpoint.config_change(changed, removed) 38 | :ok 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /lib/sqlite_scale/dynamic_repo_supervisor.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScale.DynamicRepoSupervisor do 2 | @moduledoc """ 3 | This supervision tree is used to start the registry 4 | and dynamic supervisor which handles each SQLite 5 | instance per user. 6 | """ 7 | 8 | use Supervisor 9 | 10 | alias SqliteScale.DynamicRepoSupervisor.RepoHydrator 11 | alias SqliteScale.DynamicRepoSupervisor.RepoRegistry 12 | alias SqliteScale.DynamicRepoSupervisor.RepoSupervisor 13 | 14 | def start_link(opts) do 15 | Supervisor.start_link(__MODULE__, opts, name: __MODULE__) 16 | end 17 | 18 | @impl true 19 | def init(opts) do 20 | children = [ 21 | RepoRegistry.child_spec(), 22 | RepoSupervisor, 23 | {RepoHydrator, opts} 24 | ] 25 | 26 | Supervisor.init(children, strategy: :one_for_all) 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /lib/sqlite_scale/dynamic_repo_supervisor/repo_hydrator.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScale.DynamicRepoSupervisor.RepoHydrator do 2 | @moduledoc """ 3 | This GenServer will start all of the repo processes dynamically 4 | based on what is in the priv dir. 5 | """ 6 | 7 | use GenServer 8 | 9 | alias SqliteScale.Accounts 10 | alias SqliteScale.Accounts.User 11 | alias SqliteScale.DynamicRepoSupervisor.RepoSupervisor 12 | 13 | def start_link(opts) do 14 | GenServer.start_link(__MODULE__, opts) 15 | end 16 | 17 | @impl true 18 | def init(opts) do 19 | Accounts.list_users() 20 | |> Enum.each(fn %User{} = user -> 21 | RepoSupervisor.add_repo_to_supervisor(user) 22 | end) 23 | 24 | :ignore 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /lib/sqlite_scale/dynamic_repo_supervisor/repo_registry.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScale.DynamicRepoSupervisor.RepoRegistry do 2 | @moduledoc """ 3 | This module is responsible for keeping track of all of the 4 | SQLite repos that are currently running. 5 | """ 6 | 7 | alias SqliteScale.Accounts.User 8 | 9 | @doc """ 10 | This function returns the child spec for this module so that it 11 | can easily be added to the supervision tree. 12 | """ 13 | def child_spec do 14 | Registry.child_spec( 15 | keys: :unique, 16 | name: __MODULE__, 17 | partitions: System.schedulers_online() 18 | ) 19 | end 20 | 21 | @doc """ 22 | This function looks up a repo process by its ID so that the 23 | processes can be then interacted with via its PID. 24 | """ 25 | def lookup_repo(%User{id: user_id}) do 26 | case Registry.lookup(__MODULE__, Ecto.UUID.cast!(user_id)) do 27 | [{repo_pid, _}] -> 28 | {:ok, repo_pid} 29 | 30 | [] -> 31 | {:error, :not_found} 32 | end 33 | end 34 | 35 | # The below functions are used under the hood when leveraging :via 36 | # to process PID lookup through a registry. 37 | 38 | @doc false 39 | def whereis_name(user_id) do 40 | case lookup_repo(user_id) do 41 | {:ok, repo_id} -> repo_id 42 | _ -> :undefined 43 | end 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /lib/sqlite_scale/dynamic_repo_supervisor/repo_supervisor.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScale.DynamicRepoSupervisor.RepoSupervisor do 2 | @moduledoc """ 3 | This module is responsible for starting the repos as 4 | they are needed. 5 | """ 6 | 7 | use DynamicSupervisor 8 | 9 | require Logger 10 | 11 | alias SqliteScale.Accounts.User 12 | alias SqliteScale.DynamicRepoSupervisor.RepoRegistry 13 | alias SqliteScale.UserRepo 14 | 15 | @doc """ 16 | This function is used to start the DynamicSupervisor in the supervision tree 17 | """ 18 | def start_link(opts) do 19 | DynamicSupervisor.start_link(__MODULE__, opts, name: __MODULE__) 20 | end 21 | 22 | @impl true 23 | def init(_opts) do 24 | DynamicSupervisor.init(strategy: :one_for_one) 25 | end 26 | 27 | @doc """ 28 | Start a new repo process and adds it to the DynamicSupervisor. 29 | """ 30 | def add_repo_to_supervisor(%User{} = user) do 31 | user_id = Ecto.UUID.cast!(user.id) 32 | 33 | database_file = 34 | :sqlite_scale 35 | |> :code.priv_dir() 36 | |> Path.join("/user_repo/db_files/#{user_id}/") 37 | |> Path.join("user_data.db") 38 | 39 | repo_opts = [ 40 | name: {:via, Registry, {RepoRegistry, user_id}}, 41 | database: database_file, 42 | pool_size: 5, 43 | show_sensitive_data_on_connection_error: true 44 | ] 45 | 46 | child_spec = %{ 47 | id: UserRepo, 48 | start: {UserRepo, :start_link, [repo_opts]}, 49 | restart: :permanent 50 | } 51 | 52 | {:ok, pid} = DynamicSupervisor.start_child(__MODULE__, child_spec) 53 | run_migrations(user, pid) 54 | 55 | pid 56 | end 57 | 58 | @doc """ 59 | Gets all of the PIDs upnder this DynamicSupervisor. 60 | """ 61 | def all_repo_pids do 62 | __MODULE__ 63 | |> DynamicSupervisor.which_children() 64 | |> Enum.reduce([], fn {_, repo_pid, _, _}, acc -> 65 | [repo_pid | acc] 66 | end) 67 | end 68 | 69 | defp run_migrations(user, repo_pid) do 70 | # Run any pending migrations 71 | user 72 | |> UserRepo.with_dynamic_repo(fn -> 73 | Ecto.Migrator.run(UserRepo, :up, all: true, dynamic_repo: repo_pid) 74 | end) 75 | |> case do 76 | [] -> 77 | Logger.info("The database did not have any pending migrations") 78 | 79 | migrations when is_list(migrations) -> 80 | Logger.info("The database for UserRepo has applied the following migrations: #{Enum.join(migrations, ", ")}") 81 | end 82 | end 83 | end 84 | -------------------------------------------------------------------------------- /lib/sqlite_scale/mailer.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScale.Mailer do 2 | use Swoosh.Mailer, otp_app: :sqlite_scale 3 | end 4 | -------------------------------------------------------------------------------- /lib/sqlite_scale/repo.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScale.Repo do 2 | use Ecto.Repo, 3 | otp_app: :sqlite_scale, 4 | adapter: Ecto.Adapters.SQLite3 5 | end 6 | -------------------------------------------------------------------------------- /lib/sqlite_scale/todo_items.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScale.TodoItems do 2 | @moduledoc """ 3 | The TodoItems context. 4 | """ 5 | 6 | import Ecto.Query, warn: false 7 | alias SqliteScale.UserRepo 8 | 9 | alias SqliteScale.TodoItems.TodoItem 10 | 11 | @doc """ 12 | Returns the list of todo_items. 13 | 14 | ## Examples 15 | 16 | iex> list_todo_items() 17 | [%TodoItem{}, ...] 18 | 19 | """ 20 | def list_todo_items(user) do 21 | UserRepo.with_dynamic_repo(user, fn -> 22 | UserRepo.all(TodoItem) 23 | end) 24 | end 25 | 26 | @doc """ 27 | Gets a single todo_item. 28 | 29 | Raises `Ecto.NoResultsError` if the Todo item does not exist. 30 | 31 | ## Examples 32 | 33 | iex> get_todo_item!(123) 34 | %TodoItem{} 35 | 36 | iex> get_todo_item!(456) 37 | ** (Ecto.NoResultsError) 38 | 39 | """ 40 | def get_todo_item!(user, id) do 41 | UserRepo.with_dynamic_repo(user, fn -> 42 | UserRepo.get!(TodoItem, id) 43 | end) 44 | end 45 | 46 | @doc """ 47 | Creates a todo_item. 48 | 49 | ## Examples 50 | 51 | iex> create_todo_item(%{field: value}) 52 | {:ok, %TodoItem{}} 53 | 54 | iex> create_todo_item(%{field: bad_value}) 55 | {:error, %Ecto.Changeset{}} 56 | 57 | """ 58 | def create_todo_item(user, attrs \\ %{}) do 59 | UserRepo.with_dynamic_repo(user, fn -> 60 | %TodoItem{} 61 | |> TodoItem.changeset(attrs) 62 | |> UserRepo.insert() 63 | end) 64 | end 65 | 66 | @doc """ 67 | Updates a todo_item. 68 | 69 | ## Examples 70 | 71 | iex> update_todo_item(todo_item, %{field: new_value}) 72 | {:ok, %TodoItem{}} 73 | 74 | iex> update_todo_item(todo_item, %{field: bad_value}) 75 | {:error, %Ecto.Changeset{}} 76 | 77 | """ 78 | def update_todo_item(user, %TodoItem{} = todo_item, attrs) do 79 | UserRepo.with_dynamic_repo(user, fn -> 80 | todo_item 81 | |> TodoItem.changeset(attrs) 82 | |> UserRepo.update() 83 | end) 84 | end 85 | 86 | @doc """ 87 | Deletes a todo_item. 88 | 89 | ## Examples 90 | 91 | iex> delete_todo_item(todo_item) 92 | {:ok, %TodoItem{}} 93 | 94 | iex> delete_todo_item(todo_item) 95 | {:error, %Ecto.Changeset{}} 96 | 97 | """ 98 | def delete_todo_item(user, %TodoItem{} = todo_item) do 99 | UserRepo.with_dynamic_repo(user, fn -> 100 | UserRepo.delete(todo_item) 101 | end) 102 | end 103 | 104 | @doc """ 105 | Returns an `%Ecto.Changeset{}` for tracking todo_item changes. 106 | 107 | ## Examples 108 | 109 | iex> change_todo_item(todo_item) 110 | %Ecto.Changeset{data: %TodoItem{}} 111 | 112 | """ 113 | def change_todo_item(%TodoItem{} = todo_item, attrs \\ %{}) do 114 | TodoItem.changeset(todo_item, attrs) 115 | end 116 | end 117 | -------------------------------------------------------------------------------- /lib/sqlite_scale/todo_items/todo_item.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScale.TodoItems.TodoItem do 2 | @moduledoc """ 3 | The todo item ecto schema 4 | """ 5 | 6 | use Ecto.Schema 7 | 8 | import Ecto.Changeset 9 | 10 | @primary_key {:id, :binary_id, autogenerate: true} 11 | @foreign_key_type :binary_id 12 | schema "todo_items" do 13 | field :item, :string 14 | 15 | timestamps() 16 | end 17 | 18 | @doc false 19 | def changeset(todo_item, attrs) do 20 | todo_item 21 | |> cast(attrs, [:item]) 22 | |> validate_required([:item]) 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /lib/sqlite_scale/user_repo.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScale.UserRepo do 2 | use Ecto.Repo, 3 | otp_app: :sqlite_scale, 4 | adapter: Ecto.Adapters.SQLite3, 5 | database: nil 6 | 7 | require Logger 8 | 9 | alias SqliteScale.Accounts.User 10 | alias SqliteScale.DynamicRepoSupervisor.RepoRegistry 11 | 12 | def with_dynamic_repo(%User{} = user, callback) do 13 | with {:ok, repo} <- RepoRegistry.lookup_repo(user) do 14 | try do 15 | __MODULE__.put_dynamic_repo(repo) 16 | callback.() 17 | after 18 | __MODULE__.put_dynamic_repo(nil) 19 | end 20 | else 21 | error -> 22 | Logger.warning("Failed to get UserRepo for user: #{inspect(user)}") 23 | end 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScaleWeb do 2 | @moduledoc """ 3 | The entrypoint for defining your web interface, such 4 | as controllers, views, channels and so on. 5 | 6 | This can be used in your application as: 7 | 8 | use SqliteScaleWeb, :controller 9 | use SqliteScaleWeb, :view 10 | 11 | The definitions below will be executed for every view, 12 | controller, etc, so keep them short and clean, focused 13 | on imports, uses and aliases. 14 | 15 | Do NOT define functions inside the quoted expressions 16 | below. Instead, define any helper function in modules 17 | and import those modules here. 18 | """ 19 | 20 | def controller do 21 | quote do 22 | use Phoenix.Controller, namespace: SqliteScaleWeb 23 | 24 | import Plug.Conn 25 | import SqliteScaleWeb.Gettext 26 | alias SqliteScaleWeb.Router.Helpers, as: Routes 27 | end 28 | end 29 | 30 | def view do 31 | quote do 32 | use Phoenix.View, 33 | root: "lib/sqlite_scale_web/templates", 34 | namespace: SqliteScaleWeb 35 | 36 | # Import convenience functions from controllers 37 | import Phoenix.Controller, 38 | only: [get_flash: 1, get_flash: 2, view_module: 1, view_template: 1] 39 | 40 | # Include shared imports and aliases for views 41 | unquote(view_helpers()) 42 | end 43 | end 44 | 45 | def live_view do 46 | quote do 47 | use Phoenix.LiveView, 48 | layout: {SqliteScaleWeb.LayoutView, "live.html"} 49 | 50 | unquote(view_helpers()) 51 | end 52 | end 53 | 54 | def live_component do 55 | quote do 56 | use Phoenix.LiveComponent 57 | 58 | unquote(view_helpers()) 59 | end 60 | end 61 | 62 | def component do 63 | quote do 64 | use Phoenix.Component 65 | 66 | unquote(view_helpers()) 67 | end 68 | end 69 | 70 | def router do 71 | quote do 72 | use Phoenix.Router 73 | 74 | import Plug.Conn 75 | import Phoenix.Controller 76 | import Phoenix.LiveView.Router 77 | end 78 | end 79 | 80 | def channel do 81 | quote do 82 | use Phoenix.Channel 83 | import SqliteScaleWeb.Gettext 84 | end 85 | end 86 | 87 | defp view_helpers do 88 | quote do 89 | # Use all HTML functionality (forms, tags, etc) 90 | use Phoenix.HTML 91 | 92 | # Import LiveView and .heex helpers (live_render, live_patch, <.form>, etc) 93 | import Phoenix.LiveView.Helpers 94 | 95 | # Import basic rendering functionality (render, render_layout, etc) 96 | import Phoenix.View 97 | 98 | import SqliteScaleWeb.ErrorHelpers 99 | import SqliteScaleWeb.Gettext 100 | alias SqliteScaleWeb.Router.Helpers, as: Routes 101 | end 102 | end 103 | 104 | @doc """ 105 | When used, dispatch to the appropriate controller/view/etc. 106 | """ 107 | defmacro __using__(which) when is_atom(which) do 108 | apply(__MODULE__, which, []) 109 | end 110 | end 111 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/controllers/page_controller.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScaleWeb.PageController do 2 | use SqliteScaleWeb, :controller 3 | 4 | def index(conn, _params) do 5 | render(conn, "index.html") 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/controllers/todo_item_controller.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScaleWeb.TodoItemController do 2 | use SqliteScaleWeb, :controller 3 | 4 | alias SqliteScale.TodoItems 5 | alias SqliteScale.TodoItems.TodoItem 6 | 7 | def index(conn, _params) do 8 | todo_items = TodoItems.list_todo_items(conn.assigns.current_user) 9 | render(conn, "index.html", todo_items: todo_items) 10 | end 11 | 12 | def new(conn, _params) do 13 | changeset = TodoItems.change_todo_item(%TodoItem{}) 14 | render(conn, "new.html", changeset: changeset) 15 | end 16 | 17 | def create(conn, %{"todo_item" => todo_item_params}) do 18 | case TodoItems.create_todo_item(conn.assigns.current_user, todo_item_params) do 19 | {:ok, todo_item} -> 20 | conn 21 | |> put_flash(:info, "Todo item created successfully.") 22 | |> redirect(to: Routes.todo_item_path(conn, :show, todo_item)) 23 | 24 | {:error, %Ecto.Changeset{} = changeset} -> 25 | render(conn, "new.html", changeset: changeset) 26 | end 27 | end 28 | 29 | def show(conn, %{"id" => id}) do 30 | todo_item = TodoItems.get_todo_item!(conn.assigns.current_user, id) 31 | render(conn, "show.html", todo_item: todo_item) 32 | end 33 | 34 | def edit(conn, %{"id" => id}) do 35 | todo_item = TodoItems.get_todo_item!(conn.assigns.current_user, id) 36 | changeset = TodoItems.change_todo_item(todo_item) 37 | render(conn, "edit.html", todo_item: todo_item, changeset: changeset) 38 | end 39 | 40 | def update(conn, %{"id" => id, "todo_item" => todo_item_params}) do 41 | todo_item = TodoItems.get_todo_item!(conn.assigns.current_user, id) 42 | 43 | case TodoItems.update_todo_item(conn.assigns.current_user, todo_item, todo_item_params) do 44 | {:ok, todo_item} -> 45 | conn 46 | |> put_flash(:info, "Todo item updated successfully.") 47 | |> redirect(to: Routes.todo_item_path(conn, :show, todo_item)) 48 | 49 | {:error, %Ecto.Changeset{} = changeset} -> 50 | render(conn, "edit.html", todo_item: todo_item, changeset: changeset) 51 | end 52 | end 53 | 54 | def delete(conn, %{"id" => id}) do 55 | todo_item = TodoItems.get_todo_item!(conn.assigns.current_user, id) 56 | {:ok, _todo_item} = TodoItems.delete_todo_item(conn.assigns.current_user, todo_item) 57 | 58 | conn 59 | |> put_flash(:info, "Todo item deleted successfully.") 60 | |> redirect(to: Routes.todo_item_path(conn, :index)) 61 | end 62 | end 63 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/controllers/user_auth.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScaleWeb.UserAuth do 2 | import Plug.Conn 3 | import Phoenix.Controller 4 | 5 | alias SqliteScale.Accounts 6 | alias SqliteScaleWeb.Router.Helpers, as: Routes 7 | 8 | # Make the remember me cookie valid for 60 days. 9 | # If you want bump or reduce this value, also change 10 | # the token expiry itself in UserToken. 11 | @max_age 60 * 60 * 24 * 60 12 | @remember_me_cookie "_sqlite_scale_web_user_remember_me" 13 | @remember_me_options [sign: true, max_age: @max_age, same_site: "Lax"] 14 | 15 | @doc """ 16 | Logs the user in. 17 | 18 | It renews the session ID and clears the whole session 19 | to avoid fixation attacks. See the renew_session 20 | function to customize this behaviour. 21 | 22 | It also sets a `:live_socket_id` key in the session, 23 | so LiveView sessions are identified and automatically 24 | disconnected on log out. The line can be safely removed 25 | if you are not using LiveView. 26 | """ 27 | def log_in_user(conn, user, params \\ %{}) do 28 | token = Accounts.generate_user_session_token(user) 29 | user_return_to = get_session(conn, :user_return_to) 30 | 31 | conn 32 | |> renew_session() 33 | |> put_session(:user_token, token) 34 | |> put_session(:live_socket_id, "users_sessions:#{Base.url_encode64(token)}") 35 | |> maybe_write_remember_me_cookie(token, params) 36 | |> redirect(to: user_return_to || signed_in_path(conn)) 37 | end 38 | 39 | defp maybe_write_remember_me_cookie(conn, token, %{"remember_me" => "true"}) do 40 | put_resp_cookie(conn, @remember_me_cookie, token, @remember_me_options) 41 | end 42 | 43 | defp maybe_write_remember_me_cookie(conn, _token, _params) do 44 | conn 45 | end 46 | 47 | # This function renews the session ID and erases the whole 48 | # session to avoid fixation attacks. If there is any data 49 | # in the session you may want to preserve after log in/log out, 50 | # you must explicitly fetch the session data before clearing 51 | # and then immediately set it after clearing, for example: 52 | # 53 | # defp renew_session(conn) do 54 | # preferred_locale = get_session(conn, :preferred_locale) 55 | # 56 | # conn 57 | # |> configure_session(renew: true) 58 | # |> clear_session() 59 | # |> put_session(:preferred_locale, preferred_locale) 60 | # end 61 | # 62 | defp renew_session(conn) do 63 | conn 64 | |> configure_session(renew: true) 65 | |> clear_session() 66 | end 67 | 68 | @doc """ 69 | Logs the user out. 70 | 71 | It clears all session data for safety. See renew_session. 72 | """ 73 | def log_out_user(conn) do 74 | user_token = get_session(conn, :user_token) 75 | user_token && Accounts.delete_session_token(user_token) 76 | 77 | if live_socket_id = get_session(conn, :live_socket_id) do 78 | SqliteScaleWeb.Endpoint.broadcast(live_socket_id, "disconnect", %{}) 79 | end 80 | 81 | conn 82 | |> renew_session() 83 | |> delete_resp_cookie(@remember_me_cookie) 84 | |> redirect(to: "/") 85 | end 86 | 87 | @doc """ 88 | Authenticates the user by looking into the session 89 | and remember me token. 90 | """ 91 | def fetch_current_user(conn, _opts) do 92 | {user_token, conn} = ensure_user_token(conn) 93 | user = user_token && Accounts.get_user_by_session_token(user_token) 94 | assign(conn, :current_user, user) 95 | end 96 | 97 | defp ensure_user_token(conn) do 98 | if user_token = get_session(conn, :user_token) do 99 | {user_token, conn} 100 | else 101 | conn = fetch_cookies(conn, signed: [@remember_me_cookie]) 102 | 103 | if user_token = conn.cookies[@remember_me_cookie] do 104 | {user_token, put_session(conn, :user_token, user_token)} 105 | else 106 | {nil, conn} 107 | end 108 | end 109 | end 110 | 111 | @doc """ 112 | Used for routes that require the user to not be authenticated. 113 | """ 114 | def redirect_if_user_is_authenticated(conn, _opts) do 115 | if conn.assigns[:current_user] do 116 | conn 117 | |> redirect(to: signed_in_path(conn)) 118 | |> halt() 119 | else 120 | conn 121 | end 122 | end 123 | 124 | @doc """ 125 | Used for routes that require the user to be authenticated. 126 | 127 | If you want to enforce the user email is confirmed before 128 | they use the application at all, here would be a good place. 129 | """ 130 | def require_authenticated_user(conn, _opts) do 131 | if conn.assigns[:current_user] do 132 | conn 133 | else 134 | conn 135 | |> put_flash(:error, "You must log in to access this page.") 136 | |> maybe_store_return_to() 137 | |> redirect(to: Routes.user_session_path(conn, :new)) 138 | |> halt() 139 | end 140 | end 141 | 142 | defp maybe_store_return_to(%{method: "GET"} = conn) do 143 | put_session(conn, :user_return_to, current_path(conn)) 144 | end 145 | 146 | defp maybe_store_return_to(conn), do: conn 147 | 148 | defp signed_in_path(_conn), do: "/" 149 | end 150 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/controllers/user_confirmation_controller.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScaleWeb.UserConfirmationController do 2 | use SqliteScaleWeb, :controller 3 | 4 | alias SqliteScale.Accounts 5 | 6 | def new(conn, _params) do 7 | render(conn, "new.html") 8 | end 9 | 10 | def create(conn, %{"user" => %{"email" => email}}) do 11 | if user = Accounts.get_user_by_email(email) do 12 | Accounts.deliver_user_confirmation_instructions( 13 | user, 14 | &Routes.user_confirmation_url(conn, :edit, &1) 15 | ) 16 | end 17 | 18 | conn 19 | |> put_flash( 20 | :info, 21 | "If your email is in our system and it has not been confirmed yet, " <> 22 | "you will receive an email with instructions shortly." 23 | ) 24 | |> redirect(to: "/") 25 | end 26 | 27 | def edit(conn, %{"token" => token}) do 28 | render(conn, "edit.html", token: token) 29 | end 30 | 31 | # Do not log in the user after confirmation to avoid a 32 | # leaked token giving the user access to the account. 33 | def update(conn, %{"token" => token}) do 34 | case Accounts.confirm_user(token) do 35 | {:ok, _} -> 36 | conn 37 | |> put_flash(:info, "User confirmed successfully.") 38 | |> redirect(to: "/") 39 | 40 | :error -> 41 | # If there is a current user and the account was already confirmed, 42 | # then odds are that the confirmation link was already visited, either 43 | # by some automation or by the user themselves, so we redirect without 44 | # a warning message. 45 | case conn.assigns do 46 | %{current_user: %{confirmed_at: confirmed_at}} when not is_nil(confirmed_at) -> 47 | redirect(conn, to: "/") 48 | 49 | %{} -> 50 | conn 51 | |> put_flash(:error, "User confirmation link is invalid or it has expired.") 52 | |> redirect(to: "/") 53 | end 54 | end 55 | end 56 | end 57 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/controllers/user_registration_controller.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScaleWeb.UserRegistrationController do 2 | use SqliteScaleWeb, :controller 3 | 4 | alias SqliteScale.Accounts 5 | alias SqliteScale.Accounts.User 6 | alias SqliteScaleWeb.UserAuth 7 | 8 | def new(conn, _params) do 9 | changeset = Accounts.change_user_registration(%User{}) 10 | render(conn, "new.html", changeset: changeset) 11 | end 12 | 13 | def create(conn, %{"user" => user_params}) do 14 | case Accounts.register_user(user_params) do 15 | {:ok, user} -> 16 | {:ok, _} = 17 | Accounts.deliver_user_confirmation_instructions( 18 | user, 19 | &Routes.user_confirmation_url(conn, :edit, &1) 20 | ) 21 | 22 | conn 23 | |> put_flash(:info, "User created successfully.") 24 | |> UserAuth.log_in_user(user) 25 | 26 | {:error, %Ecto.Changeset{} = changeset} -> 27 | render(conn, "new.html", changeset: changeset) 28 | end 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/controllers/user_reset_password_controller.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScaleWeb.UserResetPasswordController do 2 | use SqliteScaleWeb, :controller 3 | 4 | alias SqliteScale.Accounts 5 | 6 | plug :get_user_by_reset_password_token when action in [:edit, :update] 7 | 8 | def new(conn, _params) do 9 | render(conn, "new.html") 10 | end 11 | 12 | def create(conn, %{"user" => %{"email" => email}}) do 13 | if user = Accounts.get_user_by_email(email) do 14 | Accounts.deliver_user_reset_password_instructions( 15 | user, 16 | &Routes.user_reset_password_url(conn, :edit, &1) 17 | ) 18 | end 19 | 20 | conn 21 | |> put_flash( 22 | :info, 23 | "If your email is in our system, you will receive instructions to reset your password shortly." 24 | ) 25 | |> redirect(to: "/") 26 | end 27 | 28 | def edit(conn, _params) do 29 | render(conn, "edit.html", changeset: Accounts.change_user_password(conn.assigns.user)) 30 | end 31 | 32 | # Do not log in the user after reset password to avoid a 33 | # leaked token giving the user access to the account. 34 | def update(conn, %{"user" => user_params}) do 35 | case Accounts.reset_user_password(conn.assigns.user, user_params) do 36 | {:ok, _} -> 37 | conn 38 | |> put_flash(:info, "Password reset successfully.") 39 | |> redirect(to: Routes.user_session_path(conn, :new)) 40 | 41 | {:error, changeset} -> 42 | render(conn, "edit.html", changeset: changeset) 43 | end 44 | end 45 | 46 | defp get_user_by_reset_password_token(conn, _opts) do 47 | %{"token" => token} = conn.params 48 | 49 | if user = Accounts.get_user_by_reset_password_token(token) do 50 | conn |> assign(:user, user) |> assign(:token, token) 51 | else 52 | conn 53 | |> put_flash(:error, "Reset password link is invalid or it has expired.") 54 | |> redirect(to: "/") 55 | |> halt() 56 | end 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/controllers/user_session_controller.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScaleWeb.UserSessionController do 2 | use SqliteScaleWeb, :controller 3 | 4 | alias SqliteScale.Accounts 5 | alias SqliteScaleWeb.UserAuth 6 | 7 | def new(conn, _params) do 8 | render(conn, "new.html", error_message: nil) 9 | end 10 | 11 | def create(conn, %{"user" => user_params}) do 12 | %{"email" => email, "password" => password} = user_params 13 | 14 | if user = Accounts.get_user_by_email_and_password(email, password) do 15 | UserAuth.log_in_user(conn, user, user_params) 16 | else 17 | # In order to prevent user enumeration attacks, don't disclose whether the email is registered. 18 | render(conn, "new.html", error_message: "Invalid email or password") 19 | end 20 | end 21 | 22 | def delete(conn, _params) do 23 | conn 24 | |> put_flash(:info, "Logged out successfully.") 25 | |> UserAuth.log_out_user() 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/controllers/user_settings_controller.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScaleWeb.UserSettingsController do 2 | use SqliteScaleWeb, :controller 3 | 4 | alias SqliteScale.Accounts 5 | alias SqliteScaleWeb.UserAuth 6 | 7 | plug :assign_email_and_password_changesets 8 | 9 | def edit(conn, _params) do 10 | render(conn, "edit.html") 11 | end 12 | 13 | def update(conn, %{"action" => "update_email"} = params) do 14 | %{"current_password" => password, "user" => user_params} = params 15 | user = conn.assigns.current_user 16 | 17 | case Accounts.apply_user_email(user, password, user_params) do 18 | {:ok, applied_user} -> 19 | Accounts.deliver_update_email_instructions( 20 | applied_user, 21 | user.email, 22 | &Routes.user_settings_url(conn, :confirm_email, &1) 23 | ) 24 | 25 | conn 26 | |> put_flash( 27 | :info, 28 | "A link to confirm your email change has been sent to the new address." 29 | ) 30 | |> redirect(to: Routes.user_settings_path(conn, :edit)) 31 | 32 | {:error, changeset} -> 33 | render(conn, "edit.html", email_changeset: changeset) 34 | end 35 | end 36 | 37 | def update(conn, %{"action" => "update_password"} = params) do 38 | %{"current_password" => password, "user" => user_params} = params 39 | user = conn.assigns.current_user 40 | 41 | case Accounts.update_user_password(user, password, user_params) do 42 | {:ok, user} -> 43 | conn 44 | |> put_flash(:info, "Password updated successfully.") 45 | |> put_session(:user_return_to, Routes.user_settings_path(conn, :edit)) 46 | |> UserAuth.log_in_user(user) 47 | 48 | {:error, changeset} -> 49 | render(conn, "edit.html", password_changeset: changeset) 50 | end 51 | end 52 | 53 | def confirm_email(conn, %{"token" => token}) do 54 | case Accounts.update_user_email(conn.assigns.current_user, token) do 55 | :ok -> 56 | conn 57 | |> put_flash(:info, "Email changed successfully.") 58 | |> redirect(to: Routes.user_settings_path(conn, :edit)) 59 | 60 | :error -> 61 | conn 62 | |> put_flash(:error, "Email change link is invalid or it has expired.") 63 | |> redirect(to: Routes.user_settings_path(conn, :edit)) 64 | end 65 | end 66 | 67 | defp assign_email_and_password_changesets(conn, _opts) do 68 | user = conn.assigns.current_user 69 | 70 | conn 71 | |> assign(:email_changeset, Accounts.change_user_email(user)) 72 | |> assign(:password_changeset, Accounts.change_user_password(user)) 73 | end 74 | end 75 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/endpoint.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScaleWeb.Endpoint do 2 | use Phoenix.Endpoint, otp_app: :sqlite_scale 3 | 4 | # The session will be stored in the cookie and signed, 5 | # this means its contents can be read but not tampered with. 6 | # Set :encryption_salt if you would also like to encrypt it. 7 | @session_options [ 8 | store: :cookie, 9 | key: "_sqlite_scale_key", 10 | signing_salt: "IGw/Wshm" 11 | ] 12 | 13 | socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]] 14 | 15 | # Serve at "/" the static files from "priv/static" directory. 16 | # 17 | # You should set gzip to true if you are running phx.digest 18 | # when deploying your static files in production. 19 | plug Plug.Static, 20 | at: "/", 21 | from: :sqlite_scale, 22 | gzip: false, 23 | only: ~w(assets fonts images favicon.ico robots.txt) 24 | 25 | # Code reloading can be explicitly enabled under the 26 | # :code_reloader configuration of your endpoint. 27 | if code_reloading? do 28 | socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket 29 | plug Phoenix.LiveReloader 30 | plug Phoenix.CodeReloader 31 | plug Phoenix.Ecto.CheckRepoStatus, otp_app: :sqlite_scale 32 | end 33 | 34 | plug Phoenix.LiveDashboard.RequestLogger, 35 | param_key: "request_logger", 36 | cookie_key: "request_logger" 37 | 38 | plug Plug.RequestId 39 | plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint] 40 | 41 | plug Plug.Parsers, 42 | parsers: [:urlencoded, :multipart, :json], 43 | pass: ["*/*"], 44 | json_decoder: Phoenix.json_library() 45 | 46 | plug Plug.MethodOverride 47 | plug Plug.Head 48 | plug Plug.Session, @session_options 49 | plug SqliteScaleWeb.Router 50 | end 51 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/gettext.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScaleWeb.Gettext do 2 | @moduledoc """ 3 | A module providing Internationalization with a gettext-based API. 4 | 5 | By using [Gettext](https://hexdocs.pm/gettext), 6 | your module gains a set of macros for translations, for example: 7 | 8 | import SqliteScaleWeb.Gettext 9 | 10 | # Simple translation 11 | gettext("Here is the string to translate") 12 | 13 | # Plural translation 14 | ngettext("Here is the string to translate", 15 | "Here are the strings to translate", 16 | 3) 17 | 18 | # Domain-based translation 19 | dgettext("errors", "Here is the error message to translate") 20 | 21 | See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage. 22 | """ 23 | use Gettext, otp_app: :sqlite_scale 24 | end 25 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/router.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScaleWeb.Router do 2 | use SqliteScaleWeb, :router 3 | 4 | import SqliteScaleWeb.UserAuth 5 | 6 | pipeline :browser do 7 | plug :accepts, ["html"] 8 | plug :fetch_session 9 | plug :fetch_live_flash 10 | plug :put_root_layout, {SqliteScaleWeb.LayoutView, :root} 11 | plug :protect_from_forgery 12 | plug :put_secure_browser_headers 13 | plug :fetch_current_user 14 | end 15 | 16 | pipeline :api do 17 | plug :accepts, ["json"] 18 | end 19 | 20 | scope "/", SqliteScaleWeb do 21 | pipe_through :browser 22 | 23 | get "/", PageController, :index 24 | end 25 | 26 | # Other scopes may use custom stacks. 27 | # scope "/api", SqliteScaleWeb do 28 | # pipe_through :api 29 | # end 30 | 31 | # Enables LiveDashboard only for development 32 | # 33 | # If you want to use the LiveDashboard in production, you should put 34 | # it behind authentication and allow only admins to access it. 35 | # If your application does not have an admins-only section yet, 36 | # you can use Plug.BasicAuth to set up some basic authentication 37 | # as long as you are also using SSL (which you should anyway). 38 | if Mix.env() in [:dev, :test] do 39 | import Phoenix.LiveDashboard.Router 40 | 41 | scope "/" do 42 | pipe_through :browser 43 | 44 | live_dashboard "/dashboard", metrics: SqliteScaleWeb.Telemetry 45 | end 46 | end 47 | 48 | # Enables the Swoosh mailbox preview in development. 49 | # 50 | # Note that preview only shows emails that were sent by the same 51 | # node running the Phoenix server. 52 | if Mix.env() == :dev do 53 | scope "/dev" do 54 | pipe_through :browser 55 | 56 | forward "/mailbox", Plug.Swoosh.MailboxPreview 57 | end 58 | end 59 | 60 | ## Authentication routes 61 | 62 | scope "/", SqliteScaleWeb do 63 | pipe_through [:browser, :redirect_if_user_is_authenticated] 64 | 65 | get "/users/register", UserRegistrationController, :new 66 | post "/users/register", UserRegistrationController, :create 67 | get "/users/log_in", UserSessionController, :new 68 | post "/users/log_in", UserSessionController, :create 69 | get "/users/reset_password", UserResetPasswordController, :new 70 | post "/users/reset_password", UserResetPasswordController, :create 71 | get "/users/reset_password/:token", UserResetPasswordController, :edit 72 | put "/users/reset_password/:token", UserResetPasswordController, :update 73 | end 74 | 75 | scope "/", SqliteScaleWeb do 76 | pipe_through [:browser, :require_authenticated_user] 77 | 78 | get "/users/settings", UserSettingsController, :edit 79 | put "/users/settings", UserSettingsController, :update 80 | get "/users/settings/confirm_email/:token", UserSettingsController, :confirm_email 81 | 82 | resources "/todo_items", TodoItemController 83 | end 84 | 85 | scope "/", SqliteScaleWeb do 86 | pipe_through [:browser] 87 | 88 | delete "/users/log_out", UserSessionController, :delete 89 | get "/users/confirm", UserConfirmationController, :new 90 | post "/users/confirm", UserConfirmationController, :create 91 | get "/users/confirm/:token", UserConfirmationController, :edit 92 | post "/users/confirm/:token", UserConfirmationController, :update 93 | end 94 | end 95 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/telemetry.ex: -------------------------------------------------------------------------------- 1 | defmodule SqliteScaleWeb.Telemetry do 2 | use Supervisor 3 | import Telemetry.Metrics 4 | 5 | def start_link(arg) do 6 | Supervisor.start_link(__MODULE__, arg, name: __MODULE__) 7 | end 8 | 9 | @impl true 10 | def init(_arg) do 11 | children = [ 12 | # Telemetry poller will execute the given period measurements 13 | # every 10_000ms. Learn more here: https://hexdocs.pm/telemetry_metrics 14 | {:telemetry_poller, measurements: periodic_measurements(), period: 10_000} 15 | # Add reporters as children of your supervision tree. 16 | # {Telemetry.Metrics.ConsoleReporter, metrics: metrics()} 17 | ] 18 | 19 | Supervisor.init(children, strategy: :one_for_one) 20 | end 21 | 22 | def metrics do 23 | [ 24 | # Phoenix Metrics 25 | summary("phoenix.endpoint.stop.duration", 26 | unit: {:native, :millisecond} 27 | ), 28 | summary("phoenix.router_dispatch.stop.duration", 29 | tags: [:route], 30 | unit: {:native, :millisecond} 31 | ), 32 | 33 | # Database Metrics 34 | summary("sqlite_scale.repo.query.total_time", 35 | unit: {:native, :millisecond}, 36 | description: "The sum of the other measurements" 37 | ), 38 | summary("sqlite_scale.repo.query.decode_time", 39 | unit: {:native, :millisecond}, 40 | description: "The time spent decoding the data received from the database" 41 | ), 42 | summary("sqlite_scale.repo.query.query_time", 43 | unit: {:native, :millisecond}, 44 | description: "The time spent executing the query" 45 | ), 46 | summary("sqlite_scale.repo.query.queue_time", 47 | unit: {:native, :millisecond}, 48 | description: "The time spent waiting for a database connection" 49 | ), 50 | summary("sqlite_scale.repo.query.idle_time", 51 | unit: {:native, :millisecond}, 52 | description: 53 | "The time the connection spent waiting before being checked out for the query" 54 | ), 55 | 56 | # VM Metrics 57 | summary("vm.memory.total", unit: {:byte, :kilobyte}), 58 | summary("vm.total_run_queue_lengths.total"), 59 | summary("vm.total_run_queue_lengths.cpu"), 60 | summary("vm.total_run_queue_lengths.io") 61 | ] 62 | end 63 | 64 | defp periodic_measurements do 65 | [ 66 | # A module, function and arguments to be invoked periodically. 67 | # This function must call :telemetry.execute/3 and a metric must be added above. 68 | # {SqliteScaleWeb, :count_users, []} 69 | ] 70 | end 71 | end 72 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/templates/layout/_user_menu.html.heex: -------------------------------------------------------------------------------- 1 |
<%= get_flash(@conn, :info) %>
3 |<%= get_flash(@conn, :error) %>
4 | <%= @inner_content %> 5 |<%= live_flash(@flash, :info) %>
5 | 6 |<%= live_flash(@flash, :error) %>
9 | 10 | <%= @inner_content %> 11 |Peace of mind from prototype to production
4 |Oops, something went wrong! Please check the errors below.
5 |Item | 7 | 8 |9 | |
---|---|
<%= todo_item.item %> | 15 | 16 |17 | <%= link "Show", to: Routes.todo_item_path(@conn, :show, todo_item) %> 18 | <%= link "Edit", to: Routes.todo_item_path(@conn, :edit, todo_item) %> 19 | <%= link "Delete", to: Routes.todo_item_path(@conn, :delete, todo_item), method: :delete, data: [confirm: "Are you sure?"] %> 20 | | 21 |
10 | <%= link "Register", to: Routes.user_registration_path(@conn, :new) %> | 11 | <%= link "Log in", to: Routes.user_session_path(@conn, :new) %> 12 |
13 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/templates/user_confirmation/new.html.heex: -------------------------------------------------------------------------------- 1 |13 | <%= link "Register", to: Routes.user_registration_path(@conn, :new) %> | 14 | <%= link "Log in", to: Routes.user_session_path(@conn, :new) %> 15 |
16 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/templates/user_registration/new.html.heex: -------------------------------------------------------------------------------- 1 |Oops, something went wrong! Please check the errors below.
7 |24 | <%= link "Log in", to: Routes.user_session_path(@conn, :new) %> | 25 | <%= link "Forgot your password?", to: Routes.user_reset_password_path(@conn, :new) %> 26 |
27 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/templates/user_reset_password/edit.html.heex: -------------------------------------------------------------------------------- 1 |Oops, something went wrong! Please check the errors below.
7 |24 | <%= link "Register", to: Routes.user_registration_path(@conn, :new) %> | 25 | <%= link "Log in", to: Routes.user_session_path(@conn, :new) %> 26 |
27 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/templates/user_reset_password/new.html.heex: -------------------------------------------------------------------------------- 1 |13 | <%= link "Register", to: Routes.user_registration_path(@conn, :new) %> | 14 | <%= link "Log in", to: Routes.user_session_path(@conn, :new) %> 15 |
16 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/templates/user_session/new.html.heex: -------------------------------------------------------------------------------- 1 |<%= @error_message %>
7 |25 | <%= link "Register", to: Routes.user_registration_path(@conn, :new) %> | 26 | <%= link "Forgot your password?", to: Routes.user_reset_password_path(@conn, :new) %> 27 |
28 | -------------------------------------------------------------------------------- /lib/sqlite_scale_web/templates/user_settings/edit.html.heex: -------------------------------------------------------------------------------- 1 |Oops, something went wrong! Please check the errors below.
9 |Oops, something went wrong! Please check the errors below.
33 |