├── .gitattributes ├── .github └── workflows │ └── run_specs.yml ├── .gitignore ├── .ruby-version ├── Gemfile ├── Gemfile.lock ├── Procfile ├── README.md ├── Rakefile ├── app ├── channels │ └── application_cable │ │ ├── channel.rb │ │ └── connection.rb ├── controllers │ ├── api │ │ └── v1 │ │ │ ├── comments_controller.rb │ │ │ ├── posts_controller.rb │ │ │ └── users_controller.rb │ ├── application_controller.rb │ ├── concerns │ │ └── .keep │ ├── confirmations_controller.rb │ ├── passwords_controller.rb │ ├── ping_controller.rb │ ├── registrations_controller.rb │ └── sessions_controller.rb ├── jobs │ └── application_job.rb ├── mailers │ └── application_mailer.rb ├── models │ ├── allowlisted_jwt.rb │ ├── application_record.rb │ ├── comment.rb │ ├── concerns │ │ ├── .keep │ │ ├── abilities │ │ │ └── commentable.rb │ │ ├── comments │ │ │ ├── associations.rb │ │ │ ├── logic.rb │ │ │ └── validations.rb │ │ ├── posts │ │ │ ├── associations.rb │ │ │ ├── hooks.rb │ │ │ ├── logic.rb │ │ │ ├── scopes.rb │ │ │ └── validations.rb │ │ └── users │ │ │ ├── allowlist.rb │ │ │ ├── associations.rb │ │ │ ├── logic.rb │ │ │ └── validations.rb │ ├── post.rb │ └── user.rb ├── policies │ ├── application_policy.rb │ ├── comment_policy.rb │ └── post_policy.rb ├── serializers │ ├── comment_for_post_show_serializer.rb │ ├── comment_index_serializer.rb │ ├── comment_show_serializer.rb │ ├── post_index_serializer.rb │ ├── post_show_serializer.rb │ └── user_show_serializer.rb └── views │ ├── devise │ └── mailer │ │ └── confirmation_instructions.html.erb │ └── layouts │ ├── mailer.html.erb │ └── mailer.text.erb ├── bin ├── bundle ├── rails ├── rake ├── setup └── spring ├── config.ru ├── config ├── application.rb ├── boot.rb ├── cable.yml ├── credentials.yml.enc ├── database.yml ├── environment.rb ├── environments │ ├── development.rb │ ├── production.rb │ ├── staging.rb │ └── test.rb ├── initializers │ ├── application_controller_renderer.rb │ ├── backtrace_silencers.rb │ ├── cors.rb │ ├── devise.rb │ ├── filter_parameter_logging.rb │ ├── friendly_id.rb │ ├── inflections.rb │ ├── mime_types.rb │ ├── redis.rb │ ├── sidekiq.rb │ └── wrap_parameters.rb ├── locales │ ├── devise.en.yml │ └── en.yml ├── puma.rb ├── routes.rb ├── sitemap.rb ├── spring.rb └── storage.yml ├── db ├── migrate │ ├── 20210224031229_devise_create_users.rb │ ├── 20210224032349_create_allowlisted_jwts.rb │ ├── 20210324003543_add_names_themes_to_user.rb │ ├── 20210403204805_create_posts.rb │ ├── 20210414181412_add_slug_to_users.rb │ ├── 20210422212211_add_slug_to_posts.rb │ └── 20210422213742_create_comments.rb ├── schema.rb └── seeds.rb ├── lib ├── devise_custom_failure.rb └── tasks │ ├── .keep │ └── auto_annotate_models.rake ├── log └── .keep ├── public ├── robots.txt └── sitemap.xml ├── spec ├── rails_helper.rb ├── requests │ ├── comments_request_spec.rb │ ├── ping_request_spec.rb │ ├── posts_request_spec.rb │ └── users_request_spec.rb ├── spec_helper.rb └── support │ └── object_creators.rb ├── storage └── .keep ├── tmp ├── .keep └── pids │ └── .keep └── vendor └── .keep /.gitattributes: -------------------------------------------------------------------------------- 1 | # See https://git-scm.com/docs/gitattributes for more about git attribute files. 2 | 3 | # Mark the database schema as having been generated. 4 | db/schema.rb linguist-generated 5 | 6 | 7 | # Mark any vendored files as having been vendored. 8 | vendor/* linguist-vendored 9 | -------------------------------------------------------------------------------- /.github/workflows/run_specs.yml: -------------------------------------------------------------------------------- 1 | env: 2 | RUBY_VERSION: 3.0.0 3 | POSTGRES_USER: postgres 4 | POSTGRES_PASSWORD: postgres 5 | POSTGRES_DB: programmingtil_rails_1_test 6 | DEVISE_JWT_SECRET_KEY: ${{ secrets.DEVISE_JWT_SECRET_KEY }} 7 | 8 | name: Rails Specs 9 | on: [pull_request] 10 | jobs: 11 | rspec-test: 12 | name: RSpec 13 | runs-on: ubuntu-20.04 14 | services: 15 | postgres: 16 | image: postgres:latest 17 | ports: 18 | - 5432:5432 19 | env: 20 | POSTGRES_USER: ${{ env.POSTGRES_USER }} 21 | POSTGRES_PASSWORD: ${{ env.POSTGRES_PASSWORD }} 22 | steps: 23 | - uses: actions/checkout@v1 24 | - uses: ruby/setup-ruby@v1 25 | with: 26 | ruby-version: ${{ env.RUBY_VERSION }} 27 | - name: Install postgres client 28 | run: sudo apt-get install libpq-dev 29 | - name: Install dependencies 30 | run: | 31 | gem install bundler 32 | bundler install 33 | - name: Create database 34 | run: | 35 | bundler exec rails db:create RAILS_ENV=test 36 | bundler exec rails db:migrate RAILS_ENV=test 37 | - name: Run tests 38 | run: bundler exec rspec spec/* 39 | - name: Upload coverage results 40 | uses: actions/upload-artifact@master 41 | if: always() 42 | with: 43 | name: coverage-report 44 | path: coverage 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files for more about ignoring files. 2 | # 3 | # If you find yourself ignoring temporary files generated by your text editor 4 | # or operating system, you probably want to add a global ignore instead: 5 | # git config --global core.excludesfile '~/.gitignore_global' 6 | 7 | # Ignore bundler config. 8 | /.bundle 9 | 10 | # Ignore all logfiles and tempfiles. 11 | /log/* 12 | /tmp/* 13 | !/log/.keep 14 | !/tmp/.keep 15 | 16 | # Ignore uploaded files in development. 17 | /storage/* 18 | !/storage/.keep 19 | 20 | /public/assets 21 | .byebug_history 22 | 23 | # Ignore master key for decrypting credentials and more. 24 | /config/master.key 25 | 26 | /public/packs 27 | /public/packs-test 28 | /node_modules 29 | /yarn-error.log 30 | yarn-debug.log* 31 | .yarn-integrity 32 | 33 | /coverage/* 34 | /.env 35 | 36 | # Ignore redis 37 | *.rdb 38 | 39 | /config/credentials/production.key 40 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | ruby-3.0.0 2 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | git_source(:github) { |repo| "https://github.com/#{repo}.git" } 3 | 4 | ruby '3.0.0' 5 | 6 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' 7 | gem 'rails', '~> 6.1.1' 8 | # Use postgresql as the database for Active Record 9 | gem 'pg', '~> 1.1' 10 | # Use Puma as the app server 11 | gem 'puma', '~> 5.0' 12 | # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder 13 | # gem 'jbuilder', '~> 2.7' 14 | # Use Redis adapter to run Action Cable in production 15 | # gem 'redis', '~> 4.0' 16 | # Use Active Model has_secure_password 17 | # gem 'bcrypt', '~> 3.1.7' 18 | 19 | # Use Active Storage variant 20 | gem 'image_processing', '~> 1.2' 21 | 22 | # Reduces boot times through caching; required in config/boot.rb 23 | gem 'bootsnap', '>= 1.4.4', require: false 24 | 25 | # Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible 26 | # https://github.com/cyu/rack-cors 27 | gem 'rack-cors' 28 | 29 | # Authentication 30 | # https://github.com/heartcombo/devise 31 | gem 'devise', github: 'heartcombo/devise' 32 | 33 | # JWT devise for API 34 | # https://github.com/waiting-for-dev/devise-jwt 35 | gem 'devise-jwt' 36 | 37 | # Authorization 38 | # https://github.com/varvet/pundit 39 | gem 'pundit' 40 | 41 | # JSON API 42 | # Previously known as FastJson API 43 | # https://github.com/jsonapi-serializer/jsonapi-serializer 44 | gem 'jsonapi-serializer' 45 | 46 | # Friendly IDs 47 | # https://github.com/norman/friendly_id 48 | gem 'friendly_id', '~> 5.4.0' 49 | 50 | # Perform background queue jobs 51 | # https://github.com/mperham/sidekiq 52 | gem 'sidekiq' 53 | 54 | # Create our sitemap 55 | # https://github.com/kjvarga/sitemap_generator 56 | gem 'sitemap_generator' 57 | 58 | # AWS for storage 59 | # https://github.com/aws/aws-sdk-ruby 60 | gem 'aws-sdk-s3' 61 | 62 | group :development, :test do 63 | # Call 'byebug' anywhere in the code to stop execution and get a debugger console 64 | gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] 65 | 66 | # RSpec for testing 67 | # https://github.com/rspec/rspec-rails 68 | gem 'rspec-rails' 69 | # Needed for rspec 70 | gem 'rexml' 71 | gem 'spring-commands-rspec' 72 | # https://github.com/grosser/parallel_tests 73 | gem 'parallel_tests' 74 | 75 | # .env environment variable 76 | # https://github.com/bkeepers/dotenv 77 | gem 'dotenv-rails' 78 | end 79 | 80 | group :development do 81 | gem 'listen', '~> 3.3' 82 | # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring 83 | gem 'spring' 84 | 85 | # Annotate models and more 86 | # https://github.com/ctran/annotate_models 87 | gem 'annotate' 88 | 89 | # Local Emails 90 | # https://github.com/ryanb/letter_opener 91 | gem 'letter_opener' 92 | end 93 | 94 | group :test do 95 | # Adds support for Capybara system testing and selenium driver 96 | gem 'capybara', '>= 2.15' 97 | gem 'selenium-webdriver' 98 | # Easy installation and use of web drivers to run system tests with browsers 99 | gem 'webdrivers' 100 | 101 | # Code coverage 102 | # https://github.com/colszowka/simplecov 103 | gem 'simplecov', require: false 104 | 105 | # Clear out database between runs 106 | # https://github.com/DatabaseCleaner/database_cleaner 107 | gem 'database_cleaner-active_record' 108 | end 109 | 110 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem 111 | gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] 112 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GIT 2 | remote: https://github.com/heartcombo/devise.git 3 | revision: c82e4cf47b02002b2fd7ca31d441cf1043fc634c 4 | specs: 5 | devise (4.8.0) 6 | bcrypt (~> 3.0) 7 | orm_adapter (~> 0.1) 8 | railties (>= 4.1.0) 9 | responders 10 | warden (~> 1.2.3) 11 | 12 | GEM 13 | remote: https://rubygems.org/ 14 | specs: 15 | actioncable (6.1.3.2) 16 | actionpack (= 6.1.3.2) 17 | activesupport (= 6.1.3.2) 18 | nio4r (~> 2.0) 19 | websocket-driver (>= 0.6.1) 20 | actionmailbox (6.1.3.2) 21 | actionpack (= 6.1.3.2) 22 | activejob (= 6.1.3.2) 23 | activerecord (= 6.1.3.2) 24 | activestorage (= 6.1.3.2) 25 | activesupport (= 6.1.3.2) 26 | mail (>= 2.7.1) 27 | actionmailer (6.1.3.2) 28 | actionpack (= 6.1.3.2) 29 | actionview (= 6.1.3.2) 30 | activejob (= 6.1.3.2) 31 | activesupport (= 6.1.3.2) 32 | mail (~> 2.5, >= 2.5.4) 33 | rails-dom-testing (~> 2.0) 34 | actionpack (6.1.3.2) 35 | actionview (= 6.1.3.2) 36 | activesupport (= 6.1.3.2) 37 | rack (~> 2.0, >= 2.0.9) 38 | rack-test (>= 0.6.3) 39 | rails-dom-testing (~> 2.0) 40 | rails-html-sanitizer (~> 1.0, >= 1.2.0) 41 | actiontext (6.1.3.2) 42 | actionpack (= 6.1.3.2) 43 | activerecord (= 6.1.3.2) 44 | activestorage (= 6.1.3.2) 45 | activesupport (= 6.1.3.2) 46 | nokogiri (>= 1.8.5) 47 | actionview (6.1.3.2) 48 | activesupport (= 6.1.3.2) 49 | builder (~> 3.1) 50 | erubi (~> 1.4) 51 | rails-dom-testing (~> 2.0) 52 | rails-html-sanitizer (~> 1.1, >= 1.2.0) 53 | activejob (6.1.3.2) 54 | activesupport (= 6.1.3.2) 55 | globalid (>= 0.3.6) 56 | activemodel (6.1.3.2) 57 | activesupport (= 6.1.3.2) 58 | activerecord (6.1.3.2) 59 | activemodel (= 6.1.3.2) 60 | activesupport (= 6.1.3.2) 61 | activestorage (6.1.3.2) 62 | actionpack (= 6.1.3.2) 63 | activejob (= 6.1.3.2) 64 | activerecord (= 6.1.3.2) 65 | activesupport (= 6.1.3.2) 66 | marcel (~> 1.0.0) 67 | mini_mime (~> 1.0.2) 68 | activesupport (6.1.3.2) 69 | concurrent-ruby (~> 1.0, >= 1.0.2) 70 | i18n (>= 1.6, < 2) 71 | minitest (>= 5.1) 72 | tzinfo (~> 2.0) 73 | zeitwerk (~> 2.3) 74 | addressable (2.7.0) 75 | public_suffix (>= 2.0.2, < 5.0) 76 | annotate (3.1.1) 77 | activerecord (>= 3.2, < 7.0) 78 | rake (>= 10.4, < 14.0) 79 | aws-eventstream (1.1.1) 80 | aws-partitions (1.463.0) 81 | aws-sdk-core (3.114.0) 82 | aws-eventstream (~> 1, >= 1.0.2) 83 | aws-partitions (~> 1, >= 1.239.0) 84 | aws-sigv4 (~> 1.1) 85 | jmespath (~> 1.0) 86 | aws-sdk-kms (1.43.0) 87 | aws-sdk-core (~> 3, >= 3.112.0) 88 | aws-sigv4 (~> 1.1) 89 | aws-sdk-s3 (1.95.1) 90 | aws-sdk-core (~> 3, >= 3.112.0) 91 | aws-sdk-kms (~> 1) 92 | aws-sigv4 (~> 1.1) 93 | aws-sigv4 (1.2.3) 94 | aws-eventstream (~> 1, >= 1.0.2) 95 | bcrypt (3.1.16) 96 | bootsnap (1.7.5) 97 | msgpack (~> 1.0) 98 | builder (3.2.4) 99 | byebug (11.1.3) 100 | capybara (3.35.3) 101 | addressable 102 | mini_mime (>= 0.1.3) 103 | nokogiri (~> 1.8) 104 | rack (>= 1.6.0) 105 | rack-test (>= 0.6.3) 106 | regexp_parser (>= 1.5, < 3.0) 107 | xpath (~> 3.2) 108 | childprocess (3.0.0) 109 | concurrent-ruby (1.1.8) 110 | connection_pool (2.2.5) 111 | crass (1.0.6) 112 | database_cleaner-active_record (2.0.1) 113 | activerecord (>= 5.a) 114 | database_cleaner-core (~> 2.0.0) 115 | database_cleaner-core (2.0.1) 116 | devise-jwt (0.8.1) 117 | devise (~> 4.0) 118 | warden-jwt_auth (~> 0.5) 119 | diff-lcs (1.4.4) 120 | docile (1.4.0) 121 | dotenv (2.7.6) 122 | dotenv-rails (2.7.6) 123 | dotenv (= 2.7.6) 124 | railties (>= 3.2) 125 | dry-auto_inject (0.7.0) 126 | dry-container (>= 0.3.4) 127 | dry-configurable (0.12.1) 128 | concurrent-ruby (~> 1.0) 129 | dry-core (~> 0.5, >= 0.5.0) 130 | dry-container (0.7.2) 131 | concurrent-ruby (~> 1.0) 132 | dry-configurable (~> 0.1, >= 0.1.3) 133 | dry-core (0.5.0) 134 | concurrent-ruby (~> 1.0) 135 | erubi (1.10.0) 136 | ffi (1.15.1) 137 | friendly_id (5.4.2) 138 | activerecord (>= 4.0.0) 139 | globalid (0.4.2) 140 | activesupport (>= 4.2.0) 141 | i18n (1.8.10) 142 | concurrent-ruby (~> 1.0) 143 | image_processing (1.12.1) 144 | mini_magick (>= 4.9.5, < 5) 145 | ruby-vips (>= 2.0.17, < 3) 146 | jmespath (1.4.0) 147 | jsonapi-serializer (2.2.0) 148 | activesupport (>= 4.2) 149 | jwt (2.2.3) 150 | launchy (2.5.0) 151 | addressable (~> 2.7) 152 | letter_opener (1.7.0) 153 | launchy (~> 2.2) 154 | listen (3.5.1) 155 | rb-fsevent (~> 0.10, >= 0.10.3) 156 | rb-inotify (~> 0.9, >= 0.9.10) 157 | loofah (2.9.1) 158 | crass (~> 1.0.2) 159 | nokogiri (>= 1.5.9) 160 | mail (2.7.1) 161 | mini_mime (>= 0.1.1) 162 | marcel (1.0.1) 163 | method_source (1.0.0) 164 | mini_magick (4.11.0) 165 | mini_mime (1.0.3) 166 | minitest (5.14.4) 167 | msgpack (1.4.2) 168 | nio4r (2.5.7) 169 | nokogiri (1.11.5-x86_64-linux) 170 | racc (~> 1.4) 171 | orm_adapter (0.5.0) 172 | parallel (1.20.1) 173 | parallel_tests (3.7.0) 174 | parallel 175 | pg (1.2.3) 176 | public_suffix (4.0.6) 177 | puma (5.3.2) 178 | nio4r (~> 2.0) 179 | pundit (2.1.0) 180 | activesupport (>= 3.0.0) 181 | racc (1.5.2) 182 | rack (2.2.3) 183 | rack-cors (1.1.1) 184 | rack (>= 2.0.0) 185 | rack-test (1.1.0) 186 | rack (>= 1.0, < 3) 187 | rails (6.1.3.2) 188 | actioncable (= 6.1.3.2) 189 | actionmailbox (= 6.1.3.2) 190 | actionmailer (= 6.1.3.2) 191 | actionpack (= 6.1.3.2) 192 | actiontext (= 6.1.3.2) 193 | actionview (= 6.1.3.2) 194 | activejob (= 6.1.3.2) 195 | activemodel (= 6.1.3.2) 196 | activerecord (= 6.1.3.2) 197 | activestorage (= 6.1.3.2) 198 | activesupport (= 6.1.3.2) 199 | bundler (>= 1.15.0) 200 | railties (= 6.1.3.2) 201 | sprockets-rails (>= 2.0.0) 202 | rails-dom-testing (2.0.3) 203 | activesupport (>= 4.2.0) 204 | nokogiri (>= 1.6) 205 | rails-html-sanitizer (1.3.0) 206 | loofah (~> 2.3) 207 | railties (6.1.3.2) 208 | actionpack (= 6.1.3.2) 209 | activesupport (= 6.1.3.2) 210 | method_source 211 | rake (>= 0.8.7) 212 | thor (~> 1.0) 213 | rake (13.0.3) 214 | rb-fsevent (0.11.0) 215 | rb-inotify (0.10.1) 216 | ffi (~> 1.0) 217 | redis (4.2.5) 218 | regexp_parser (2.1.1) 219 | responders (3.0.1) 220 | actionpack (>= 5.0) 221 | railties (>= 5.0) 222 | rexml (3.2.5) 223 | rspec-core (3.10.1) 224 | rspec-support (~> 3.10.0) 225 | rspec-expectations (3.10.1) 226 | diff-lcs (>= 1.2.0, < 2.0) 227 | rspec-support (~> 3.10.0) 228 | rspec-mocks (3.10.2) 229 | diff-lcs (>= 1.2.0, < 2.0) 230 | rspec-support (~> 3.10.0) 231 | rspec-rails (5.0.1) 232 | actionpack (>= 5.2) 233 | activesupport (>= 5.2) 234 | railties (>= 5.2) 235 | rspec-core (~> 3.10) 236 | rspec-expectations (~> 3.10) 237 | rspec-mocks (~> 3.10) 238 | rspec-support (~> 3.10) 239 | rspec-support (3.10.2) 240 | ruby-vips (2.1.2) 241 | ffi (~> 1.12) 242 | rubyzip (2.3.0) 243 | selenium-webdriver (3.142.7) 244 | childprocess (>= 0.5, < 4.0) 245 | rubyzip (>= 1.2.2) 246 | sidekiq (6.2.1) 247 | connection_pool (>= 2.2.2) 248 | rack (~> 2.0) 249 | redis (>= 4.2.0) 250 | simplecov (0.21.2) 251 | docile (~> 1.1) 252 | simplecov-html (~> 0.11) 253 | simplecov_json_formatter (~> 0.1) 254 | simplecov-html (0.12.3) 255 | simplecov_json_formatter (0.1.3) 256 | sitemap_generator (6.1.2) 257 | builder (~> 3.0) 258 | spring (2.1.1) 259 | spring-commands-rspec (1.0.4) 260 | spring (>= 0.9.1) 261 | sprockets (4.0.2) 262 | concurrent-ruby (~> 1.0) 263 | rack (> 1, < 3) 264 | sprockets-rails (3.2.2) 265 | actionpack (>= 4.0) 266 | activesupport (>= 4.0) 267 | sprockets (>= 3.0.0) 268 | thor (1.1.0) 269 | tzinfo (2.0.4) 270 | concurrent-ruby (~> 1.0) 271 | warden (1.2.9) 272 | rack (>= 2.0.9) 273 | warden-jwt_auth (0.5.0) 274 | dry-auto_inject (~> 0.6) 275 | dry-configurable (~> 0.9) 276 | jwt (~> 2.1) 277 | warden (~> 1.2) 278 | webdrivers (4.6.0) 279 | nokogiri (~> 1.6) 280 | rubyzip (>= 1.3.0) 281 | selenium-webdriver (>= 3.0, < 4.0) 282 | websocket-driver (0.7.4) 283 | websocket-extensions (>= 0.1.0) 284 | websocket-extensions (0.1.5) 285 | xpath (3.2.0) 286 | nokogiri (~> 1.8) 287 | zeitwerk (2.4.2) 288 | 289 | PLATFORMS 290 | x86_64-linux 291 | 292 | DEPENDENCIES 293 | annotate 294 | aws-sdk-s3 295 | bootsnap (>= 1.4.4) 296 | byebug 297 | capybara (>= 2.15) 298 | database_cleaner-active_record 299 | devise! 300 | devise-jwt 301 | dotenv-rails 302 | friendly_id (~> 5.4.0) 303 | image_processing (~> 1.2) 304 | jsonapi-serializer 305 | letter_opener 306 | listen (~> 3.3) 307 | parallel_tests 308 | pg (~> 1.1) 309 | puma (~> 5.0) 310 | pundit 311 | rack-cors 312 | rails (~> 6.1.1) 313 | rexml 314 | rspec-rails 315 | selenium-webdriver 316 | sidekiq 317 | simplecov 318 | sitemap_generator 319 | spring 320 | spring-commands-rspec 321 | tzinfo-data 322 | webdrivers 323 | 324 | RUBY VERSION 325 | ruby 3.0.0p0 326 | 327 | BUNDLED WITH 328 | 2.2.6 329 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: bundle exec rails server -p $PORT 2 | worker: bundle exec sidekiq -c 1 -q $REDIS_QUEUE_DEFAULT -q $REDIS_QUEUE_MAILERS 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # COMMANDS and things 2 | 3 | ``` 4 | redis-server 5 | rails s 6 | bundle exec sidekiq -c 1 -q default -q mailers 7 | ``` 8 | 9 | ## EPISODE 25 - putting sitemap on AWS S3 10 | 11 | TODO: 12 | ``` 13 | Ensure credentials are set in Rails credentials 14 | Create new buckets on AWS S3 15 | ``` 16 | 17 | ``` 18 | modified: Gemfile 19 | modified: Gemfile.lock 20 | modified: README.md 21 | modified: config/credentials.yml.enc 22 | modified: config/sitemap.rb 23 | ``` 24 | 25 | ## EPISODE 24 - Credentials 26 | 27 | Resources: 28 | * https://edgeguides.rubyonrails.org/security.html#custom-credentials 29 | * https://s3.console.aws.amazon.com/ 30 | * https://blog.saeloun.com/2019/10/10/rails-6-adds-support-for-multi-environment-credentials.html 31 | 32 | Commands 33 | ``` 34 | rails credentials:help 35 | rails credentials:edit 36 | rails credentials:edit --environment production 37 | EDITOR=nano rails credentials:edit 38 | cat config/credentials/production.key 39 | heroku config:set RAILS_MASTER_KEY=`cat config/master.key` 40 | ``` 41 | 42 | Setup 43 | ``` 44 | Create user in IAM 45 | Create bucket in S3 46 | ``` 47 | 48 | Usage 49 | ``` 50 | Rails.application.credentials.config 51 | Rails.application.credentials.aws[:access_key_id] 52 | ``` 53 | 54 | ## EPISODE 23 - Sitemap 55 | 56 | Resources: 57 | * https://github.com/kjvarga/sitemap_generator 58 | 59 | ``` 60 | bundle install 61 | ``` 62 | 63 | ``` 64 | rake sitemap:install 65 | rake sitemap:refresh 66 | rake sitemap:refresh:no_ping 67 | ``` 68 | 69 | ``` 70 | modified: Gemfile 71 | modified: Gemfile.lock 72 | modified: README.md 73 | modified: app/controllers/posts_controller.rb 74 | new file: app/models/concerns/posts/scopes.rb 75 | modified: app/models/post.rb 76 | new file: config/sitemap.rb 77 | new file: public/sitemap.xml 78 | ``` 79 | 80 | ## EPISODE 22 - Redis + Sidekiq 81 | 82 | Resources: 83 | * https://github.com/mperham/sidekiq 84 | 85 | ``` 86 | # Perform background queue jobs 87 | # https://github.com/mperham/sidekiq 88 | gem 'sidekiq' 89 | ``` 90 | 91 | ``` 92 | bundle install 93 | ``` 94 | 95 | ``` 96 | modified: Gemfile 97 | modified: Gemfile.lock 98 | modified: Procfile 99 | modified: README.md 100 | modified: app/controllers/api/v1/posts_controller.rb 101 | modified: app/controllers/sessions_controller.rb 102 | modified: app/models/user.rb 103 | modified: app/serializers/post_show_serializer.rb 104 | modified: config/application.rb 105 | config/initializers/redis.rb 106 | config/initializers/sidekiq.rb 107 | ``` 108 | 109 | ## EPISODE 21 - comments CRUD, and returning some with initial Post Show 110 | 111 | ``` 112 | modified: README.md 113 | modified: app/controllers/api/v1/comments_controller.rb 114 | modified: app/models/concerns/abilities/commentable.rb 115 | modified: app/models/concerns/comments/logic.rb 116 | modified: app/models/concerns/posts/hooks.rb 117 | modified: app/models/post.rb 118 | modified: app/policies/comment_policy.rb 119 | new file: app/serializers/comment_for_post_show_serializer.rb 120 | modified: app/serializers/comment_index_serializer.rb 121 | new file: app/serializers/comment_show_serializer.rb 122 | modified: app/serializers/post_index_serializer.rb 123 | modified: app/serializers/post_show_serializer.rb 124 | modified: spec/requests/comments_request_spec.rb 125 | modified: spec/requests/posts_request_spec.rb 126 | modified: spec/support/object_creators.rb 127 | ``` 128 | 129 | ## EPISODE 20 - comments model 130 | 131 | ``` 132 | rails g migration createComments 133 | ``` 134 | 135 | ``` 136 | rails db:migrate 137 | ``` 138 | 139 | files 140 | ``` 141 | # modified: README.md 142 | # new file: app/controllers/api/v1/comments_controller.rb 143 | # new file: app/models/comment.rb 144 | # new file: app/models/concerns/abilities/commentable.rb 145 | # new file: app/models/concerns/comments/associations.rb 146 | # new file: app/models/concerns/comments/logic.rb 147 | # new file: app/models/concerns/comments/validations.rb 148 | # modified: app/models/concerns/users/associations.rb 149 | # new file: app/models/concerns/users/logic.rb 150 | # modified: app/models/post.rb 151 | # modified: app/models/user.rb 152 | # new file: app/policies/comment_policy.rb 153 | # new file: app/serializers/comment_index_serializer.rb 154 | # modified: app/serializers/post_index_serializer.rb 155 | # modified: app/serializers/post_show_serializer.rb 156 | # modified: config/locales/en.yml 157 | # modified: config/routes.rb 158 | # new file: db/migrate/20210422213742_create_comments.rb 159 | # modified: db/schema.rb 160 | # new file: spec/requests/comments_request_spec.rb 161 | # modified: spec/support/object_creators.rb 162 | ``` 163 | 164 | ## EPISODE 19 - fix user validations and post slugs 165 | 166 | ``` 167 | rails g migration addSlugToPosts 168 | ``` 169 | 170 | FILES 171 | ``` 172 | modified: app/controllers/api/v1/posts_controller.rb 173 | modified: app/models/concerns/users/validations.rb 174 | modified: app/models/post.rb 175 | modified: app/models/user.rb 176 | modified: app/serializers/post_show_serializer.rb 177 | modified: config/locales/en.yml 178 | modified: config/routes.rb 179 | new file: db/migrate/20210422212211_add_slug_to_posts.rb 180 | modified: db/schema.rb 181 | modified: spec/requests/posts_request_spec.rb 182 | ``` 183 | 184 | ``` 185 | Post.find_each(&:save) 186 | ``` 187 | 188 | ## EPISODE 18 - friendly URLs via the friendly gem 189 | 190 | * https://github.com/norman/friendly_id 191 | 192 | ``` 193 | rails g migration AddSlugToUsers slug:uniq 194 | ``` 195 | 196 | Files 197 | ``` 198 | # modified: Gemfile 199 | # modified: Gemfile.lock 200 | # modified: README.md 201 | # modified: app/controllers/api/v1/posts_controller.rb 202 | # modified: app/controllers/api/v1/users_controller.rb 203 | # modified: app/controllers/application_controller.rb 204 | # modified: app/models/concerns/posts/logic.rb 205 | # modified: app/models/concerns/posts/validations.rb 206 | # modified: app/models/user.rb 207 | # modified: app/policies/post_policy.rb 208 | # modified: app/serializers/post_index_serializer.rb 209 | # new file: app/serializers/user_show_serializer.rb 210 | # new file: config/initializers/friendly_id.rb 211 | # modified: config/routes.rb 212 | # new file: db/migrate/20210414181412_add_slug_to_users.rb 213 | # modified: db/schema.rb 214 | # modified: spec/requests/posts_request_spec.rb 215 | # modified: spec/requests/users_request_spec.rb 216 | # 217 | ``` 218 | 219 | After, rails console: 220 | ``` 221 | User.find_each(&:save) 222 | ``` 223 | 224 | 225 | ## EPISODE 17 - cookies 226 | 227 | ## EPISODE 16 - create/update/delete posts 228 | 229 | ``` 230 | Gemfile 231 | app/controllers/api/v1/posts_controller.rb 232 | app/controllers/application_controller.rb 233 | app/models/post.rb 234 | app/models/concerns/posts/logic.rb 235 | app/policies/application_policy.rb 236 | app/policies/post_policy.rb 237 | app/serializers/post_index_serializer.rb 238 | app/serializers/post_show_serializer.rb 239 | config/locales/en.yml 240 | config/routes.rb 241 | spec/requests/posts_request_spec.rb 242 | spec/support/object_creators.rb 243 | ``` 244 | 245 | ## EPISODE 15 - creating a blog 246 | 247 | ``` 248 | rails g migration createPosts 249 | rake db:migrate 250 | ``` 251 | 252 | Files 253 | ``` 254 | db/migrations/XXX_create_posts.rb 255 | app/models/post.rb 256 | app/models/user.rb 257 | app/models/concerns/posts/associations.rb 258 | app/models/concerns/posts/validations.rb 259 | app/models/concerns/users/associations.rb 260 | app/models/concerns/users/validations.rb 261 | config/routes.rb 262 | spec/requests/posts_request_spec.rb 263 | spec/support/object_creators.rb 264 | ``` 265 | 266 | ## EPISODE 14 267 | 268 | Backend, and why using localStorage: 269 | https://github.com/waiting-for-dev/devise-jwt/issues/126 270 | 271 | tldr; 272 | * cannot use different domains. 273 | * long-term, we'll be using the same APIs with our mobile app. 274 | * update to check and compare/use the AUD 275 | 276 | Concerns 277 | * XSS 278 | 279 | ``` 280 | config/initializers/cors.rb 281 | models/concerns/users/allowlist.rb 282 | controllers/sessions_controller.rb 283 | ``` 284 | 285 | ## EPISODE 13 286 | 287 | ``` 288 | routes.rb 289 | controllers/api/v1/users_controller.rb 290 | en.yml 291 | models/user.rb 292 | spec/requests/users_request_spec.rb 293 | ``` 294 | 295 | ## EPISODE 12 296 | 297 | Adding usernames: 298 | ``` 299 | migration > rails g migration addNamesThemesToUser 300 | config/initializers/devise.rb 301 | controllers/application_controller.rb 302 | model/user.rb 303 | views/devise/mailer/confirmation_instructions.html.erb 304 | ``` 305 | 306 | Fixing specs: 307 | ``` 308 | spec/support/object_creators.rb 309 | ``` 310 | 311 | Changes: 312 | ``` 313 | config/environments/development.rb (port) 314 | ``` 315 | 316 | Upcoming: 317 | ``` 318 | config/routes.rb 319 | controllers/api/v1/users_controller.rb 320 | spec/requests/users_request_spec.rb 321 | ``` 322 | 323 | ## EPISODE 11 324 | 325 | In heroku, add Mailgun addon. 326 | 327 | Under environment variables, add each: 328 | 329 | ``` 330 | MAILGUN_SMTP_LOGIN -> MAIL_PROVIDER_USERNAME 331 | MAILGUN_SMTP_PASSWORD -> MAIL_PROVIDER_PASSWORD 332 | MAILGUN_SMTP_PORT -> MAIL_PROVIDER_PORT 333 | MAILGUN_SMTP_SERVER -> MAIL_PROVIDER_ADDRESS 334 | ``` 335 | 336 | Delete the old MAILGUN_X ones. 337 | 338 | In Mailgun, add your email to authorized emails + confirm it. 339 | 340 | ## EPISODE 10 341 | 342 | Promote to production 343 | 344 | heroku run rails db:migrate -a ptil-rails-api 345 | heroku run rails c -a ptil-rails-api 346 | 347 | Addons: 348 | * Bug Tracking - Honeybadger 349 | * Performance / Monitoring - Librato 350 | * Performance / Monitoring - New Relic 351 | * Logging - Logentries 352 | * Redis - Redis Enterprise Cloud 353 | * Cron - Heroku Scheduler 354 | 355 | ## EPISODE 9 356 | 357 | Create Heroku account 358 | Install setup Heroku CLI 359 | Create pipeline 360 | Create staging application 361 | Create production application 362 | 363 | Install add-ons: 364 | * Heroku Postgres 365 | 366 | ENV variables: 367 | * DEVISE_JWT_SECRET_KEY 368 | * RACK_ENV 369 | * RAILS_ENV 370 | * RAILS_LOG_TO_STDOUT 371 | * RAILS_SERVE_STATIC_FILES 372 | * SECRET_KEY_BASE 373 | 374 | Procfile 375 | 376 | heroku git:remote -a ptil-rails-staging-api 377 | git push heroku ep9:master 378 | 379 | heroku run rails db:migrate -a ptil-rails-staging-api 380 | heroku run rails c -a ptil-rails-staging-api 381 | 382 | ## EPISODE 8 383 | 384 | config/initializers/cors.rb 385 | ```ruby 386 | Rails.application.config.middleware.insert_before 0, Rack::Cors do 387 | allow do 388 | origins '*' 389 | 390 | resource '*', 391 | headers: :any, 392 | methods: [:get, :post, :put, :patch, :delete, :options, :head] 393 | end 394 | end 395 | ``` 396 | 397 | Gemfile 398 | ```ruby 399 | # Local Emails 400 | # https://github.com/ryanb/letter_opener 401 | gem 'letter_opener' 402 | ``` 403 | 404 | config/environments/development.rb 405 | ```ruby 406 | config.action_mailer.default_url_options = { host: 'localhost', port: 5000 } 407 | config.action_mailer.delivery_method = :letter_opener 408 | config.action_mailer.raise_delivery_errors = false 409 | config.action_mailer.perform_caching = false 410 | config.action_mailer.perform_deliveries = true 411 | ``` 412 | 413 | ## EPISODE 7 414 | 415 | Github Actions 416 | 417 | database.yml 418 | ```yml 419 | test: 420 | <<: *default 421 | database: programmingtil_rails_1_test 422 | password: <%= ENV['POSTGRES_PASSWORD'] %> 423 | username: <%= ENV['POSTGRES_USER'] %> 424 | host: 127.0.0.1 425 | ``` 426 | 427 | .github/workflows/run_specs.yml 428 | ```yml 429 | env: 430 | RUBY_VERSION: 3.0.0 431 | POSTGRES_USER: postgres 432 | POSTGRES_PASSWORD: postgres 433 | POSTGRES_DB: programmingtil_rails_1_test 434 | DEVISE_JWT_SECRET_KEY: ${{ secrets.DEVISE_JWT_SECRET_KEY }} 435 | 436 | name: Rails Specs 437 | on: [push,pull_request] 438 | jobs: 439 | rspec-test: 440 | name: RSpec 441 | runs-on: ubuntu-20.04 442 | services: 443 | postgres: 444 | image: postgres:latest 445 | ports: 446 | - 5432:5432 447 | env: 448 | POSTGRES_USER: ${{ env.POSTGRES_USER }} 449 | POSTGRES_PASSWORD: ${{ env.POSTGRES_PASSWORD }} 450 | steps: 451 | - uses: actions/checkout@v1 452 | - uses: actions/setup-ruby@v1 453 | with: 454 | ruby-version: ${{ env.RUBY_VERSION }} 455 | - name: Install postgres client 456 | run: sudo apt-get install libpq-dev 457 | - name: Install dependencies 458 | run: | 459 | gem install bundler 460 | bundler install 461 | - name: Create database 462 | run: | 463 | bundler exec rails db:create RAILS_ENV=test 464 | bundler exec rails db:migrate RAILS_ENV=test 465 | - name: Run tests 466 | run: bundler exec rspec spec/* 467 | - name: Upload coverage results 468 | uses: actions/upload-artifact@master 469 | if: always() 470 | with: 471 | name: coverage-report 472 | path: coverage 473 | ``` 474 | 475 | ## EPISODE 6 476 | 477 | ```ruby 478 | gem 'simplecov', require: false 479 | ``` 480 | ## EPISODE 5 481 | 482 | Gemfile 483 | ```ruby 484 | # RSpec for testing 485 | # https://github.com/rspec/rspec-rails 486 | gem 'rspec-rails' 487 | # Needed for rspec 488 | gem 'rexml' 489 | gem 'spring-commands-rspec' 490 | # https://github.com/grosser/parallel_tests 491 | gem 'parallel_tests' 492 | 493 | # .env environment variable 494 | # https://github.com/bkeepers/dotenv 495 | gem 'dotenv-rails' 496 | 497 | group :test do 498 | # Adds support for Capybara system testing and selenium driver 499 | gem 'capybara', '>= 2.15' 500 | gem 'selenium-webdriver' 501 | # Easy installation and use of web drivers to run system tests with browsers 502 | gem 'webdrivers' 503 | 504 | # Code coverage 505 | # https://github.com/colszowka/simplecov 506 | gem 'simplecov', require: false 507 | 508 | # Clear out database between runs 509 | # https://github.com/DatabaseCleaner/database_cleaner 510 | gem 'database_cleaner-active_record' 511 | end 512 | ``` 513 | 514 | routes.rb 515 | ```ruby 516 | # Ping to ensure site is up 517 | resources :ping, only: [:index] do 518 | collection do 519 | get :auth 520 | end 521 | end 522 | ``` 523 | 524 | en.yml 525 | ```yml 526 | en: 527 | controllers: 528 | confirmations: 529 | resent: "Confirmation email sent successfully." 530 | success: "Email confirmed successfully." 531 | passwords: 532 | email_required: "Email is required." 533 | email_sent: "Email sent. Please check your inbox." 534 | success: "Password updated successfully. You may need to sign in again." 535 | registrations: 536 | confirm: "Please confirm your email address." 537 | sessions: 538 | sign_out: "Signed out successfully." 539 | ``` 540 | 541 | application_controllerb.rb 542 | confirmations_controller.rb 543 | passwords_controller.rb 544 | registrations_controller.rb 545 | sessions_controller.rb 546 | 547 | ping_controller.rb 548 | ```ruby 549 | class PingController < ApplicationController 550 | before_action :authenticate_user!, only: [:auth] 551 | 552 | # GET /ping 553 | def index 554 | render body: nil, status: 200 555 | end 556 | 557 | # GET /ping/auth 558 | def auth 559 | render body: nil, status: 200 560 | end 561 | end 562 | ``` 563 | 564 | ping_request_spec.rb 565 | ```ruby 566 | require 'rails_helper' 567 | 568 | RSpec.describe "Pings", type: :request do 569 | it 'Returns a status of 200' do 570 | get '/ping/' 571 | expect(response).to have_http_status(200) 572 | end 573 | 574 | it 'Returns a status of 401 if not logged in' do 575 | get '/ping/auth/' 576 | expect(response).to have_http_status(401) 577 | end 578 | 579 | it 'Returns a status of 200 if logged in' do 580 | user = create_user 581 | headers = get_headers(user.username) 582 | 583 | get '/ping/auth/', headers: headers 584 | expect(response).to have_http_status(200) 585 | end 586 | end 587 | ``` 588 | 589 | devise.rb 590 | ```ruby 591 | config.warden do |manager| 592 | manager.failure_app = DeviseCustomFailure 593 | end 594 | ``` 595 | 596 | application.rb 597 | lib/DeviseCustomFailure.rb 598 | models/user.rb 599 | 600 | ## EPISODE 4 601 | 602 | Gemfile 603 | ```ruby 604 | # Annotate models and more 605 | # https://github.com/ctran/annotate_models 606 | gem 'annotate' 607 | ``` 608 | 609 | ``` 610 | bundle install 611 | ``` 612 | 613 | auto_annotate_models.rake 614 | ```ruby 615 | # NOTE: only doing this in development as some production environments (Heroku) 616 | # NOTE: are sensitive to local FS writes, and besides -- it's just not proper 617 | # NOTE: to have a dev-mode tool do its thing in production. 618 | if Rails.env.development? 619 | require 'annotate' 620 | task :set_annotation_options do 621 | # You can override any of these by setting an environment variable of the 622 | # same name. 623 | Annotate.set_defaults( 624 | 'active_admin' => 'false', 625 | 'additional_file_patterns' => [], 626 | 'routes' => 'false', 627 | 'models' => 'true', 628 | 'position_in_routes' => 'before', 629 | 'position_in_class' => 'before', 630 | 'position_in_test' => 'before', 631 | 'position_in_fixture' => 'before', 632 | 'position_in_factory' => 'before', 633 | 'position_in_serializer' => 'before', 634 | 'show_foreign_keys' => 'true', 635 | 'show_complete_foreign_keys' => 'false', 636 | 'show_indexes' => 'true', 637 | 'simple_indexes' => 'false', 638 | 'model_dir' => 'app/models', 639 | 'root_dir' => '', 640 | 'include_version' => 'false', 641 | 'require' => '', 642 | 'exclude_tests' => 'false', 643 | 'exclude_fixtures' => 'true', 644 | 'exclude_factories' => 'true', 645 | 'exclude_serializers' => 'true', 646 | 'exclude_scaffolds' => 'true', 647 | 'exclude_controllers' => 'true', 648 | 'exclude_helpers' => 'true', 649 | 'exclude_sti_subclasses' => 'false', 650 | 'ignore_model_sub_dir' => 'false', 651 | 'ignore_columns' => nil, 652 | 'ignore_routes' => nil, 653 | 'ignore_unknown_models' => 'false', 654 | 'hide_limit_column_types' => 'integer,bigint,boolean', 655 | 'hide_default_column_types' => 'json,jsonb,hstore', 656 | 'skip_on_db_migrate' => 'false', 657 | 'format_bare' => 'true', 658 | 'format_rdoc' => 'false', 659 | 'format_yard' => 'false', 660 | 'format_markdown' => 'false', 661 | 'sort' => 'false', 662 | 'force' => 'false', 663 | 'frozen' => 'false', 664 | 'classified_sort' => 'false', 665 | 'trace' => 'false', 666 | 'wrapper_open' => nil, 667 | 'wrapper_close' => nil, 668 | 'with_comment' => 'true' 669 | ) 670 | end 671 | 672 | Annotate.load_tasks 673 | end 674 | ``` 675 | 676 | ``` 677 | rake db:migrate 678 | ``` 679 | 680 | ## EPISODE 3 681 | 682 | devise.rb 683 | ```ruby 684 | config.jwt do |jwt| 685 | jwt.secret = ENV['DEVISE_JWT_SECRET_KEY'] 686 | jwt.dispatch_requests = [ 687 | ['POST', %r{^/signin$}], 688 | ] 689 | jwt.revocation_requests = [ 690 | ['DELETE', %r{^/signout$}] 691 | ] 692 | jwt.expiration_time = 14.days.to_i 693 | # Use default aud_header 694 | jwt.aud_header = 'JWT_AUD' 695 | end 696 | ``` 697 | 698 | user.rb 699 | ```ruby 700 | devise :database_authenticatable, 701 | :confirmable, 702 | :registerable, 703 | :recoverable, 704 | :rememberable, 705 | :validatable, 706 | :jwt_authenticatable, 707 | jwt_revocation_strategy: self 708 | ``` 709 | 710 | ```bash 711 | rails g migration createAllowlistedJwts 712 | ``` 713 | 714 | create_allowlisted_jwts.rb 715 | ```ruby 716 | def change 717 | create_table :allowlisted_jwts do |t| 718 | t.references :users, foreign_key: { on_delete: :cascade }, null: false 719 | t.string :jti, null: false 720 | t.string :aud, null: false 721 | t.datetime :exp, null: false 722 | t.string :remote_ip 723 | t.string :os_data 724 | t.string :browser_data 725 | t.string :device_data 726 | t.timestamps null: false 727 | end 728 | 729 | add_index :allowlisted_jwts, :jti, unique: true 730 | end 731 | ``` 732 | 733 | models/allowlisted_jwt.rb 734 | ```ruby 735 | class AllowlistedJwt < ApplicationRecord 736 | end 737 | ``` 738 | 739 | ``` 740 | rake db:migrate 741 | ``` 742 | 743 | 744 | 745 | ## EPISODE 2: 746 | 747 | database.yml > host: 127.0.0.1 -> (needed because WSL) 748 | 749 | Gemfile 750 | ```ruby 751 | gem 'devise', github: 'heartcombo/devise' 752 | gem 'devise-jwt' 753 | gem 'rack-cors' 754 | ``` 755 | 756 | ``` 757 | rake db:create 758 | ``` 759 | 760 | ``` 761 | rails generate devise:install 762 | rails generate devise user 763 | rails db:migrate 764 | ``` 765 | 766 | ## EPISODE 1: 767 | ``` 768 | rails new programmingtil-rails-1 --api --database=postgresql 769 | ``` 770 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require_relative "config/application" 5 | 6 | Rails.application.load_tasks 7 | -------------------------------------------------------------------------------- /app/channels/application_cable/channel.rb: -------------------------------------------------------------------------------- 1 | module ApplicationCable 2 | class Channel < ActionCable::Channel::Base 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/channels/application_cable/connection.rb: -------------------------------------------------------------------------------- 1 | module ApplicationCable 2 | class Connection < ActionCable::Connection::Base 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/controllers/api/v1/comments_controller.rb: -------------------------------------------------------------------------------- 1 | class Api::V1::CommentsController < ApplicationController 2 | before_action :authenticate_user!, only: [:create, :update, :destroy] 3 | 4 | # POST /api/v1/comments 5 | def create 6 | authorize Comment 7 | comment = Comment.create_comment!(current_user, create_params) 8 | render json: comment_show(comment, { message: I18n.t('controllers.comments.created') }) 9 | end 10 | 11 | # DELETE /api/v1/comments/:id 12 | def destroy 13 | comment = Comment.find(params[:id]) 14 | authorize comment 15 | comment = Comment.delete_comment!(comment) 16 | render json: comment_show(comment, { message: I18n.t('controllers.comments.deleted') }) 17 | end 18 | 19 | # GET /api/v1/comments 20 | def index 21 | comments = policy_scope(Comment) 22 | comments = comments 23 | .where(commentable_id: params[:commentable_id], commentable_type: params[:commentable_type]) 24 | .includes(:commentable, :user) 25 | render json: CommentIndexSerializer.new(comments, list_options).serializable_hash.to_json 26 | end 27 | 28 | # GET /api/v1/comments/:id 29 | def show 30 | comment = Comment.find(params[:id]) 31 | render json: comment_show(comment) 32 | rescue ActiveRecord::RecordNotFound 33 | render json: { error: I18n.t('api.not_found') }, status: 404 34 | end 35 | 36 | # PUT /api/v1/comments/:id 37 | def update 38 | comment = Comment.find(params[:id]) 39 | authorize comment 40 | comment = Comment.update_comment!(comment, update_params) 41 | render json: comment_show(comment, { message: I18n.t('controllers.comments.updated') }) 42 | end 43 | 44 | private 45 | 46 | def create_params 47 | params.require(:comment).permit(:body, :commentable_id, :commentable_type) 48 | end 49 | 50 | def update_params 51 | params.require(:comment).permit(:body, :id, :commentable_id, :commentable_type) 52 | end 53 | 54 | def comment_show(comment, meta = {}) 55 | CommentShowSerializer.new(comment, show_options(meta)).serializable_hash.to_json 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /app/controllers/api/v1/posts_controller.rb: -------------------------------------------------------------------------------- 1 | class Api::V1::PostsController < ApplicationController 2 | before_action :authenticate_user!, only: [:create, :update, :destroy] 3 | 4 | # POST /api/v1/posts 5 | def create 6 | authorize Post 7 | post = Post.create_post!(create_params, current_user) 8 | render json: post_show(post, { message: I18n.t('controllers.posts.created') }) 9 | end 10 | 11 | # DELETE /api/v1/posts/:id 12 | def destroy 13 | post = Post.find(params[:id]) 14 | authorize post 15 | post = Post.delete_post!(post) 16 | render json: post_show(post, { message: I18n.t('controllers.posts.deleted') }) 17 | end 18 | 19 | # GET /api/v1/posts 20 | def index 21 | posts = policy_scope(Post) 22 | posts = posts.for_index(params) 23 | render json: PostIndexSerializer.new(posts, list_options).serializable_hash.to_json 24 | end 25 | 26 | # GET /api/v1/posts/:slug 27 | def show 28 | post = Post.friendly.find(params[:id]) 29 | options = show_options 30 | options[:params] = options[:params].merge({ all: params[:all] }) if params[:all].present? 31 | render json: PostShowSerializer.new(post, options).serializable_hash.to_json 32 | rescue ActiveRecord::RecordNotFound 33 | render json: { error: I18n.t('api.not_found') }, status: 404 34 | end 35 | 36 | # PUT /api/v1/posts/:id 37 | def update 38 | post = Post.find(params[:id]) 39 | authorize post 40 | post = Post.update_post!(post, update_params) 41 | render json: post_show(post, { message: I18n.t('controllers.posts.updated') }) 42 | end 43 | 44 | private 45 | 46 | def create_params 47 | params.require(:post).permit(:title, :content, :published_at) 48 | end 49 | 50 | def update_params 51 | params.require(:post).permit(:id, :title, :content, :published_at) 52 | end 53 | 54 | def post_show(post, meta = {}) 55 | PostShowSerializer.new(post, show_options(meta)).serializable_hash.to_json 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /app/controllers/api/v1/users_controller.rb: -------------------------------------------------------------------------------- 1 | class Api::V1::UsersController < ApplicationController 2 | before_action :authenticate_user!, only: [:update] 3 | 4 | # GET /api/v1/users/available 5 | def available 6 | free = if params[:email].present? 7 | !User.where(email: params[:email].downcase).exists? 8 | elsif params[:username].present? 9 | !User.where(username: params[:username].downcase).exists? 10 | else 11 | true 12 | end 13 | render json: { data: free } 14 | end 15 | 16 | # GET /api/v1/users/#{slug} 17 | def show 18 | user = User.friendly.find(params[:id]) 19 | render json: UserShowSerializer.new(user, show_options).serializable_hash.to_json 20 | rescue ActiveRecord::RecordNotFound 21 | render json: { error: I18n.t('api.not_found') }, status: 404 22 | end 23 | 24 | # authenticate_user! 25 | # PUT /api/v1/users/#{id} 26 | def update 27 | current_user.update(user_params) 28 | render json: { 29 | message: I18n.t('controllers.users.updated'), 30 | user: current_user.for_display 31 | } 32 | rescue => error 33 | render json: { error: I18n.t('api.oops') }, status: 500 34 | end 35 | 36 | private 37 | 38 | def user_params 39 | params.require(:user).permit( 40 | :display_name, 41 | :username 42 | ) 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::API 2 | include Pundit 3 | 4 | rescue_from ActiveRecord::RecordInvalid, with: :record_invalid 5 | rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized 6 | 7 | before_action :configure_permitted_parameters, if: :devise_controller? 8 | 9 | # Helper methods 10 | # Return an options object for lists for jsonapi-serializer 11 | def list_options(meta = {}) 12 | opts = { is_collection: true } 13 | opts[:meta] = get_meta_data(meta) 14 | opts[:params] = get_params_data 15 | opts 16 | end 17 | 18 | # Return an options object for single objects for jsonapi-serializer 19 | def show_options(meta = {}) 20 | opts = { is_collection: false } 21 | opts[:meta] = get_meta_data(meta) 22 | opts[:params] = get_params_data 23 | opts 24 | end 25 | 26 | # Set any kind of meta data needed for the options 27 | def get_meta_data(meta = {}) 28 | ret_meta = meta 29 | if request.headers['auth_failure'] 30 | ret_meta[:authFailure] = true 31 | else 32 | if current_token.present? 33 | ret_meta[:jwt] = current_token 34 | end 35 | end 36 | ret_meta 37 | end 38 | 39 | # Set any kind of params data needed for the options 40 | def get_params_data 41 | if current_user.present? 42 | { user: current_user, } 43 | else 44 | {} 45 | end 46 | end 47 | 48 | protected 49 | 50 | def current_token 51 | request.env['warden-jwt_auth.token'] 52 | end 53 | 54 | def configure_permitted_parameters 55 | devise_parameter_sanitizer.permit(:sign_in, keys: [:login]) 56 | devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :email]) 57 | end 58 | 59 | private 60 | 61 | def record_invalid(exception) 62 | message = exception.message.partition('Validation failed: ').last 63 | render json: { meta: { message: message } }, status: 401 64 | return 65 | end 66 | 67 | def user_not_authorized 68 | render json: { message: I18n.t('api.unauthorized') }, status: 404 69 | return 70 | end 71 | end 72 | -------------------------------------------------------------------------------- /app/controllers/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidwparker/programmingtil-rails/9151797fae190b1abb7519240d3245dd58ba5347/app/controllers/concerns/.keep -------------------------------------------------------------------------------- /app/controllers/confirmations_controller.rb: -------------------------------------------------------------------------------- 1 | class ConfirmationsController < Devise::ConfirmationsController 2 | # POST /resource/confirmation 3 | def create 4 | self.resource = resource_class.send_confirmation_instructions(resource_params) 5 | yield resource if block_given? 6 | 7 | if successfully_sent?(resource) 8 | render json: { message: I18n.t('controllers.confirmations.resent') }, status: 200 9 | else 10 | render json: resource.errors, status: 401 11 | end 12 | end 13 | 14 | # GET /resource/confirmation?confirmation_token=abcdef 15 | def show 16 | self.resource = resource_class.confirm_by_token(params[:confirmation_token]) 17 | yield resource if block_given? 18 | 19 | if resource.errors.empty? 20 | render json: { message: I18n.t('controllers.confirmations.success') }, status: 200 21 | else 22 | render json: resource.errors, status: 401 23 | end 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /app/controllers/passwords_controller.rb: -------------------------------------------------------------------------------- 1 | class PasswordsController < Devise::PasswordsController 2 | respond_to :json 3 | 4 | # POST /users/password 5 | # Specs No 6 | def create 7 | if params[:user] && params[:user][:email].blank? 8 | render json: { error: I18n.t('controllers.passwords.email_required') }, status: 406 9 | else 10 | self.resource = resource_class.send_reset_password_instructions(resource_params) 11 | if successfully_sent?(resource) 12 | render json: { message: I18n.t('controllers.passwords.email_sent') } 13 | else 14 | respond_with_error(resource) 15 | end 16 | end 17 | end 18 | 19 | # PUT /users/password 20 | # Specs No 21 | def update 22 | self.resource = resource_class.reset_password_by_token(resource_params) 23 | 24 | if resource.errors.empty? 25 | if Devise.sign_in_after_reset_password 26 | resource.after_database_authentication 27 | sign_in(resource_name, resource) 28 | if user_signed_in? 29 | respond_with(resource) 30 | else 31 | respond_with_error(resource) 32 | end 33 | else 34 | respond_with(resource) 35 | end 36 | else 37 | set_minimum_password_length 38 | respond_with_error(resource) 39 | end 40 | end 41 | 42 | private 43 | 44 | def current_token 45 | # NOTE: this is technically nil at this point, and user still must login again 46 | request.env['warden-jwt_auth.token'] 47 | end 48 | 49 | def respond_with(resource, _opts = {}) 50 | render json: { 51 | message: I18n.t('controllers.passwords.success'), 52 | user: resource.for_display, 53 | jwt: current_token, 54 | } 55 | end 56 | 57 | def respond_with_error(resource) 58 | render json: resource.errors, status: 401 59 | end 60 | end 61 | -------------------------------------------------------------------------------- /app/controllers/ping_controller.rb: -------------------------------------------------------------------------------- 1 | class PingController < ApplicationController 2 | before_action :authenticate_user!, only: [:auth] 3 | 4 | # GET /ping 5 | def index 6 | render body: nil, status: 200 7 | end 8 | 9 | # GET /ping/auth 10 | def auth 11 | render body: nil, status: 200 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /app/controllers/registrations_controller.rb: -------------------------------------------------------------------------------- 1 | class RegistrationsController < Devise::RegistrationsController 2 | respond_to :json 3 | 4 | # POST /users 5 | # Specs No 6 | def create 7 | build_resource(sign_up_params) 8 | 9 | resource.save 10 | if resource.persisted? 11 | render json: { message: I18n.t('controllers.registrations.confirm') } 12 | else 13 | render json: resource.errors, status: 401 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /app/controllers/sessions_controller.rb: -------------------------------------------------------------------------------- 1 | require 'digest' 2 | 3 | class SessionsController < Devise::SessionsController 4 | respond_to :json 5 | 6 | # POST /users/sign_in 7 | # Specs No 8 | def create 9 | # Check both because rspec vs normal server requests .... do different things? WTF. 10 | possible_aud = request.headers['HTTP_JWT_AUD'].presence || request.headers['JWT_AUD'].presence 11 | if params[:browser].present? 12 | browser, version = params[:browser].split("||") 13 | digest = Digest::SHA256.hexdigest("#{params[:os]}||||#{browser}||#{version.to_i}") 14 | if digest != possible_aud 15 | raise "Unmatched AUD" 16 | end 17 | end 18 | self.resource = warden.authenticate!(auth_options) 19 | sign_in(resource_name, resource) 20 | if user_signed_in? 21 | # TODO: resource.blocked? 22 | # 23 | # For the initial login, we need to manually update IP / metadata for JWT here as no hooks 24 | # And we'll want this data for all subsequent requests 25 | last = resource.allowlisted_jwts.where(aud: possible_aud).last 26 | aud = possible_aud 27 | if last.present? 28 | last.update_columns({ 29 | browser_data: params[:browser], 30 | os_data: params[:os], 31 | remote_ip: params[:ip], 32 | }) 33 | aud = last.aud 34 | end 35 | respond_with(resource, { aud: aud }) 36 | else 37 | render json: resource.errors, status: 401 38 | end 39 | rescue => e 40 | render json: { error: I18n.t('api.oops') }, status: 500 41 | end 42 | 43 | private 44 | 45 | def current_token 46 | request.env['warden-jwt_auth.token'] 47 | end 48 | 49 | # What we respond with for signing in. 50 | # Add token in with body as fetch+CORS cannot read Authorization header 51 | def respond_with(resource, opts = {}) 52 | # NOTE: the current_token _should_ be the last AllowlistedJwt, but it might not 53 | # be, in case of race conditions and such 54 | render json: { 55 | user: resource.for_display, 56 | jwt: current_token, 57 | # aud: opts[:aud], 58 | } 59 | end 60 | 61 | # Required for sign out 62 | def respond_to_on_destroy 63 | render json: { message: I18n.t('controllers.sessions.sign_out') } 64 | end 65 | end 66 | -------------------------------------------------------------------------------- /app/jobs/application_job.rb: -------------------------------------------------------------------------------- 1 | class ApplicationJob < ActiveJob::Base 2 | # Automatically retry jobs that encountered a deadlock 3 | # retry_on ActiveRecord::Deadlocked 4 | 5 | # Most jobs are safe to ignore if the underlying records are no longer available 6 | # discard_on ActiveJob::DeserializationError 7 | end 8 | -------------------------------------------------------------------------------- /app/mailers/application_mailer.rb: -------------------------------------------------------------------------------- 1 | class ApplicationMailer < ActionMailer::Base 2 | default from: 'from@example.com' 3 | layout 'mailer' 4 | end 5 | -------------------------------------------------------------------------------- /app/models/allowlisted_jwt.rb: -------------------------------------------------------------------------------- 1 | # == Schema Information 2 | # 3 | # Table name: allowlisted_jwts 4 | # 5 | # id :bigint not null, primary key 6 | # user_id :bigint not null 7 | # jti :string not null 8 | # aud :string not null 9 | # exp :datetime not null 10 | # remote_ip :string 11 | # os_data :string 12 | # browser_data :string 13 | # device_data :string 14 | # created_at :datetime not null 15 | # updated_at :datetime not null 16 | # 17 | # Indexes 18 | # 19 | # index_allowlisted_jwts_on_jti (jti) UNIQUE 20 | # index_allowlisted_jwts_on_user_id (user_id) 21 | # 22 | # Foreign Keys 23 | # 24 | # fk_rails_... (user_id => users.id) ON DELETE => cascade 25 | # 26 | class AllowlistedJwt < ApplicationRecord 27 | end 28 | -------------------------------------------------------------------------------- /app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | class ApplicationRecord < ActiveRecord::Base 2 | self.abstract_class = true 3 | end 4 | -------------------------------------------------------------------------------- /app/models/comment.rb: -------------------------------------------------------------------------------- 1 | # == Schema Information 2 | # 3 | # Table name: comments 4 | # 5 | # id :bigint not null, primary key 6 | # commentable_type :string 7 | # commentable_id :bigint 8 | # user_id :bigint 9 | # thread_id :bigint 10 | # parent_id :bigint 11 | # body :text not null 12 | # deleted_at :datetime 13 | # created_at :datetime not null 14 | # updated_at :datetime not null 15 | # 16 | # Indexes 17 | # 18 | # index_comments_on_commentable (commentable_type,commentable_id) 19 | # index_comments_on_parent_id (parent_id) 20 | # index_comments_on_thread_id (thread_id) 21 | # index_comments_on_user_id (user_id) 22 | # 23 | class Comment < ApplicationRecord 24 | CLASSES = [ 25 | Post, 26 | ].freeze 27 | 28 | include Comments::Associations 29 | include Comments::Logic 30 | include Comments::Validations 31 | end 32 | -------------------------------------------------------------------------------- /app/models/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidwparker/programmingtil-rails/9151797fae190b1abb7519240d3245dd58ba5347/app/models/concerns/.keep -------------------------------------------------------------------------------- /app/models/concerns/abilities/commentable.rb: -------------------------------------------------------------------------------- 1 | module Abilities::Commentable 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | has_many :comments, as: :commentable 6 | 7 | def create_comment!(params) 8 | comment = comments.build(params) 9 | save 10 | comment 11 | end 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /app/models/concerns/comments/associations.rb: -------------------------------------------------------------------------------- 1 | module Comments::Associations 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | belongs_to :commentable, polymorphic: true, counter_cache: true 6 | belongs_to :parent, class_name: 'Comment', optional: true 7 | belongs_to :thread, class_name: 'Comment', optional: true 8 | belongs_to :user, optional: true 9 | has_many :children, class_name: 'Comment', foreign_key: :parent_id, dependent: :destroy 10 | has_many :descendents, class_name: 'Comment', foreign_key: :thread_id, dependent: :destroy 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /app/models/concerns/comments/logic.rb: -------------------------------------------------------------------------------- 1 | module Comments::Logic 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | def self.create_comment!(user, params) 6 | klass = from_class_name(params.delete(:commentable_type)) 7 | raise 'Not Commentable' if klass.blank? 8 | klass.find(params.delete(:commentable_id)) 9 | .create_comment!(params.merge({ user_id: user.id})) 10 | end 11 | 12 | def self.delete_comment!(comment) 13 | comment.update!( 14 | body: '[deleted]', 15 | user_id: nil, 16 | deleted_at: Time.now, 17 | ) 18 | comment 19 | end 20 | 21 | def self.update_comment!(comment, params) 22 | comment.update!(body: params[:body]) 23 | comment 24 | end 25 | 26 | def self.from_class_name(klass_name) 27 | ret_class = nil 28 | Comment::CLASSES.detect do |klass| 29 | ret_class = klass if klass.name == klass_name 30 | end 31 | ret_class 32 | end 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /app/models/concerns/comments/validations.rb: -------------------------------------------------------------------------------- 1 | module Comments::Validations 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | validates :body, presence: true 6 | validates :commentable, presence: true 7 | validates :commentable_type, inclusion: { in: Comment::CLASSES.map(&:name) } 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /app/models/concerns/posts/associations.rb: -------------------------------------------------------------------------------- 1 | module Posts::Associations 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | belongs_to :user 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /app/models/concerns/posts/hooks.rb: -------------------------------------------------------------------------------- 1 | module Posts::Hooks 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | before_create :set_comments_cache 6 | 7 | def set_comments_cache 8 | self.comments_count = 0 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /app/models/concerns/posts/logic.rb: -------------------------------------------------------------------------------- 1 | module Posts::Logic 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | def self.create_post!(params, user) 6 | post = Post.new(params.merge({ 7 | user_id: user.id, 8 | })) 9 | post.save! 10 | post 11 | end 12 | 13 | def self.delete_post!(post) 14 | post.destroy! 15 | post 16 | end 17 | 18 | def self.update_post!(post, params) 19 | post.update!(params) 20 | post 21 | end 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /app/models/concerns/posts/scopes.rb: -------------------------------------------------------------------------------- 1 | module Posts::Scopes 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | scope :for_index, ->(params) { 6 | query = includes(:user).order(id: :desc) 7 | query = query.published if params[:published].present? 8 | if params[:rss].present? 9 | query = query.published.limit(5) 10 | end 11 | query 12 | } 13 | scope :published, ->() { 14 | where.not(published_at: nil) 15 | } 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /app/models/concerns/posts/validations.rb: -------------------------------------------------------------------------------- 1 | module Posts::Validations 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | validates :title, presence: true, allow_blank: false 6 | validates :content, presence: true, allow_blank: false 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /app/models/concerns/users/allowlist.rb: -------------------------------------------------------------------------------- 1 | module Users::Allowlist 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | has_many :allowlisted_jwts, dependent: :destroy 6 | 7 | # @see Warden::JWTAuth::Interfaces::RevocationStrategy#jwt_revoked? 8 | def self.jwt_revoked?(payload, user) 9 | !user.allowlisted_jwts.exists?(payload.slice('jti', 'aud')) 10 | end 11 | 12 | # @see Warden::JWTAuth::Interfaces::RevocationStrategy#revoke_jwt 13 | def self.revoke_jwt(payload, user) 14 | jwt = user.allowlisted_jwts.find_by(payload.slice('jti', 'aud')) 15 | jwt.destroy! if jwt 16 | end 17 | end 18 | 19 | # Warden::JWTAuth::Interfaces::User#on_jwt_dispatch 20 | def on_jwt_dispatch(_token, payload) 21 | prev_token = allowlisted_jwts.where(aud: payload['aud']).where.not(exp: ..Time.now).last 22 | token = allowlisted_jwts.create!( 23 | jti: payload['jti'], 24 | aud: payload['aud'], 25 | exp: Time.at(payload['exp'].to_i) 26 | ) 27 | if token.present? && prev_token.present? 28 | token.update_columns({ 29 | browser_data: prev_token.browser_data, 30 | os_data: prev_token.os_data, 31 | remote_ip: prev_token.remote_ip, 32 | }) 33 | # NOTE: don't destroy the previous token right away in case 34 | # user opens new tab, or whatever and needs to do something... 35 | # prev_token.destroy! 36 | end 37 | token 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /app/models/concerns/users/associations.rb: -------------------------------------------------------------------------------- 1 | module Users::Associations 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | has_many :comments, dependent: :nullify 6 | has_many :posts, dependent: :destroy 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /app/models/concerns/users/logic.rb: -------------------------------------------------------------------------------- 1 | module Users::Logic 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | def for_display 6 | { 7 | displayName: display_name, 8 | email: email, 9 | id: id, 10 | username: username, 11 | } 12 | end 13 | 14 | def for_others 15 | { 16 | displayName: display_name.presence || id, 17 | id: id, 18 | slug: slug, 19 | } 20 | end 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /app/models/concerns/users/validations.rb: -------------------------------------------------------------------------------- 1 | module Users::Validations 2 | extend ActiveSupport::Concern 3 | 4 | included do 5 | validates :email, 6 | presence: true, 7 | uniqueness: { case_sensitive: false } 8 | validates :slug, 9 | format: { without: /\A\d+\Z/, message: I18n.t('models.users.slug_numbers') } 10 | validates :username, 11 | presence: true, 12 | length: { minimum: 2 }, 13 | uniqueness: { case_sensitive: false } 14 | validates :username, 15 | format: { with: /\A[a-zA-Z0-9_-]+\z/, message: I18n.t('models.users.username') } 16 | validates :username, 17 | format: { without: /\A\d+\Z/, message: I18n.t('models.users.username_numbers') } 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /app/models/post.rb: -------------------------------------------------------------------------------- 1 | # == Schema Information 2 | # 3 | # Table name: posts 4 | # 5 | # id :bigint not null, primary key 6 | # user_id :bigint not null 7 | # title :string not null 8 | # content :text not null 9 | # published_at :datetime 10 | # created_at :datetime not null 11 | # updated_at :datetime not null 12 | # slug :string 13 | # comments_count :bigint 14 | # 15 | # Indexes 16 | # 17 | # index_posts_on_user_id (user_id) 18 | # 19 | class Post < ApplicationRecord 20 | include Abilities::Commentable 21 | include Posts::Associations 22 | include Posts::Hooks 23 | include Posts::Logic 24 | include Posts::Scopes 25 | include Posts::Validations 26 | 27 | extend FriendlyId 28 | friendly_id :title, use: [:slugged] 29 | end 30 | -------------------------------------------------------------------------------- /app/models/user.rb: -------------------------------------------------------------------------------- 1 | # == Schema Information 2 | # 3 | # Table name: users 4 | # 5 | # id :bigint not null, primary key 6 | # email :string default(""), not null 7 | # encrypted_password :string default(""), not null 8 | # reset_password_token :string 9 | # reset_password_sent_at :datetime 10 | # remember_created_at :datetime 11 | # confirmation_token :string 12 | # confirmed_at :datetime 13 | # confirmation_sent_at :datetime 14 | # unconfirmed_email :string 15 | # created_at :datetime not null 16 | # updated_at :datetime not null 17 | # username :string 18 | # display_name :string 19 | # slug :string 20 | # theme :integer default(0) 21 | # theme_color :integer default(0) 22 | # 23 | # Indexes 24 | # 25 | # index_users_on_confirmation_token (confirmation_token) UNIQUE 26 | # index_users_on_email (email) UNIQUE 27 | # index_users_on_reset_password_token (reset_password_token) UNIQUE 28 | # index_users_on_slug (slug) UNIQUE 29 | # 30 | class User < ApplicationRecord 31 | include Users::Allowlist 32 | include Users::Associations 33 | include Users::Logic 34 | include Users::Validations 35 | 36 | devise :database_authenticatable, 37 | :confirmable, 38 | :registerable, 39 | :recoverable, 40 | :rememberable, 41 | :validatable, 42 | :jwt_authenticatable, 43 | jwt_revocation_strategy: self 44 | 45 | extend FriendlyId 46 | friendly_id :username, use: [:slugged] 47 | 48 | # DEVISE-specific things 49 | # Devise override for logging in with username or email 50 | attr_writer :login 51 | 52 | def login 53 | @login || username || email 54 | end 55 | 56 | # Use :login for searching username and email 57 | def self.find_for_database_authentication(warden_conditions) 58 | conditions = warden_conditions.dup 59 | login = conditions.delete(:login) 60 | where(conditions).where([ 61 | "lower(username) = :value OR lower(email) = :value", 62 | { value: login.strip.downcase }, 63 | ]).first 64 | end 65 | 66 | # Make sure to send the devise emails via async 67 | def send_devise_notification(notification, *args) 68 | devise_mailer.send(notification, self, *args).deliver_later 69 | end 70 | end 71 | -------------------------------------------------------------------------------- /app/policies/application_policy.rb: -------------------------------------------------------------------------------- 1 | class ApplicationPolicy 2 | attr_reader :user, :record 3 | 4 | def initialize(user, record) 5 | @user = user 6 | @record = record 7 | end 8 | 9 | class Scope 10 | attr_reader :user, :scope, :params 11 | 12 | def initialize(user, scope) 13 | @user = user&.user 14 | @params = user&.params 15 | @scope = scope 16 | end 17 | 18 | def resolve 19 | scope.all 20 | end 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /app/policies/comment_policy.rb: -------------------------------------------------------------------------------- 1 | class CommentPolicy < ApplicationPolicy 2 | class Scope < Scope 3 | def resolve 4 | scope.all 5 | end 6 | end 7 | 8 | def create? 9 | true 10 | end 11 | 12 | # Only an user can destroy their own 13 | def destroy? 14 | record.user == user 15 | end 16 | 17 | # Only an user can update their own 18 | def update? 19 | record.user == user 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /app/policies/post_policy.rb: -------------------------------------------------------------------------------- 1 | class PostPolicy < ApplicationPolicy 2 | class Scope < Scope 3 | def resolve 4 | scope.all 5 | end 6 | end 7 | 8 | # Users can only create up to 3 posts 9 | def create? 10 | # user.posts.size < 3 11 | true 12 | end 13 | 14 | # Only an user can destroy their own 15 | def destroy? 16 | record.user == user 17 | end 18 | 19 | # Only an user can update their own 20 | def update? 21 | record.user == user 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /app/serializers/comment_for_post_show_serializer.rb: -------------------------------------------------------------------------------- 1 | class CommentForPostShowSerializer 2 | include FastJsonapi::ObjectSerializer 3 | 4 | set_key_transform :camel_lower 5 | 6 | attributes :id, 7 | :body, 8 | :updated_at 9 | 10 | attribute :user do |comment| 11 | comment.user.for_others 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /app/serializers/comment_index_serializer.rb: -------------------------------------------------------------------------------- 1 | class CommentIndexSerializer 2 | include FastJsonapi::ObjectSerializer 3 | 4 | set_key_transform :camel_lower 5 | 6 | attributes :id, 7 | :body, 8 | :updated_at 9 | 10 | attribute :commentable do |comment| 11 | { 12 | id: comment.commentable_id, 13 | type: comment.commentable_type, 14 | title: comment.commentable.title, 15 | } 16 | end 17 | 18 | attribute :user, if: Proc.new { |comment| comment.user.present? } do |comment| 19 | comment.user.for_others 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /app/serializers/comment_show_serializer.rb: -------------------------------------------------------------------------------- 1 | class CommentShowSerializer 2 | include FastJsonapi::ObjectSerializer 3 | 4 | set_key_transform :camel_lower 5 | 6 | attributes :id, 7 | :body, 8 | :updated_at 9 | 10 | attribute :commentable do |comment| 11 | { 12 | id: comment.commentable_id, 13 | type: comment.commentable_type, 14 | title: comment.commentable.title, 15 | } 16 | end 17 | 18 | attribute :user, if: Proc.new { |comment| comment.user.present? } do |comment| 19 | comment.user.for_others 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /app/serializers/post_index_serializer.rb: -------------------------------------------------------------------------------- 1 | class PostIndexSerializer 2 | include FastJsonapi::ObjectSerializer 3 | 4 | set_key_transform :camel_lower 5 | 6 | attributes :id, 7 | :comments_count, 8 | :content, 9 | :published_at, 10 | :slug, 11 | :title 12 | 13 | attribute :user do |post| 14 | post.user.for_others 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /app/serializers/post_show_serializer.rb: -------------------------------------------------------------------------------- 1 | class PostShowSerializer 2 | include FastJsonapi::ObjectSerializer 3 | 4 | set_key_transform :camel_lower 5 | 6 | attributes :id, 7 | :comments_count, 8 | :content, 9 | :published_at, 10 | :slug, 11 | :title 12 | 13 | # 14 | # Show the most recent 5 comments with the users 15 | # 16 | attribute :comments do |post, params| 17 | comments = post.comments.includes(:user).order(id: :desc) 18 | if params[:all].blank? 19 | comments = comments.limit(5) 20 | end 21 | CommentForPostShowSerializer.new(comments, { is_collection: true }) 22 | end 23 | 24 | attribute :user do |post| 25 | { 26 | displayName: post.user.display_name.presence || post.user_id, 27 | id: post.user_id, 28 | slug: post.user.slug, 29 | } 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /app/serializers/user_show_serializer.rb: -------------------------------------------------------------------------------- 1 | class UserShowSerializer 2 | include FastJsonapi::ObjectSerializer 3 | 4 | set_key_transform :camel_lower 5 | 6 | attributes :id, 7 | :display_name, 8 | :slug 9 | end 10 | -------------------------------------------------------------------------------- /app/views/devise/mailer/confirmation_instructions.html.erb: -------------------------------------------------------------------------------- 1 |

2 | Welcome <%= @resource.username %>! 3 |

4 |

5 | You can confirm your account email through the link below: 6 |

7 |

8 | <%= link_to 'Confirm my account', "#{users_sign_in_url}/?confirmation_token=#{@token}" %> 9 |

10 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.text.erb: -------------------------------------------------------------------------------- 1 | <%= yield %> 2 | -------------------------------------------------------------------------------- /bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # 5 | # This file was generated by Bundler. 6 | # 7 | # The application 'bundle' is installed as part of a gem, and 8 | # this file is here to facilitate running it. 9 | # 10 | 11 | require "rubygems" 12 | 13 | m = Module.new do 14 | module_function 15 | 16 | def invoked_as_script? 17 | File.expand_path($0) == File.expand_path(__FILE__) 18 | end 19 | 20 | def env_var_version 21 | ENV["BUNDLER_VERSION"] 22 | end 23 | 24 | def cli_arg_version 25 | return unless invoked_as_script? # don't want to hijack other binstubs 26 | return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` 27 | bundler_version = nil 28 | update_index = nil 29 | ARGV.each_with_index do |a, i| 30 | if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN 31 | bundler_version = a 32 | end 33 | next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ 34 | bundler_version = $1 35 | update_index = i 36 | end 37 | bundler_version 38 | end 39 | 40 | def gemfile 41 | gemfile = ENV["BUNDLE_GEMFILE"] 42 | return gemfile if gemfile && !gemfile.empty? 43 | 44 | File.expand_path("../../Gemfile", __FILE__) 45 | end 46 | 47 | def lockfile 48 | lockfile = 49 | case File.basename(gemfile) 50 | when "gems.rb" then gemfile.sub(/\.rb$/, gemfile) 51 | else "#{gemfile}.lock" 52 | end 53 | File.expand_path(lockfile) 54 | end 55 | 56 | def lockfile_version 57 | return unless File.file?(lockfile) 58 | lockfile_contents = File.read(lockfile) 59 | return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ 60 | Regexp.last_match(1) 61 | end 62 | 63 | def bundler_version 64 | @bundler_version ||= 65 | env_var_version || cli_arg_version || 66 | lockfile_version 67 | end 68 | 69 | def bundler_requirement 70 | return "#{Gem::Requirement.default}.a" unless bundler_version 71 | 72 | bundler_gem_version = Gem::Version.new(bundler_version) 73 | 74 | requirement = bundler_gem_version.approximate_recommendation 75 | 76 | return requirement unless Gem::Version.new(Gem::VERSION) < Gem::Version.new("2.7.0") 77 | 78 | requirement += ".a" if bundler_gem_version.prerelease? 79 | 80 | requirement 81 | end 82 | 83 | def load_bundler! 84 | ENV["BUNDLE_GEMFILE"] ||= gemfile 85 | 86 | activate_bundler 87 | end 88 | 89 | def activate_bundler 90 | gem_error = activation_error_handling do 91 | gem "bundler", bundler_requirement 92 | end 93 | return if gem_error.nil? 94 | require_error = activation_error_handling do 95 | require "bundler/version" 96 | end 97 | return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) 98 | warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" 99 | exit 42 100 | end 101 | 102 | def activation_error_handling 103 | yield 104 | nil 105 | rescue StandardError, LoadError => e 106 | e 107 | end 108 | end 109 | 110 | m.load_bundler! 111 | 112 | if m.invoked_as_script? 113 | load Gem.bin_path("bundler", "bundle") 114 | end 115 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | load File.expand_path("spring", __dir__) 3 | APP_PATH = File.expand_path('../config/application', __dir__) 4 | require_relative "../config/boot" 5 | require "rails/commands" 6 | -------------------------------------------------------------------------------- /bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | load File.expand_path("spring", __dir__) 3 | require_relative "../config/boot" 4 | require "rake" 5 | Rake.application.run 6 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require "fileutils" 3 | 4 | # path to your application root. 5 | APP_ROOT = File.expand_path('..', __dir__) 6 | 7 | def system!(*args) 8 | system(*args) || abort("\n== Command #{args} failed ==") 9 | end 10 | 11 | FileUtils.chdir APP_ROOT do 12 | # This script is a way to set up or update your development environment automatically. 13 | # This script is idempotent, so that you can run it at any time and get an expectable outcome. 14 | # Add necessary setup steps to this file. 15 | 16 | puts '== Installing dependencies ==' 17 | system! 'gem install bundler --conservative' 18 | system('bundle check') || system!('bundle install') 19 | 20 | # puts "\n== Copying sample files ==" 21 | # unless File.exist?('config/database.yml') 22 | # FileUtils.cp 'config/database.yml.sample', 'config/database.yml' 23 | # end 24 | 25 | puts "\n== Preparing database ==" 26 | system! 'bin/rails db:prepare' 27 | 28 | puts "\n== Removing old logs and tempfiles ==" 29 | system! 'bin/rails log:clear tmp:clear' 30 | 31 | puts "\n== Restarting application server ==" 32 | system! 'bin/rails restart' 33 | end 34 | -------------------------------------------------------------------------------- /bin/spring: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | if !defined?(Spring) && [nil, "development", "test"].include?(ENV["RAILS_ENV"]) 3 | gem "bundler" 4 | require "bundler" 5 | 6 | # Load Spring without loading other gems in the Gemfile, for speed. 7 | Bundler.locked_gems.specs.find { |spec| spec.name == "spring" }&.tap do |spring| 8 | Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path 9 | gem "spring", spring.version 10 | require "spring/binstub" 11 | rescue Gem::LoadError 12 | # Ignore when Spring is not installed. 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require_relative "config/environment" 4 | 5 | run Rails.application 6 | Rails.application.load_server 7 | -------------------------------------------------------------------------------- /config/application.rb: -------------------------------------------------------------------------------- 1 | require_relative "boot" 2 | 3 | require "rails" 4 | # Pick the frameworks you want: 5 | require "active_model/railtie" 6 | require "active_job/railtie" 7 | require "active_record/railtie" 8 | require "active_storage/engine" 9 | require "action_controller/railtie" 10 | require "action_mailer/railtie" 11 | require "action_mailbox/engine" 12 | require "action_text/engine" 13 | require "action_view/railtie" 14 | require "action_cable/engine" 15 | # require "sprockets/railtie" 16 | require "rails/test_unit/railtie" 17 | 18 | # Require the gems listed in Gemfile, including any gems 19 | # you've limited to :test, :development, or :production. 20 | Bundler.require(*Rails.groups) 21 | 22 | module ProgrammingtilRails1 23 | class Application < Rails::Application 24 | # Initialize configuration defaults for originally generated Rails version. 25 | config.load_defaults 6.1 26 | 27 | # Configuration for the application, engines, and railties goes here. 28 | config.autoload_paths << Rails.root.join('lib') 29 | # 30 | # These settings can be overridden in specific environments using the files 31 | # in config/environments, which are processed later. 32 | # 33 | # config.time_zone = "Central Time (US & Canada)" 34 | # config.eager_load_paths << Rails.root.join("extras") 35 | 36 | # Only loads a smaller set of middleware suitable for API only apps. 37 | # Middleware like session, flash, cookies can be added back manually. 38 | # Skip views, helpers and assets when generating a new resource. 39 | config.api_only = true 40 | 41 | # Queues 42 | config.active_job.queue_adapter = :sidekiq 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /config/boot.rb: -------------------------------------------------------------------------------- 1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 2 | 3 | require "bundler/setup" # Set up gems listed in the Gemfile. 4 | require "bootsnap/setup" # Speed up boot time by caching expensive operations. 5 | -------------------------------------------------------------------------------- /config/cable.yml: -------------------------------------------------------------------------------- 1 | development: 2 | adapter: async 3 | 4 | test: 5 | adapter: test 6 | 7 | production: 8 | adapter: redis 9 | url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> 10 | channel_prefix: programmingtil_rails_1_production 11 | -------------------------------------------------------------------------------- /config/credentials.yml.enc: -------------------------------------------------------------------------------- 1 | Y2ALOEnuToZqQvnGcpXmehmTDatOmu9mW5rnbYPs6EeGHYTHsy35uRJKOlZrZnAudq654u9ZDHJcKAz78XtzW/Hn7BZuSMxfBhcRwESS6MMAGAbJDxe3W3ChpuJpgawp2UuHM8TLmk+PsFXSBVZ9DtVD9GggIYbSM9eFFQz4OQWzvkoxSvI361uPM0vlsl9ucIJUrQsCHE8yTxhtHv3mj4heRHRh0zAXWCyIVwjMFFGpL+l6NCUgqMwgU4QH5CakOkqlsr8B04uMODUV2PjfQRc9WA2TSJLRfmIrHwmsbCWh9A8xRaBYWDbOHJ172YQPgmvnFyRPnQ3zNpTeu0BevSsOayi1MVMsiMifasf2hgtbhZ069FPtLyVAKAq6s1e0dnPs1fPD3YY6YqH1noyphGxr4zC432y/IfoTA6XKGl4YHry8yBUOaQZXj8HSWVc4NhG9Vh/wlOMB2354vbqUatGZ8OgNT8n1put4+00T6UIuDZCD--NUABWWfgGiVaeZQs--p6Y1wPBoXfZoCGwMcJcgzw== -------------------------------------------------------------------------------- /config/database.yml: -------------------------------------------------------------------------------- 1 | # PostgreSQL. Versions 9.3 and up are supported. 2 | # 3 | # Install the pg driver: 4 | # gem install pg 5 | # On macOS with Homebrew: 6 | # gem install pg -- --with-pg-config=/usr/local/bin/pg_config 7 | # On macOS with MacPorts: 8 | # gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config 9 | # On Windows: 10 | # gem install pg 11 | # Choose the win32 build. 12 | # Install PostgreSQL and put its /bin directory on your path. 13 | # 14 | # Configure Using Gemfile 15 | # gem 'pg' 16 | # 17 | default: &default 18 | adapter: postgresql 19 | encoding: unicode 20 | # For details on connection pooling, see Rails configuration guide 21 | # https://guides.rubyonrails.org/configuring.html#database-pooling 22 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> 23 | 24 | development: 25 | <<: *default 26 | database: programmingtil_rails_1_development 27 | host: 127.0.0.1 28 | 29 | # The specified database role being used to connect to postgres. 30 | # To create additional roles in postgres see `$ createuser --help`. 31 | # When left blank, postgres will use the default role. This is 32 | # the same name as the operating system user running Rails. 33 | #username: programmingtil_rails_1 34 | 35 | # The password associated with the postgres role (username). 36 | #password: 37 | 38 | # Connect on a TCP socket. Omitted by default since the client uses a 39 | # domain socket that doesn't need configuration. Windows does not have 40 | # domain sockets, so uncomment these lines. 41 | #host: localhost 42 | 43 | # The TCP port the server listens on. Defaults to 5432. 44 | # If your server runs on a different port number, change accordingly. 45 | #port: 5432 46 | 47 | # Schema search path. The server defaults to $user,public 48 | #schema_search_path: myapp,sharedapp,public 49 | 50 | # Minimum log levels, in increasing order: 51 | # debug5, debug4, debug3, debug2, debug1, 52 | # log, notice, warning, error, fatal, and panic 53 | # Defaults to warning. 54 | #min_messages: notice 55 | 56 | # Warning: The database defined as "test" will be erased and 57 | # re-generated from your development database when you run "rake". 58 | # Do not set this db to the same as development or production. 59 | test: 60 | <<: *default 61 | database: programmingtil_rails_1_test 62 | password: <%= ENV['POSTGRES_PASSWORD'] %> 63 | username: <%= ENV['POSTGRES_USER'] %> 64 | host: 127.0.0.1 65 | 66 | # As with config/credentials.yml, you never want to store sensitive information, 67 | # like your database password, in your source code. If your source code is 68 | # ever seen by anyone, they now have access to your database. 69 | # 70 | # Instead, provide the password or a full connection URL as an environment 71 | # variable when you boot the app. For example: 72 | # 73 | # DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" 74 | # 75 | # If the connection URL is provided in the special DATABASE_URL environment 76 | # variable, Rails will automatically merge its configuration values on top of 77 | # the values provided in this file. Alternatively, you can specify a connection 78 | # URL environment variable explicitly: 79 | # 80 | # production: 81 | # url: <%= ENV['MY_APP_DATABASE_URL'] %> 82 | # 83 | # Read https://guides.rubyonrails.org/configuring.html#configuring-a-database 84 | # for a full overview on how database connection configuration can be specified. 85 | # 86 | production: 87 | <<: *default 88 | database: programmingtil_rails_1_production 89 | username: programmingtil_rails_1 90 | password: <%= ENV['PROGRAMMINGTIL_RAILS_1_DATABASE_PASSWORD'] %> 91 | -------------------------------------------------------------------------------- /config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require_relative "application" 3 | 4 | # Initialize the Rails application. 5 | Rails.application.initialize! 6 | -------------------------------------------------------------------------------- /config/environments/development.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # In the development environment your application's code is reloaded any time 7 | # it changes. This slows down response time but is perfect for development 8 | # since you don't have to restart the web server when you make code changes. 9 | config.cache_classes = false 10 | 11 | # Do not eager load code on boot. 12 | config.eager_load = false 13 | 14 | # Show full error reports. 15 | config.consider_all_requests_local = true 16 | 17 | # Enable/disable caching. By default caching is disabled. 18 | # Run rails dev:cache to toggle caching. 19 | if Rails.root.join('tmp', 'caching-dev.txt').exist? 20 | config.cache_store = :memory_store 21 | config.public_file_server.headers = { 22 | 'Cache-Control' => "public, max-age=#{2.days.to_i}" 23 | } 24 | else 25 | config.action_controller.perform_caching = false 26 | 27 | config.cache_store = :null_store 28 | end 29 | 30 | # Store uploaded files on the local file system (see config/storage.yml for options). 31 | config.active_storage.service = :local 32 | 33 | # Don't care if the mailer can't send. 34 | config.action_mailer.default_url_options = { host: 'localhost', port: 5000 } 35 | config.action_mailer.delivery_method = :letter_opener 36 | config.action_mailer.raise_delivery_errors = false 37 | config.action_mailer.perform_caching = false 38 | config.action_mailer.perform_deliveries = true 39 | 40 | # Print deprecation notices to the Rails logger. 41 | config.active_support.deprecation = :log 42 | 43 | # Raise exceptions for disallowed deprecations. 44 | config.active_support.disallowed_deprecation = :raise 45 | 46 | # Tell Active Support which deprecation messages to disallow. 47 | config.active_support.disallowed_deprecation_warnings = [] 48 | 49 | # Raise an error on page load if there are pending migrations. 50 | config.active_record.migration_error = :page_load 51 | 52 | # Highlight code that triggered database queries in logs. 53 | config.active_record.verbose_query_logs = true 54 | 55 | 56 | # Raises error for missing translations. 57 | # config.i18n.raise_on_missing_translations = true 58 | 59 | # Annotate rendered view with file names. 60 | # config.action_view.annotate_rendered_view_with_filenames = true 61 | 62 | # Use an evented file watcher to asynchronously detect changes in source code, 63 | # routes, locales, etc. This feature depends on the listen gem. 64 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker 65 | 66 | # Uncomment if you wish to allow Action Cable access from any origin. 67 | # config.action_cable.disable_request_forgery_protection = true 68 | end 69 | -------------------------------------------------------------------------------- /config/environments/production.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # Code is not reloaded between requests. 7 | config.cache_classes = true 8 | 9 | # Eager load code on boot. This eager loads most of Rails and 10 | # your application in memory, allowing both threaded web servers 11 | # and those relying on copy on write to perform better. 12 | # Rake tasks automatically ignore this option for performance. 13 | config.eager_load = true 14 | 15 | # Full error reports are disabled and caching is turned on. 16 | config.consider_all_requests_local = false 17 | 18 | # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] 19 | # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). 20 | # config.require_master_key = true 21 | 22 | # Disable serving static files from the `/public` folder by default since 23 | # Apache or NGINX already handles this. 24 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 25 | 26 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 27 | # config.asset_host = 'http://assets.example.com' 28 | 29 | # Specifies the header that your server uses for sending files. 30 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 31 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 32 | 33 | # Store uploaded files on the local file system (see config/storage.yml for options). 34 | config.active_storage.service = :local 35 | 36 | # Mount Action Cable outside main process or domain. 37 | # config.action_cable.mount_path = nil 38 | # config.action_cable.url = 'wss://example.com/cable' 39 | # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] 40 | 41 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 42 | # config.force_ssl = true 43 | 44 | # Include generic and useful information about system operation, but avoid logging too much 45 | # information to avoid inadvertent exposure of personally identifiable information (PII). 46 | config.log_level = :info 47 | 48 | # Prepend all log lines with the following tags. 49 | config.log_tags = [ :request_id ] 50 | 51 | # Use a different cache store in production. 52 | # config.cache_store = :mem_cache_store 53 | 54 | # Use a real queuing backend for Active Job (and separate queues per environment). 55 | # config.active_job.queue_adapter = :resque 56 | # config.active_job.queue_name_prefix = "programmingtil_rails_1_production" 57 | 58 | config.action_mailer.perform_caching = false 59 | 60 | # Ignore bad email addresses and do not raise email delivery errors. 61 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 62 | # config.action_mailer.raise_delivery_errors = false 63 | 64 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 65 | # the I18n.default_locale when a translation cannot be found). 66 | config.i18n.fallbacks = true 67 | 68 | # Send deprecation notices to registered listeners. 69 | config.active_support.deprecation = :notify 70 | 71 | # Log disallowed deprecations. 72 | config.active_support.disallowed_deprecation = :log 73 | 74 | # Tell Active Support which deprecation messages to disallow. 75 | config.active_support.disallowed_deprecation_warnings = [] 76 | 77 | # Use default logging formatter so that PID and timestamp are not suppressed. 78 | config.log_formatter = ::Logger::Formatter.new 79 | 80 | # Use a different logger for distributed setups. 81 | # require "syslog/logger" 82 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 83 | 84 | if ENV["RAILS_LOG_TO_STDOUT"].present? 85 | logger = ActiveSupport::Logger.new(STDOUT) 86 | logger.formatter = config.log_formatter 87 | config.logger = ActiveSupport::TaggedLogging.new(logger) 88 | end 89 | 90 | # Do not dump schema after migrations. 91 | config.active_record.dump_schema_after_migration = false 92 | 93 | # Inserts middleware to perform automatic connection switching. 94 | # The `database_selector` hash is used to pass options to the DatabaseSelector 95 | # middleware. The `delay` is used to determine how long to wait after a write 96 | # to send a subsequent read to the primary. 97 | # 98 | # The `database_resolver` class is used by the middleware to determine which 99 | # database is appropriate to use based on the time delay. 100 | # 101 | # The `database_resolver_context` class is used by the middleware to set 102 | # timestamps for the last write to the primary. The resolver uses the context 103 | # class timestamps to determine how long to wait before reading from the 104 | # replica. 105 | # 106 | # By default Rails will store a last write timestamp in the session. The 107 | # DatabaseSelector middleware is designed as such you can define your own 108 | # strategy for connection switching and pass that into the middleware through 109 | # these configuration options. 110 | # config.active_record.database_selector = { delay: 2.seconds } 111 | # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver 112 | # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session 113 | 114 | Rails.application.routes.default_url_options[:host]= ENV['HOST_URL'] 115 | 116 | ActionMailer::Base.smtp_settings = { 117 | :authentication => :plain, 118 | :address => ENV['MAIL_PROVIDER_ADDRESS'], 119 | :port => ENV['MAIL_PROVIDER_PORT'], 120 | :user_name => ENV['MAIL_PROVIDER_USERNAME'], 121 | :password => ENV['MAIL_PROVIDER_PASSWORD'], 122 | # :domain => 'heroku.com', 123 | :enable_starttls_auto => true 124 | } 125 | end 126 | -------------------------------------------------------------------------------- /config/environments/staging.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # Code is not reloaded between requests. 5 | config.cache_classes = true 6 | 7 | # Eager load code on boot. This eager loads most of Rails and 8 | # your application in memory, allowing both threaded web servers 9 | # and those relying on copy on write to perform better. 10 | # Rake tasks automatically ignore this option for performance. 11 | config.eager_load = true 12 | 13 | # Full error reports are disabled and caching is turned on. 14 | config.consider_all_requests_local = false 15 | config.action_controller.perform_caching = true 16 | 17 | # Ensures that a master key has been made available in either ENV['RAILS_MASTER_KEY'] 18 | # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). 19 | # config.require_master_key = true 20 | 21 | # Disable serving static files from the `/public` folder by default since 22 | # Apache or NGINX already handles this. 23 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 24 | 25 | # Compress CSS using a preprocessor. 26 | # config.assets.css_compressor = :sass 27 | 28 | # Do not fallback to assets pipeline if a precompiled asset is missed. 29 | # config.assets.compile = false 30 | 31 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 32 | # config.action_controller.asset_host = 'http://assets.example.com' 33 | 34 | # Specifies the header that your server uses for sending files. 35 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 36 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 37 | 38 | # Store uploaded files on the local file system (see config/storage.yml for options). 39 | config.active_storage.queues.analysis = :default 40 | config.active_storage.queues.mirror = :default 41 | config.active_storage.queues.purge = :default 42 | # config.active_storage.service = :amazon 43 | 44 | # Mount Action Cable outside main process or domain. 45 | # config.action_cable.mount_path = nil 46 | # config.action_cable.url = 'wss://example.com/cable' 47 | # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] 48 | 49 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 50 | # Cloudflare is handling SSL, turn off here. 51 | # config.force_ssl = true 52 | 53 | # Use the lowest log level to ensure availability of diagnostic information 54 | # when problems arise. 55 | config.log_level = :debug 56 | 57 | # Prepend all log lines with the following tags. 58 | config.log_tags = [ :request_id ] 59 | 60 | # Use a different cache store in production. 61 | # config.cache_store = :mem_cache_store 62 | 63 | # Use a real queuing backend for Active Job (and separate queues per environment). 64 | # config.active_job.queue_adapter = :resque 65 | config.active_job.queue_name_prefix = "ptil_rails_staging" 66 | 67 | config.action_mailer.perform_caching = false 68 | config.action_mailer.deliver_later_queue_name = :mailers 69 | 70 | # Ignore bad email addresses and do not raise email delivery errors. 71 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 72 | # config.action_mailer.raise_delivery_errors = false 73 | 74 | # action_mailbox queues 75 | config.action_mailbox.queues.incineration :default 76 | config.action_mailbox.queues.routing = :default 77 | 78 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 79 | # the I18n.default_locale when a translation cannot be found). 80 | config.i18n.fallbacks = true 81 | 82 | # Send deprecation notices to registered listeners. 83 | config.active_support.deprecation = :notify 84 | 85 | # Use default logging formatter so that PID and timestamp are not suppressed. 86 | config.log_formatter = ::Logger::Formatter.new 87 | 88 | # Use a different logger for distributed setups. 89 | # require 'syslog/logger' 90 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 91 | 92 | if ENV['RAILS_LOG_TO_STDOUT'].present? 93 | logger = ActiveSupport::Logger.new(STDOUT) 94 | logger.formatter = config.log_formatter 95 | config.logger = ActiveSupport::TaggedLogging.new(logger) 96 | end 97 | 98 | # Do not dump schema after migrations. 99 | config.active_record.dump_schema_after_migration = false 100 | # config.active_record.queues.destroy = :default 101 | 102 | # Inserts middleware to perform automatic connection switching. 103 | # The `database_selector` hash is used to pass options to the DatabaseSelector 104 | # middleware. The `delay` is used to determine how long to wait after a write 105 | # to send a subsequent read to the primary. 106 | # 107 | # The `database_resolver` class is used by the middleware to determine which 108 | # database is appropriate to use based on the time delay. 109 | # 110 | # The `database_resolver_context` class is used by the middleware to set 111 | # timestamps for the last write to the primary. The resolver uses the context 112 | # class timestamps to determine how long to wait before reading from the 113 | # replica. 114 | # 115 | # By default Rails will store a last write timestamp in the session. The 116 | # DatabaseSelector middleware is designed as such you can define your own 117 | # strategy for connection switching and pass that into the middleware through 118 | # these configuration options. 119 | # config.active_record.database_selector = { delay: 2.seconds } 120 | # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver 121 | # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session 122 | 123 | Rails.application.routes.default_url_options[:host]= ENV['HOST_URL'] 124 | 125 | ActionMailer::Base.smtp_settings = { 126 | :authentication => :plain, 127 | :address => ENV['MAIL_PROVIDER_ADDRESS'], 128 | :port => ENV['MAIL_PROVIDER_PORT'], 129 | :user_name => ENV['MAIL_PROVIDER_USERNAME'], 130 | :password => ENV['MAIL_PROVIDER_PASSWORD'], 131 | # :domain => 'heroku.com', 132 | :enable_starttls_auto => true 133 | } 134 | end 135 | -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | # The test environment is used exclusively to run your application's 4 | # test suite. You never need to work with it otherwise. Remember that 5 | # your test database is "scratch space" for the test suite and is wiped 6 | # and recreated between test runs. Don't rely on the data there! 7 | 8 | Rails.application.configure do 9 | # Settings specified here will take precedence over those in config/application.rb. 10 | 11 | config.cache_classes = false 12 | config.action_view.cache_template_loading = true 13 | 14 | # Do not eager load code on boot. This avoids loading your whole application 15 | # just for the purpose of running a single test. If you are using a tool that 16 | # preloads Rails for running tests, you may have to set it to true. 17 | config.eager_load = false 18 | 19 | # Configure public file server for tests with Cache-Control for performance. 20 | config.public_file_server.enabled = true 21 | config.public_file_server.headers = { 22 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}" 23 | } 24 | 25 | # Show full error reports and disable caching. 26 | config.consider_all_requests_local = true 27 | config.action_controller.perform_caching = false 28 | config.cache_store = :null_store 29 | 30 | # Raise exceptions instead of rendering exception templates. 31 | config.action_dispatch.show_exceptions = false 32 | 33 | # Disable request forgery protection in test environment. 34 | config.action_controller.allow_forgery_protection = false 35 | 36 | # Store uploaded files on the local file system in a temporary directory. 37 | config.active_storage.service = :test 38 | 39 | config.action_mailer.perform_caching = false 40 | 41 | # Tell Action Mailer not to deliver emails to the real world. 42 | # The :test delivery method accumulates sent emails in the 43 | # ActionMailer::Base.deliveries array. 44 | config.action_mailer.delivery_method = :test 45 | 46 | # Print deprecation notices to the stderr. 47 | config.active_support.deprecation = :stderr 48 | 49 | # Raise exceptions for disallowed deprecations. 50 | config.active_support.disallowed_deprecation = :raise 51 | 52 | # Tell Active Support which deprecation messages to disallow. 53 | config.active_support.disallowed_deprecation_warnings = [] 54 | 55 | # Raises error for missing translations. 56 | # config.i18n.raise_on_missing_translations = true 57 | 58 | # Annotate rendered view with file names. 59 | # config.action_view.annotate_rendered_view_with_filenames = true 60 | end 61 | -------------------------------------------------------------------------------- /config/initializers/application_controller_renderer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # ActiveSupport::Reloader.to_prepare do 4 | # ApplicationController.renderer.defaults.merge!( 5 | # http_host: 'example.org', 6 | # https: false 7 | # ) 8 | # end 9 | -------------------------------------------------------------------------------- /config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| /my_noisy_library/.match?(line) } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code 7 | # by setting BACKTRACE=1 before calling your invocation, like "BACKTRACE=1 ./bin/rails runner 'MyClass.perform'". 8 | Rails.backtrace_cleaner.remove_silencers! if ENV["BACKTRACE"] 9 | -------------------------------------------------------------------------------- /config/initializers/cors.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Avoid CORS issues when API is called from the frontend app. 4 | # Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. 5 | 6 | # Read more: https://github.com/cyu/rack-cors 7 | 8 | Rails.application.config.middleware.insert_before 0, Rack::Cors do 9 | if Rails.env.development? 10 | origins = [ 11 | 'localhost:3000', 'localhost:3001', 'localhost:5000', 12 | 'staging.xyz.com', 'www.xyz.com', 13 | ].freeze 14 | allow do 15 | origins origins 16 | resource '*', 17 | headers: :any, 18 | methods: %i(get post put patch delete options head) 19 | end 20 | else 21 | origins = [ 22 | 'staging.xyz.com', 'www.xyz.com', 23 | ].freeze 24 | allow do 25 | origins origins 26 | resource '*', 27 | headers: :any, 28 | methods: %i(get post put patch delete options head) 29 | end 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /config/initializers/devise.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Assuming you have not yet modified this file, each configuration option below 4 | # is set to its default value. Note that some are commented out while others 5 | # are not: uncommented lines are intended to protect your configuration from 6 | # breaking changes in upgrades (i.e., in the event that future versions of 7 | # Devise change the default values for those options). 8 | # 9 | # Use this hook to configure devise mailer, warden hooks and so forth. 10 | # Many of these configuration options can be set straight in your model. 11 | Devise.setup do |config| 12 | # The secret key used by Devise. Devise uses this key to generate 13 | # random tokens. Changing this key will render invalid all existing 14 | # confirmation, reset password and unlock tokens in the database. 15 | # Devise will use the `secret_key_base` as its `secret_key` 16 | # by default. You can change it below and use your own secret key. 17 | # config.secret_key = '298cf921ab15f2f35d7123aa766d9971f23b0ed88845c030362d1354e3ce142bda07355cafc412978bd97e1c8db5505d303e2275e683a8364cb4ba7bdad254d0' 18 | 19 | # ==> Controller configuration 20 | # Configure the parent class to the devise controllers. 21 | # config.parent_controller = 'DeviseController' 22 | 23 | # ==> Mailer Configuration 24 | # Configure the e-mail address which will be shown in Devise::Mailer, 25 | # note that it will be overwritten if you use your own mailer class 26 | # with default "from" parameter. 27 | config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' 28 | 29 | # Configure the class responsible to send e-mails. 30 | # config.mailer = 'Devise::Mailer' 31 | 32 | # Configure the parent class responsible to send e-mails. 33 | # config.parent_mailer = 'ActionMailer::Base' 34 | 35 | # ==> ORM configuration 36 | # Load and configure the ORM. Supports :active_record (default) and 37 | # :mongoid (bson_ext recommended) by default. Other ORMs may be 38 | # available as additional gems. 39 | require 'devise/orm/active_record' 40 | 41 | # ==> Configuration for any authentication mechanism 42 | # Configure which keys are used when authenticating a user. The default is 43 | # just :email. You can configure it to use [:username, :subdomain], so for 44 | # authenticating a user, both parameters are required. Remember that those 45 | # parameters are used only when authenticating and not when retrieving from 46 | # session. If you need permissions, you should implement that in a before filter. 47 | # You can also supply a hash where the value is a boolean determining whether 48 | # or not authentication should be aborted when the value is not present. 49 | config.authentication_keys = [:login] 50 | 51 | # Configure parameters from the request object used for authentication. Each entry 52 | # given should be a request method and it will automatically be passed to the 53 | # find_for_authentication method and considered in your model lookup. For instance, 54 | # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. 55 | # The same considerations mentioned for authentication_keys also apply to request_keys. 56 | # config.request_keys = [] 57 | 58 | # Configure which authentication keys should be case-insensitive. 59 | # These keys will be downcased upon creating or modifying a user and when used 60 | # to authenticate or find a user. Default is :email. 61 | config.case_insensitive_keys = [:login] 62 | 63 | # Configure which authentication keys should have whitespace stripped. 64 | # These keys will have whitespace before and after removed upon creating or 65 | # modifying a user and when used to authenticate or find a user. Default is :email. 66 | config.strip_whitespace_keys = [:email] 67 | 68 | # Tell if authentication through request.params is enabled. True by default. 69 | # It can be set to an array that will enable params authentication only for the 70 | # given strategies, for example, `config.params_authenticatable = [:database]` will 71 | # enable it only for database (email + password) authentication. 72 | # config.params_authenticatable = true 73 | 74 | # Tell if authentication through HTTP Auth is enabled. False by default. 75 | # It can be set to an array that will enable http authentication only for the 76 | # given strategies, for example, `config.http_authenticatable = [:database]` will 77 | # enable it only for database authentication. 78 | # For API-only applications to support authentication "out-of-the-box", you will likely want to 79 | # enable this with :database unless you are using a custom strategy. 80 | # The supported strategies are: 81 | # :database = Support basic authentication with authentication key + password 82 | # config.http_authenticatable = false 83 | 84 | # If 401 status code should be returned for AJAX requests. True by default. 85 | # config.http_authenticatable_on_xhr = true 86 | 87 | # The realm used in Http Basic Authentication. 'Application' by default. 88 | # config.http_authentication_realm = 'Application' 89 | 90 | # It will change confirmation, password recovery and other workflows 91 | # to behave the same regardless if the e-mail provided was right or wrong. 92 | # Does not affect registerable. 93 | # config.paranoid = true 94 | 95 | # By default Devise will store the user in session. You can skip storage for 96 | # particular strategies by setting this option. 97 | # Notice that if you are skipping storage for all authentication paths, you 98 | # may want to disable generating routes to Devise's sessions controller by 99 | # passing skip: :sessions to `devise_for` in your config/routes.rb 100 | config.skip_session_storage = [:http_auth] 101 | 102 | # By default, Devise cleans up the CSRF token on authentication to 103 | # avoid CSRF token fixation attacks. This means that, when using AJAX 104 | # requests for sign in and sign up, you need to get a new CSRF token 105 | # from the server. You can disable this option at your own risk. 106 | # config.clean_up_csrf_token_on_authentication = true 107 | 108 | # When false, Devise will not attempt to reload routes on eager load. 109 | # This can reduce the time taken to boot the app but if your application 110 | # requires the Devise mappings to be loaded during boot time the application 111 | # won't boot properly. 112 | # config.reload_routes = true 113 | 114 | # ==> Configuration for :database_authenticatable 115 | # For bcrypt, this is the cost for hashing the password and defaults to 12. If 116 | # using other algorithms, it sets how many times you want the password to be hashed. 117 | # The number of stretches used for generating the hashed password are stored 118 | # with the hashed password. This allows you to change the stretches without 119 | # invalidating existing passwords. 120 | # 121 | # Limiting the stretches to just one in testing will increase the performance of 122 | # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use 123 | # a value less than 10 in other environments. Note that, for bcrypt (the default 124 | # algorithm), the cost increases exponentially with the number of stretches (e.g. 125 | # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). 126 | config.stretches = Rails.env.test? ? 1 : 12 127 | 128 | # Set up a pepper to generate the hashed password. 129 | # config.pepper = 'bb36a8caae58940fbe41d3e7b49f0e09d544dbb8ffb4834cbad2b5ffc2d58ab675c60a383841555207e2e5468f782a9619b156860b9635082dcc870137f0dad3' 130 | 131 | # Send a notification to the original email when the user's email is changed. 132 | config.send_email_changed_notification = true 133 | 134 | # Send a notification email when the user's password is changed. 135 | config.send_password_change_notification = true 136 | 137 | # ==> Configuration for :confirmable 138 | # A period that the user is allowed to access the website even without 139 | # confirming their account. For instance, if set to 2.days, the user will be 140 | # able to access the website for two days without confirming their account, 141 | # access will be blocked just in the third day. 142 | # You can also set it to nil, which will allow the user to access the website 143 | # without confirming their account. 144 | # Default is 0.days, meaning the user cannot access the website without 145 | # confirming their account. 146 | # config.allow_unconfirmed_access_for = 2.days 147 | 148 | # A period that the user is allowed to confirm their account before their 149 | # token becomes invalid. For example, if set to 3.days, the user can confirm 150 | # their account within 3 days after the mail was sent, but on the fourth day 151 | # their account can't be confirmed with the token any more. 152 | # Default is nil, meaning there is no restriction on how long a user can take 153 | # before confirming their account. 154 | # config.confirm_within = 3.days 155 | 156 | # If true, requires any email changes to be confirmed (exactly the same way as 157 | # initial account confirmation) to be applied. Requires additional unconfirmed_email 158 | # db field (see migrations). Until confirmed, new email is stored in 159 | # unconfirmed_email column, and copied to email column on successful confirmation. 160 | config.reconfirmable = true 161 | 162 | # Defines which key will be used when confirming an account 163 | # config.confirmation_keys = [:email] 164 | 165 | # ==> Configuration for :rememberable 166 | # The time the user will be remembered without asking for credentials again. 167 | # config.remember_for = 2.weeks 168 | 169 | # Invalidates all the remember me tokens when the user signs out. 170 | config.expire_all_remember_me_on_sign_out = true 171 | 172 | # If true, extends the user's remember period when remembered via cookie. 173 | # config.extend_remember_period = false 174 | 175 | # Options to be passed to the created cookie. For instance, you can set 176 | # secure: true in order to force SSL only cookies. 177 | # config.rememberable_options = {} 178 | 179 | # ==> Configuration for :validatable 180 | # Range for password length. 181 | config.password_length = 6..128 182 | 183 | # Email regex used to validate email formats. It simply asserts that 184 | # one (and only one) @ exists in the given string. This is mainly 185 | # to give user feedback and not to assert the e-mail validity. 186 | config.email_regexp = /\A[^@\s]+@[^@\s]+\z/ 187 | 188 | # ==> Configuration for :timeoutable 189 | # The time you want to timeout the user session without activity. After this 190 | # time the user will be asked for credentials again. Default is 30 minutes. 191 | # config.timeout_in = 30.minutes 192 | 193 | # ==> Configuration for :lockable 194 | # Defines which strategy will be used to lock an account. 195 | # :failed_attempts = Locks an account after a number of failed attempts to sign in. 196 | # :none = No lock strategy. You should handle locking by yourself. 197 | # config.lock_strategy = :failed_attempts 198 | 199 | # Defines which key will be used when locking and unlocking an account 200 | # config.unlock_keys = [:email] 201 | 202 | # Defines which strategy will be used to unlock an account. 203 | # :email = Sends an unlock link to the user email 204 | # :time = Re-enables login after a certain amount of time (see :unlock_in below) 205 | # :both = Enables both strategies 206 | # :none = No unlock strategy. You should handle unlocking by yourself. 207 | # config.unlock_strategy = :both 208 | 209 | # Number of authentication tries before locking an account if lock_strategy 210 | # is failed attempts. 211 | # config.maximum_attempts = 20 212 | 213 | # Time interval to unlock the account if :time is enabled as unlock_strategy. 214 | # config.unlock_in = 1.hour 215 | 216 | # Warn on the last attempt before the account is locked. 217 | # config.last_attempt_warning = true 218 | 219 | # ==> Configuration for :recoverable 220 | # 221 | # Defines which key will be used when recovering the password for an account 222 | # config.reset_password_keys = [:email] 223 | 224 | # Time interval you can reset your password with a reset password key. 225 | # Don't put a too small interval or your users won't have the time to 226 | # change their passwords. 227 | config.reset_password_within = 6.hours 228 | 229 | # When set to false, does not sign a user in automatically after their password is 230 | # reset. Defaults to true, so a user is signed in automatically after a reset. 231 | # config.sign_in_after_reset_password = true 232 | 233 | # ==> Configuration for :encryptable 234 | # Allow you to use another hashing or encryption algorithm besides bcrypt (default). 235 | # You can use :sha1, :sha512 or algorithms from others authentication tools as 236 | # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20 237 | # for default behavior) and :restful_authentication_sha1 (then you should set 238 | # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper). 239 | # 240 | # Require the `devise-encryptable` gem when using anything other than bcrypt 241 | # config.encryptor = :sha512 242 | 243 | # ==> Scopes configuration 244 | # Turn scoped views on. Before rendering "sessions/new", it will first check for 245 | # "users/sessions/new". It's turned off by default because it's slower if you 246 | # are using only default views. 247 | # config.scoped_views = false 248 | 249 | # Configure the default scope given to Warden. By default it's the first 250 | # devise role declared in your routes (usually :user). 251 | # config.default_scope = :user 252 | 253 | # Set this configuration to false if you want /users/sign_out to sign out 254 | # only the current scope. By default, Devise signs out all scopes. 255 | # config.sign_out_all_scopes = true 256 | 257 | # ==> Navigation configuration 258 | # Lists the formats that should be treated as navigational. Formats like 259 | # :html, should redirect to the sign in page when the user does not have 260 | # access, but formats like :xml or :json, should return 401. 261 | # 262 | # If you have any extra navigational formats, like :iphone or :mobile, you 263 | # should add them to the navigational formats lists. 264 | # 265 | # The "*/*" below is required to match Internet Explorer requests. 266 | # config.navigational_formats = ['*/*', :html] 267 | 268 | # The default HTTP method used to sign out a resource. Default is :delete. 269 | config.sign_out_via = :delete 270 | 271 | # ==> OmniAuth 272 | # Add a new OmniAuth provider. Check the wiki for more information on setting 273 | # up on your models and hooks. 274 | # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' 275 | 276 | # ==> Warden configuration 277 | # If you want to use other strategies, that are not supported by Devise, or 278 | # change the failure app, you can configure them inside the config.warden block. 279 | # 280 | # config.warden do |manager| 281 | # manager.intercept_401 = false 282 | # manager.default_strategies(scope: :user).unshift :some_external_strategy 283 | # end 284 | config.warden do |manager| 285 | manager.failure_app = DeviseCustomFailure 286 | end 287 | 288 | # ==> Mountable engine configurations 289 | # When using Devise inside an engine, let's call it `MyEngine`, and this engine 290 | # is mountable, there are some extra configurations to be taken into account. 291 | # The following options are available, assuming the engine is mounted as: 292 | # 293 | # mount MyEngine, at: '/my_engine' 294 | # 295 | # The router that invoked `devise_for`, in the example above, would be: 296 | # config.router_name = :my_engine 297 | # 298 | # When using OmniAuth, Devise cannot automatically set OmniAuth path, 299 | # so you need to do it manually. For the users scope, it would be: 300 | # config.omniauth_path_prefix = '/my_engine/users/auth' 301 | 302 | # ==> Turbolinks configuration 303 | # If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly: 304 | # 305 | # ActiveSupport.on_load(:devise_failure_app) do 306 | # include Turbolinks::Controller 307 | # end 308 | 309 | # ==> Configuration for :registerable 310 | 311 | # When set to false, does not sign a user in automatically after their password is 312 | # changed. Defaults to true, so a user is signed in automatically after changing a password. 313 | # config.sign_in_after_change_password = true 314 | 315 | config.jwt do |jwt| 316 | jwt.secret = ENV['DEVISE_JWT_SECRET_KEY'] 317 | jwt.dispatch_requests = [ 318 | ['POST', %r{^/signin$}], 319 | ] 320 | jwt.revocation_requests = [ 321 | ['DELETE', %r{^/signout$}] 322 | ] 323 | jwt.expiration_time = 14.days.to_i 324 | # Use default aud_header 325 | jwt.aud_header = 'JWT_AUD' 326 | end 327 | end 328 | -------------------------------------------------------------------------------- /config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure sensitive parameters which will be filtered from the log file. 4 | Rails.application.config.filter_parameters += [ 5 | :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn 6 | ] 7 | -------------------------------------------------------------------------------- /config/initializers/friendly_id.rb: -------------------------------------------------------------------------------- 1 | # FriendlyId Global Configuration 2 | # 3 | # Use this to set up shared configuration options for your entire application. 4 | # Any of the configuration options shown here can also be applied to single 5 | # models by passing arguments to the `friendly_id` class method or defining 6 | # methods in your model. 7 | # 8 | # To learn more, check out the guide: 9 | # 10 | # http://norman.github.io/friendly_id/file.Guide.html 11 | 12 | FriendlyId.defaults do |config| 13 | # ## Reserved Words 14 | # 15 | # Some words could conflict with Rails's routes when used as slugs, or are 16 | # undesirable to allow as slugs. Edit this list as needed for your app. 17 | config.use :reserved 18 | 19 | config.reserved_words = %w(new edit index session login logout users admin 20 | stylesheets assets javascripts images) 21 | 22 | # This adds an option to treat reserved words as conflicts rather than exceptions. 23 | # When there is no good candidate, a UUID will be appended, matching the existing 24 | # conflict behavior. 25 | 26 | # config.treat_reserved_as_conflict = true 27 | 28 | # ## Friendly Finders 29 | # 30 | # Uncomment this to use friendly finders in all models. By default, if 31 | # you wish to find a record by its friendly id, you must do: 32 | # 33 | # MyModel.friendly.find('foo') 34 | # 35 | # If you uncomment this, you can do: 36 | # 37 | # MyModel.find('foo') 38 | # 39 | # This is significantly more convenient but may not be appropriate for 40 | # all applications, so you must explicity opt-in to this behavior. You can 41 | # always also configure it on a per-model basis if you prefer. 42 | # 43 | # Something else to consider is that using the :finders addon boosts 44 | # performance because it will avoid Rails-internal code that makes runtime 45 | # calls to `Module.extend`. 46 | # 47 | # config.use :finders 48 | # 49 | # ## Slugs 50 | # 51 | # Most applications will use the :slugged module everywhere. If you wish 52 | # to do so, uncomment the following line. 53 | # 54 | # config.use :slugged 55 | # 56 | # By default, FriendlyId's :slugged addon expects the slug column to be named 57 | # 'slug', but you can change it if you wish. 58 | # 59 | # config.slug_column = 'slug' 60 | # 61 | # By default, slug has no size limit, but you can change it if you wish. 62 | # 63 | # config.slug_limit = 255 64 | # 65 | # When FriendlyId can not generate a unique ID from your base method, it appends 66 | # a UUID, separated by a single dash. You can configure the character used as the 67 | # separator. If you're upgrading from FriendlyId 4, you may wish to replace this 68 | # with two dashes. 69 | # 70 | # config.sequence_separator = '-' 71 | # 72 | # Note that you must use the :slugged addon **prior** to the line which 73 | # configures the sequence separator, or else FriendlyId will raise an undefined 74 | # method error. 75 | # 76 | # ## Tips and Tricks 77 | # 78 | # ### Controlling when slugs are generated 79 | # 80 | # As of FriendlyId 5.0, new slugs are generated only when the slug field is 81 | # nil, but if you're using a column as your base method can change this 82 | # behavior by overriding the `should_generate_new_friendly_id?` method that 83 | # FriendlyId adds to your model. The change below makes FriendlyId 5.0 behave 84 | # more like 4.0. 85 | # Note: Use(include) Slugged module in the config if using the anonymous module. 86 | # If you have `friendly_id :name, use: slugged` in the model, Slugged module 87 | # is included after the anonymous module defined in the initializer, so it 88 | # overrides the `should_generate_new_friendly_id?` method from the anonymous module. 89 | # 90 | # config.use :slugged 91 | # config.use Module.new { 92 | # def should_generate_new_friendly_id? 93 | # slug.blank? || _changed? 94 | # end 95 | # } 96 | # 97 | # FriendlyId uses Rails's `parameterize` method to generate slugs, but for 98 | # languages that don't use the Roman alphabet, that's not usually sufficient. 99 | # Here we use the Babosa library to transliterate Russian Cyrillic slugs to 100 | # ASCII. If you use this, don't forget to add "babosa" to your Gemfile. 101 | # 102 | # config.use Module.new { 103 | # def normalize_friendly_id(text) 104 | # text.to_slug.normalize! :transliterations => [:russian, :latin] 105 | # end 106 | # } 107 | end 108 | -------------------------------------------------------------------------------- /config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format. Inflections 4 | # are locale specific, and you may define rules for as many different 5 | # locales as you wish. All of these examples are active by default: 6 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 7 | # inflect.plural /^(ox)$/i, '\1en' 8 | # inflect.singular /^(ox)en/i, '\1' 9 | # inflect.irregular 'person', 'people' 10 | # inflect.uncountable %w( fish sheep ) 11 | # end 12 | 13 | # These inflection rules are supported but not enabled by default: 14 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 15 | # inflect.acronym 'RESTful' 16 | # end 17 | -------------------------------------------------------------------------------- /config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | -------------------------------------------------------------------------------- /config/initializers/redis.rb: -------------------------------------------------------------------------------- 1 | if ENV['REDIS_URL'] 2 | $redis = Redis.new(url: ENV['REDIS_URL']) 3 | end 4 | -------------------------------------------------------------------------------- /config/initializers/sidekiq.rb: -------------------------------------------------------------------------------- 1 | if ENV['REDIS_URL'] 2 | Sidekiq.configure_client do |config| 3 | config.redis = { url: ENV['REDIS_URL'], network_timeout: 5 } 4 | end 5 | Sidekiq.configure_server do |config| 6 | config.redis = { url: ENV['REDIS_URL'], network_timeout: 5 } 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # This file contains settings for ActionController::ParamsWrapper which 4 | # is enabled by default. 5 | 6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 7 | ActiveSupport.on_load(:action_controller) do 8 | wrap_parameters format: [:json] 9 | end 10 | 11 | # To enable root element in JSON for ActiveRecord objects. 12 | # ActiveSupport.on_load(:active_record) do 13 | # self.include_root_in_json = true 14 | # end 15 | -------------------------------------------------------------------------------- /config/locales/devise.en.yml: -------------------------------------------------------------------------------- 1 | # Additional translations at https://github.com/heartcombo/devise/wiki/I18n 2 | 3 | en: 4 | devise: 5 | confirmations: 6 | confirmed: "Your email address has been successfully confirmed." 7 | send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes." 8 | send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." 9 | failure: 10 | already_authenticated: "You are already signed in." 11 | inactive: "Your account is not activated yet." 12 | invalid: "Invalid %{authentication_keys} or password." 13 | locked: "Your account is locked." 14 | last_attempt: "You have one more attempt before your account is locked." 15 | not_found_in_database: "Invalid %{authentication_keys} or password." 16 | timeout: "Your session expired. Please sign in again to continue." 17 | unauthenticated: "You need to sign in or sign up before continuing." 18 | unconfirmed: "You have to confirm your email address before continuing." 19 | mailer: 20 | confirmation_instructions: 21 | subject: "Confirmation instructions" 22 | reset_password_instructions: 23 | subject: "Reset password instructions" 24 | unlock_instructions: 25 | subject: "Unlock instructions" 26 | email_changed: 27 | subject: "Email Changed" 28 | password_change: 29 | subject: "Password Changed" 30 | omniauth_callbacks: 31 | failure: "Could not authenticate you from %{kind} because \"%{reason}\"." 32 | success: "Successfully authenticated from %{kind} account." 33 | passwords: 34 | no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." 35 | send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes." 36 | send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." 37 | updated: "Your password has been changed successfully. You are now signed in." 38 | updated_not_active: "Your password has been changed successfully." 39 | registrations: 40 | destroyed: "Bye! Your account has been successfully cancelled. We hope to see you again soon." 41 | signed_up: "Welcome! You have signed up successfully." 42 | signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated." 43 | signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked." 44 | signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please follow the link to activate your account." 45 | update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and follow the confirmation link to confirm your new email address." 46 | updated: "Your account has been updated successfully." 47 | updated_but_not_signed_in: "Your account has been updated successfully, but since your password was changed, you need to sign in again." 48 | sessions: 49 | signed_in: "Signed in successfully." 50 | signed_out: "Signed out successfully." 51 | already_signed_out: "Signed out successfully." 52 | unlocks: 53 | send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes." 54 | send_paranoid_instructions: "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." 55 | unlocked: "Your account has been unlocked successfully. Please sign in to continue." 56 | errors: 57 | messages: 58 | already_confirmed: "was already confirmed, please try signing in" 59 | confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" 60 | expired: "has expired, please request a new one" 61 | not_found: "not found" 62 | not_locked: "was not locked" 63 | not_saved: 64 | one: "1 error prohibited this %{resource} from being saved:" 65 | other: "%{count} errors prohibited this %{resource} from being saved:" 66 | -------------------------------------------------------------------------------- /config/locales/en.yml: -------------------------------------------------------------------------------- 1 | en: 2 | api: 3 | bad_request: "Bad Request" 4 | error: "API error: %{error} at LOC: %{loc}" 5 | not_found: "Not Found" 6 | ok: "ok" 7 | oops: "Oops! There was an error." 8 | unauthorized: "Unauthorized" 9 | controllers: 10 | comments: 11 | created: "Comment created successfully." 12 | deleted: "Comment deleted successfully." 13 | updated: "Comment updated successfully." 14 | confirmations: 15 | resent: "Confirmation email sent successfully." 16 | success: "Email confirmed successfully." 17 | passwords: 18 | email_required: "Email is required." 19 | email_sent: "Email sent. Please check your inbox." 20 | success: "Password updated successfully. You may need to sign in again." 21 | posts: 22 | created: "Post created successfully." 23 | deleted: "Post deleted successfully." 24 | updated: "Post updated successfully." 25 | registrations: 26 | confirm: "Please confirm your email address." 27 | sessions: 28 | sign_out: "Signed out successfully." 29 | users: 30 | updated: "Update successfully." 31 | models: 32 | users: 33 | slug_numbers: "cannot be only numbers, please add at least one character." 34 | username: "must be alphanumeric or underscore/dash only and must contain at least one character." 35 | username_numbers: "cannot be only numbers, please add at least one character." 36 | 37 | -------------------------------------------------------------------------------- /config/puma.rb: -------------------------------------------------------------------------------- 1 | # Puma can serve each request in a thread from an internal thread pool. 2 | # The `threads` method setting takes two numbers: a minimum and maximum. 3 | # Any libraries that use thread pools should be configured to match 4 | # the maximum value specified for Puma. Default is set to 5 threads for minimum 5 | # and maximum; this matches the default thread size of Active Record. 6 | # 7 | max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } 8 | min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } 9 | threads min_threads_count, max_threads_count 10 | 11 | # Specifies the `worker_timeout` threshold that Puma will use to wait before 12 | # terminating a worker in development environments. 13 | # 14 | worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" 15 | 16 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000. 17 | # 18 | port ENV.fetch("PORT") { 3000 } 19 | 20 | # Specifies the `environment` that Puma will run in. 21 | # 22 | environment ENV.fetch("RAILS_ENV") { "development" } 23 | 24 | # Specifies the `pidfile` that Puma will use. 25 | pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } 26 | 27 | # Specifies the number of `workers` to boot in clustered mode. 28 | # Workers are forked web server processes. If using threads and workers together 29 | # the concurrency of the application would be max `threads` * `workers`. 30 | # Workers do not work on JRuby or Windows (both of which do not support 31 | # processes). 32 | # 33 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 } 34 | 35 | # Use the `preload_app!` method when specifying a `workers` number. 36 | # This directive tells Puma to first boot the application and load code 37 | # before forking the application. This takes advantage of Copy On Write 38 | # process behavior so workers use less memory. 39 | # 40 | # preload_app! 41 | 42 | # Allow puma to be restarted by `rails restart` command. 43 | plugin :tmp_restart 44 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | devise_for :users, 3 | controllers: { 4 | confirmations: 'confirmations', 5 | passwords: 'passwords', 6 | registrations: 'registrations', 7 | sessions: 'sessions', 8 | } 9 | 10 | # Ping to ensure site is up 11 | resources :ping, only: [:index] do 12 | collection do 13 | get :auth 14 | end 15 | end 16 | 17 | # APIs 18 | namespace :api do 19 | namespace :v1 do 20 | resources :comments, only: [:create, :destroy, :index, :show, :update] 21 | resources :posts, only: [:create, :destroy, :index, :show, :update] 22 | resources :users, only: [:show, :update] do 23 | collection do 24 | get :available 25 | end 26 | end 27 | end 28 | end 29 | 30 | namespace :users do 31 | get "sign-in", to: "sessions#new" 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /config/sitemap.rb: -------------------------------------------------------------------------------- 1 | require 'aws-sdk-s3' 2 | 3 | # Set the host name for URL creation 4 | SitemapGenerator::Sitemap.default_host = "https://ptil-rails-staging-api.herokuapp.com" 5 | SitemapGenerator::Sitemap.public_path = 'tmp/' 6 | SitemapGenerator::Sitemap.sitemaps_path = 'sitemaps/' 7 | SitemapGenerator::Sitemap.compress = false 8 | SitemapGenerator::Sitemap.adapter = SitemapGenerator::AwsSdkAdapter.new( 9 | "programmingtil-rails-#{Rails.env}", 10 | aws_access_key_id: Rails.application.credentials.dig(:aws, :access_key_id), 11 | aws_secret_access_key: Rails.application.credentials.dig(:aws, :secret_access_key), 12 | aws_region: 'us-west-1' 13 | ) 14 | 15 | SitemapGenerator::Sitemap.create do 16 | add "/about", 17 | changefreq: 'yearly', 18 | lastmod: '2021-05-13T09:19:54-06:00', 19 | priority: 0.4 20 | Post.published.order(id: :desc).each do |post| 21 | add "/posts/#{post.slug}", 22 | changefreq: 'weekly', 23 | lastmod: post.published_at, 24 | priority: 0.6 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /config/spring.rb: -------------------------------------------------------------------------------- 1 | Spring.watch( 2 | ".ruby-version", 3 | ".rbenv-vars", 4 | "tmp/restart.txt", 5 | "tmp/caching-dev.txt" 6 | ) 7 | -------------------------------------------------------------------------------- /config/storage.yml: -------------------------------------------------------------------------------- 1 | test: 2 | service: Disk 3 | root: <%= Rails.root.join("tmp/storage") %> 4 | 5 | local: 6 | service: Disk 7 | root: <%= Rails.root.join("storage") %> 8 | 9 | # Use rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) 10 | # amazon: 11 | # service: S3 12 | # access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> 13 | # secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> 14 | # region: us-east-1 15 | # bucket: your_own_bucket 16 | 17 | # Remember not to checkin your GCS keyfile to a repository 18 | # google: 19 | # service: GCS 20 | # project: your_project 21 | # credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> 22 | # bucket: your_own_bucket 23 | 24 | # Use rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) 25 | # microsoft: 26 | # service: AzureStorage 27 | # storage_account_name: your_account_name 28 | # storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> 29 | # container: your_container_name 30 | 31 | # mirror: 32 | # service: Mirror 33 | # primary: local 34 | # mirrors: [ amazon, google, microsoft ] 35 | -------------------------------------------------------------------------------- /db/migrate/20210224031229_devise_create_users.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class DeviseCreateUsers < ActiveRecord::Migration[6.1] 4 | def change 5 | create_table :users do |t| 6 | ## Database authenticatable 7 | t.string :email, null: false, default: "" 8 | t.string :encrypted_password, null: false, default: "" 9 | 10 | ## Recoverable 11 | t.string :reset_password_token 12 | t.datetime :reset_password_sent_at 13 | 14 | ## Rememberable 15 | t.datetime :remember_created_at 16 | 17 | ## Trackable 18 | # t.integer :sign_in_count, default: 0, null: false 19 | # t.datetime :current_sign_in_at 20 | # t.datetime :last_sign_in_at 21 | # t.string :current_sign_in_ip 22 | # t.string :last_sign_in_ip 23 | 24 | ## Confirmable 25 | t.string :confirmation_token 26 | t.datetime :confirmed_at 27 | t.datetime :confirmation_sent_at 28 | t.string :unconfirmed_email # Only if using reconfirmable 29 | 30 | ## Lockable 31 | # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts 32 | # t.string :unlock_token # Only if unlock strategy is :email or :both 33 | # t.datetime :locked_at 34 | 35 | 36 | t.timestamps null: false 37 | end 38 | 39 | add_index :users, :email, unique: true 40 | add_index :users, :reset_password_token, unique: true 41 | add_index :users, :confirmation_token, unique: true 42 | # add_index :users, :unlock_token, unique: true 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /db/migrate/20210224032349_create_allowlisted_jwts.rb: -------------------------------------------------------------------------------- 1 | class CreateAllowlistedJwts < ActiveRecord::Migration[6.1] 2 | def change 3 | create_table :allowlisted_jwts do |t| 4 | t.references :user, foreign_key: { on_delete: :cascade }, null: false 5 | t.string :jti, null: false 6 | t.string :aud, null: false 7 | t.datetime :exp, null: false 8 | t.string :remote_ip 9 | t.string :os_data 10 | t.string :browser_data 11 | t.string :device_data 12 | t.timestamps null: false 13 | end 14 | 15 | add_index :allowlisted_jwts, :jti, unique: true 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /db/migrate/20210324003543_add_names_themes_to_user.rb: -------------------------------------------------------------------------------- 1 | class AddNamesThemesToUser < ActiveRecord::Migration[6.1] 2 | def change 3 | add_column :users, :username, :string, index: true, unique: true 4 | add_column :users, :display_name, :string, index: true 5 | add_column :users, :slug, :string, index: true 6 | add_column :users, :theme, :integer, default: 0 7 | add_column :users, :theme_color, :integer, default: 0 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /db/migrate/20210403204805_create_posts.rb: -------------------------------------------------------------------------------- 1 | class CreatePosts < ActiveRecord::Migration[6.1] 2 | def change 3 | create_table :posts do |t| 4 | t.references :user, null: false, index: true 5 | t.string :title, null: false 6 | t.text :content, null: false 7 | t.timestamp :published_at 8 | t.timestamps 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /db/migrate/20210414181412_add_slug_to_users.rb: -------------------------------------------------------------------------------- 1 | class AddSlugToUsers < ActiveRecord::Migration[6.1] 2 | def change 3 | add_index :users, :slug, unique: true 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /db/migrate/20210422212211_add_slug_to_posts.rb: -------------------------------------------------------------------------------- 1 | class AddSlugToPosts < ActiveRecord::Migration[6.1] 2 | def change 3 | add_column :posts, :slug, :string, index: true, unique: true 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /db/migrate/20210422213742_create_comments.rb: -------------------------------------------------------------------------------- 1 | class CreateComments < ActiveRecord::Migration[6.1] 2 | def change 3 | create_table :comments do |t| 4 | t.references :commentable, null: :false, polymorphic: true 5 | t.references :user, index: true 6 | t.references :thread, index: true 7 | t.references :parent, index: true 8 | t.text :body, null: false 9 | t.datetime :deleted_at 10 | t.timestamps null: false 11 | end 12 | 13 | add_column :posts, :comments_count, :bigint 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /db/schema.rb: -------------------------------------------------------------------------------- 1 | # This file is auto-generated from the current state of the database. Instead 2 | # of editing this file, please use the migrations feature of Active Record to 3 | # incrementally modify your database, and then regenerate this schema definition. 4 | # 5 | # This file is the source Rails uses to define your schema when running `bin/rails 6 | # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to 7 | # be faster and is potentially less error prone than running all of your 8 | # migrations from scratch. Old migrations may fail to apply correctly if those 9 | # migrations use external dependencies or application code. 10 | # 11 | # It's strongly recommended that you check this file into your version control system. 12 | 13 | ActiveRecord::Schema.define(version: 2021_04_22_213742) do 14 | 15 | # These are extensions that must be enabled in order to support this database 16 | enable_extension "plpgsql" 17 | 18 | create_table "allowlisted_jwts", force: :cascade do |t| 19 | t.bigint "user_id", null: false 20 | t.string "jti", null: false 21 | t.string "aud", null: false 22 | t.datetime "exp", null: false 23 | t.string "remote_ip" 24 | t.string "os_data" 25 | t.string "browser_data" 26 | t.string "device_data" 27 | t.datetime "created_at", precision: 6, null: false 28 | t.datetime "updated_at", precision: 6, null: false 29 | t.index ["jti"], name: "index_allowlisted_jwts_on_jti", unique: true 30 | t.index ["user_id"], name: "index_allowlisted_jwts_on_user_id" 31 | end 32 | 33 | create_table "comments", force: :cascade do |t| 34 | t.string "commentable_type" 35 | t.bigint "commentable_id" 36 | t.bigint "user_id" 37 | t.bigint "thread_id" 38 | t.bigint "parent_id" 39 | t.text "body", null: false 40 | t.datetime "deleted_at" 41 | t.datetime "created_at", precision: 6, null: false 42 | t.datetime "updated_at", precision: 6, null: false 43 | t.index ["commentable_type", "commentable_id"], name: "index_comments_on_commentable" 44 | t.index ["parent_id"], name: "index_comments_on_parent_id" 45 | t.index ["thread_id"], name: "index_comments_on_thread_id" 46 | t.index ["user_id"], name: "index_comments_on_user_id" 47 | end 48 | 49 | create_table "posts", force: :cascade do |t| 50 | t.bigint "user_id", null: false 51 | t.string "title", null: false 52 | t.text "content", null: false 53 | t.datetime "published_at" 54 | t.datetime "created_at", precision: 6, null: false 55 | t.datetime "updated_at", precision: 6, null: false 56 | t.string "slug" 57 | t.bigint "comments_count" 58 | t.index ["user_id"], name: "index_posts_on_user_id" 59 | end 60 | 61 | create_table "users", force: :cascade do |t| 62 | t.string "email", default: "", null: false 63 | t.string "encrypted_password", default: "", null: false 64 | t.string "reset_password_token" 65 | t.datetime "reset_password_sent_at" 66 | t.datetime "remember_created_at" 67 | t.string "confirmation_token" 68 | t.datetime "confirmed_at" 69 | t.datetime "confirmation_sent_at" 70 | t.string "unconfirmed_email" 71 | t.datetime "created_at", precision: 6, null: false 72 | t.datetime "updated_at", precision: 6, null: false 73 | t.string "username" 74 | t.string "display_name" 75 | t.string "slug" 76 | t.integer "theme", default: 0 77 | t.integer "theme_color", default: 0 78 | t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true 79 | t.index ["email"], name: "index_users_on_email", unique: true 80 | t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true 81 | t.index ["slug"], name: "index_users_on_slug", unique: true 82 | end 83 | 84 | add_foreign_key "allowlisted_jwts", "users", on_delete: :cascade 85 | end 86 | -------------------------------------------------------------------------------- /db/seeds.rb: -------------------------------------------------------------------------------- 1 | # This file should contain all the record creation needed to seed the database with its default values. 2 | # The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). 3 | # 4 | # Examples: 5 | # 6 | # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) 7 | # Character.create(name: 'Luke', movie: movies.first) 8 | -------------------------------------------------------------------------------- /lib/devise_custom_failure.rb: -------------------------------------------------------------------------------- 1 | # https://github.com/heartcombo/devise/blob/master/lib/devise/failure_app.rb 2 | class DeviseCustomFailure < Devise::FailureApp 3 | def respond 4 | # If fails on certain actions, then ignore and make request as if no user. 5 | # Basically, any with `authenticate_user_if_needed!` needs to use this as a fallback 6 | path_params = request.path_parameters 7 | control = path_params[:controller] 8 | act = path_params[:action] 9 | if (control == 'api/v1/ping' && act == 'index') 10 | # HACK! Rails converts 'api/v1/people'.classify => API::V1::Person 11 | # So we pluralize it and get People or Talks, etc 12 | classify = control.classify.pluralize 13 | 14 | warden_options[:recall] = "#{classify}##{act}" 15 | request.headers['auth_failure'] = true 16 | request.headers['auth_failure_message'] = i18n_message 17 | recall 18 | else 19 | http_auth 20 | end 21 | end 22 | 23 | # Override failure to always return JSON. 24 | # This is needed because Devise will attempt to redirect otherwise 25 | def http_auth_body 26 | { 27 | authFailure: true, 28 | error: i18n_message, 29 | }.to_json 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /lib/tasks/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidwparker/programmingtil-rails/9151797fae190b1abb7519240d3245dd58ba5347/lib/tasks/.keep -------------------------------------------------------------------------------- /lib/tasks/auto_annotate_models.rake: -------------------------------------------------------------------------------- 1 | # NOTE: only doing this in development as some production environments (Heroku) 2 | # NOTE: are sensitive to local FS writes, and besides -- it's just not proper 3 | # NOTE: to have a dev-mode tool do its thing in production. 4 | if Rails.env.development? 5 | require 'annotate' 6 | task :set_annotation_options do 7 | # You can override any of these by setting an environment variable of the 8 | # same name. 9 | Annotate.set_defaults( 10 | 'active_admin' => 'false', 11 | 'additional_file_patterns' => [], 12 | 'routes' => 'false', 13 | 'models' => 'true', 14 | 'position_in_routes' => 'before', 15 | 'position_in_class' => 'before', 16 | 'position_in_test' => 'before', 17 | 'position_in_fixture' => 'before', 18 | 'position_in_factory' => 'before', 19 | 'position_in_serializer' => 'before', 20 | 'show_foreign_keys' => 'true', 21 | 'show_complete_foreign_keys' => 'false', 22 | 'show_indexes' => 'true', 23 | 'simple_indexes' => 'false', 24 | 'model_dir' => 'app/models', 25 | 'root_dir' => '', 26 | 'include_version' => 'false', 27 | 'require' => '', 28 | 'exclude_tests' => 'false', 29 | 'exclude_fixtures' => 'true', 30 | 'exclude_factories' => 'true', 31 | 'exclude_serializers' => 'true', 32 | 'exclude_scaffolds' => 'true', 33 | 'exclude_controllers' => 'true', 34 | 'exclude_helpers' => 'true', 35 | 'exclude_sti_subclasses' => 'false', 36 | 'ignore_model_sub_dir' => 'false', 37 | 'ignore_columns' => nil, 38 | 'ignore_routes' => nil, 39 | 'ignore_unknown_models' => 'false', 40 | 'hide_limit_column_types' => 'integer,bigint,boolean', 41 | 'hide_default_column_types' => 'json,jsonb,hstore', 42 | 'skip_on_db_migrate' => 'false', 43 | 'format_bare' => 'true', 44 | 'format_rdoc' => 'false', 45 | 'format_yard' => 'false', 46 | 'format_markdown' => 'false', 47 | 'sort' => 'false', 48 | 'force' => 'false', 49 | 'frozen' => 'false', 50 | 'classified_sort' => 'false', 51 | 'trace' => 'false', 52 | 'wrapper_open' => nil, 53 | 'wrapper_close' => nil, 54 | 'with_comment' => 'true' 55 | ) 56 | end 57 | 58 | Annotate.load_tasks 59 | end 60 | -------------------------------------------------------------------------------- /log/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidwparker/programmingtil-rails/9151797fae190b1abb7519240d3245dd58ba5347/log/.keep -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | -------------------------------------------------------------------------------- /public/sitemap.xml: -------------------------------------------------------------------------------- 1 | localhost:50002021-05-13T16:31:46-06:00always1.0localhost:5000/about2021-05-13T09:19:54-06:00yearly0.4localhost:5000/posts/this-is-a-test-192021-04-02T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-182021-03-31T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-172021-04-03T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-162021-04-06T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-152021-04-05T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-142021-04-03T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-132021-04-06T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-122021-04-02T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-112021-04-05T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-102021-03-31T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-92021-04-06T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-82021-03-31T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-72021-04-03T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-62021-04-02T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-52021-04-03T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-42021-04-06T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-32021-03-30T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-22021-04-02T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-12021-03-30T15:49:42+00:00weekly0.6localhost:5000/posts/this-is-a-test-02021-03-31T15:49:42+00:00weekly0.6 -------------------------------------------------------------------------------- /spec/rails_helper.rb: -------------------------------------------------------------------------------- 1 | # This file is copied to spec/ when you run 'rails generate rspec:install' 2 | require 'spec_helper' 3 | ENV['RAILS_ENV'] ||= 'test' 4 | require File.expand_path('../config/environment', __dir__) 5 | # Prevent database truncation if the environment is production 6 | abort("The Rails environment is running in production mode!") if Rails.env.production? 7 | require 'rspec/rails' 8 | # Add additional requires below this line. Rails is not loaded until this point! 9 | # require 'devise' 10 | # require 'devise/jwt/test_helpers' 11 | 12 | # Requires supporting ruby files with custom matchers and macros, etc, in 13 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are 14 | # run as spec files by default. This means that files in spec/support that end 15 | # in _spec.rb will both be required and run as specs, causing the specs to be 16 | # run twice. It is recommended that you do not name files matching this glob to 17 | # end with _spec.rb. You can configure this pattern with the --pattern 18 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. 19 | # 20 | # The following line is provided for convenience purposes. It has the downside 21 | # of increasing the boot-up time by auto-requiring all files in the support 22 | # directory. Alternatively, in the individual `*_spec.rb` files, manually 23 | # require only the support files necessary. 24 | # 25 | Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } 26 | 27 | # Checks for pending migrations and applies them before tests are run. 28 | # If you are not using ActiveRecord, you can remove these lines. 29 | begin 30 | ActiveRecord::Migration.maintain_test_schema! 31 | rescue ActiveRecord::PendingMigrationError => e 32 | puts e.to_s.strip 33 | exit 1 34 | end 35 | 36 | RSpec.configure do |config| 37 | # config.include Devise::Test::IntegrationHelpers, type: :request 38 | 39 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 40 | config.fixture_path = "#{::Rails.root}/spec/fixtures" 41 | 42 | # If you're not using ActiveRecord, or you'd prefer not to run each of your 43 | # examples within a transaction, remove the following line or assign false 44 | # instead of true. 45 | config.use_transactional_fixtures = true 46 | 47 | config.before(:suite) do 48 | DatabaseCleaner.strategy = :transaction 49 | DatabaseCleaner.clean_with(:truncation) 50 | end 51 | 52 | # config.around(:each) do |example| 53 | # DatabaseCleaner.cleaning do 54 | # example.run 55 | # end 56 | # end 57 | config.before(:each) do 58 | DatabaseCleaner.strategy = :transaction 59 | # DatabaseCleaner.start 60 | end 61 | 62 | config.after(:each) do 63 | DatabaseCleaner.clean 64 | end 65 | 66 | # config.append_after(:each) do 67 | # DatabaseCleaner.clean 68 | # end 69 | 70 | # You can uncomment this line to turn off ActiveRecord support entirely. 71 | # config.use_active_record = false 72 | 73 | # RSpec Rails can automatically mix in different behaviours to your tests 74 | # based on their file location, for example enabling you to call `get` and 75 | # `post` in specs under `spec/controllers`. 76 | # 77 | # You can disable this behaviour by removing the line below, and instead 78 | # explicitly tag your specs with their type, e.g.: 79 | # 80 | # RSpec.describe UsersController, type: :controller do 81 | # # ... 82 | # end 83 | # 84 | # The different available types are documented in the features, such as in 85 | # https://relishapp.com/rspec/rspec-rails/docs 86 | config.infer_spec_type_from_file_location! 87 | 88 | # Filter lines from Rails gems in backtraces. 89 | config.filter_rails_from_backtrace! 90 | # arbitrary gems may also be filtered via: 91 | # config.filter_gems_from_backtrace("gem name") 92 | end 93 | -------------------------------------------------------------------------------- /spec/requests/comments_request_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe "api/v1/comments", type: :request do 4 | # Create 5 | context 'POST /api/v1/comments' do 6 | context 'without a user' do 7 | it 'returns a 401' do 8 | post '/api/v1/comments' 9 | expect(response).to have_http_status(401) 10 | end 11 | end 12 | 13 | context 'as a user' do 14 | it 'should let me create a comment on a post' do 15 | user = create_user 16 | post = create_post({ user: user }) 17 | headers = get_headers(user.username) 18 | url = '/api/v1/comments' 19 | post url, 20 | params: '{ "comment": { "body": "comment body", "commentable_type": "Post", "commentable_id": ' + post.id.to_s + ' } }', 21 | headers: headers 22 | parsed = JSON.parse(response.body, object_class: OpenStruct) 23 | expect(response).to have_http_status(200) 24 | expect(parsed.data.attributes.user.id).to eq(user.id) 25 | expect(parsed.data.attributes.body).to eq('comment body') 26 | end 27 | end 28 | end 29 | 30 | # Destroy 31 | context 'DELETE /api/v1/comments/:id' do 32 | context 'without a user' do 33 | it 'returns a 401' do 34 | record = create_comment 35 | delete "/api/v1/comments/#{record.id}" 36 | expect(response).to have_http_status(401) 37 | end 38 | end 39 | 40 | context 'as a user' do 41 | it 'should not let me destroy an comment' do 42 | user = create_user 43 | user2 = create_user 44 | record = create_comment({ user: user }) 45 | url = "/api/v1/comments/#{record.id}" 46 | delete url, headers: get_headers(user2.username) 47 | expect(response).to have_http_status(404) 48 | end 49 | end 50 | 51 | context 'as a user (owner)' do 52 | it 'should let me destroy a comment' do 53 | user = create_user 54 | record = create_comment({ user: user }) 55 | url = "/api/v1/comments/#{record.id}" 56 | delete url, headers: get_headers(user.username) 57 | parsed = JSON.parse(response.body, object_class: OpenStruct) 58 | expect(response).to have_http_status(200) 59 | expect(parsed.data.attributes.user).to eq(nil) 60 | expect(parsed.data.attributes.body).to eq('[deleted]') 61 | end 62 | end 63 | end 64 | 65 | # Index 66 | context 'GET /api/v1/comments' do 67 | it 'Returns a status of 200 with a list of posts' do 68 | user = create_user 69 | post = create_post({ user: user }) 70 | create_comment({ user: user, commentable: post }) 71 | create_comment({ user: user, commentable: post }) 72 | create_comment({ user: user, commentable: post }) 73 | get "/api/v1/comments?commentable_id=#{post.id}&commentable_type=Post" 74 | parsed = JSON.parse(response.body, object_class: OpenStruct) 75 | expect(response).to have_http_status(200) 76 | expect(parsed.data.size).to eq(3) 77 | end 78 | end 79 | 80 | 81 | # Show 82 | context 'GET /api/v1/comments/:slug' do 83 | it 'Returns a status of 404 if does not exist' do 84 | get '/api/v1/comments/1234' 85 | parsed = JSON.parse(response.body, object_class: OpenStruct) 86 | expect(response).to have_http_status(404) 87 | end 88 | 89 | it 'Returns a comment if exists' do 90 | user = create_user(name: 'testtest') 91 | record = create_comment({ user: user }) 92 | get "/api/v1/comments/#{record.id}" 93 | parsed = JSON.parse(response.body, object_class: OpenStruct) 94 | expect(response).to have_http_status(200) 95 | expect(parsed.data.id.to_i).to eq(record.id) 96 | end 97 | end 98 | 99 | # Update 100 | context 'PUT /api/v1/comments/:id' do 101 | context 'without a user' do 102 | it 'returns a 401' do 103 | record = create_comment 104 | url = "/api/v1/comments/#{record.id}" 105 | put url, params: '{ "comment": { "body": "comment updated 1" } }' 106 | expect(response).to have_http_status(401) 107 | end 108 | end 109 | 110 | context 'as a non-user of comment' do 111 | it 'should not let me update a comment' do 112 | user = create_user 113 | user2 = create_user 114 | record = create_comment({ user: user }) 115 | headers = get_headers(user2.username) 116 | url = "/api/v1/comments/#{record.id}" 117 | put url, params: '{ "comment": { "title": "comment updated 1" } }', headers: headers 118 | expect(response).to have_http_status(404) 119 | end 120 | end 121 | 122 | context 'as a comment owner' do 123 | it 'should let me update a comment' do 124 | user = create_user 125 | record = create_comment({ user: user }) 126 | headers = get_headers(user.username) 127 | url = "/api/v1/comments/#{record.id}" 128 | put url, params: '{ "comment": { "body": "comment updated 1" } }', headers: headers 129 | parsed = JSON.parse(response.body, object_class: OpenStruct) 130 | expect(response).to have_http_status(200) 131 | expect(parsed.data.attributes.body).to eq('comment updated 1') 132 | end 133 | end 134 | end 135 | end 136 | -------------------------------------------------------------------------------- /spec/requests/ping_request_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe "Pings", type: :request do 4 | it 'Returns a status of 200' do 5 | get '/ping/' 6 | expect(response).to have_http_status(200) 7 | end 8 | 9 | it 'Returns a status of 401 if not logged in' do 10 | get '/ping/auth/' 11 | expect(response).to have_http_status(401) 12 | end 13 | 14 | it 'Returns a status of 200 if logged in' do 15 | user = create_user 16 | headers = get_headers(user.username) 17 | get '/ping/auth/', headers: headers 18 | expect(response).to have_http_status(200) 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /spec/requests/posts_request_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe "api/v1/posts", type: :request do 4 | # Create 5 | context 'POST /api/v1/posts' do 6 | context 'without a user' do 7 | it 'returns a 401' do 8 | post '/api/v1/posts' 9 | expect(response).to have_http_status(401) 10 | end 11 | end 12 | 13 | context 'as a user' do 14 | it 'should let me create a post' do 15 | user = create_user 16 | headers = get_headers(user.username) 17 | url = '/api/v1/posts' 18 | post url, params: '{ "post": { "title": "post 1", "content": "content 1" } }', headers: headers 19 | parsed = JSON.parse(response.body, object_class: OpenStruct) 20 | expect(response).to have_http_status(200) 21 | expect(parsed.data.attributes.user.id).to eq(user.id) 22 | end 23 | 24 | # it 'should not let me create more than 3 posts' do 25 | # user = create_user 26 | # headers = get_headers(user.username) 27 | # url = '/api/v1/posts' 28 | # post url, params: '{ "post": { "title": "post 1", "content": "content 1" } }', headers: headers 29 | # post url, params: '{ "post": { "title": "post 2", "content": "content 2" } }', headers: headers 30 | # post url, params: '{ "post": { "title": "post 3", "content": "content 3" } }', headers: headers 31 | 32 | # expect(response).to have_http_status(200) 33 | 34 | # post url, params: '{ "post": { "title": "post 4", "content": "content 4" } }', headers: headers 35 | # expect(response).to have_http_status(404) 36 | # end 37 | end 38 | end 39 | 40 | # Destroy 41 | context 'DELETE /api/v1/posts/:id' do 42 | context 'without a user' do 43 | it 'returns a 401' do 44 | record = create_post 45 | delete "/api/v1/posts/#{record.id}" 46 | expect(response).to have_http_status(401) 47 | end 48 | end 49 | 50 | context 'as a user' do 51 | it 'should not let me destroy an post' do 52 | user = create_user 53 | user2 = create_user 54 | record = create_post({ user: user }) 55 | url = "/api/v1/posts/#{record.id}" 56 | delete url, headers: get_headers(user2.username) 57 | expect(response).to have_http_status(404) 58 | end 59 | end 60 | 61 | context 'as a user (owner)' do 62 | it 'should let me destroy a post' do 63 | user = create_user 64 | record = create_post({ user: user }) 65 | url = "/api/v1/posts/#{record.id}" 66 | delete url, headers: get_headers(user.username) 67 | expect(response).to have_http_status(200) 68 | end 69 | end 70 | end 71 | 72 | # Index 73 | context 'GET /api/v1/posts' do 74 | it 'Returns a status of 200 with a list of posts' do 75 | user = create_user 76 | create_post({ user: user }) 77 | create_post({ user: user }) 78 | get '/api/v1/posts' 79 | parsed = JSON.parse(response.body, object_class: OpenStruct) 80 | expect(response).to have_http_status(200) 81 | expect(parsed.data.size).to eq(2) 82 | end 83 | end 84 | 85 | # Show 86 | context 'GET /api/v1/posts/:slug' do 87 | it 'Returns a status of 404 if does not exist' do 88 | get '/api/v1/posts/name' 89 | parsed = JSON.parse(response.body, object_class: OpenStruct) 90 | expect(response).to have_http_status(404) 91 | end 92 | 93 | it 'Returns post if sending back slug' do 94 | user = create_user(name: 'testtest') 95 | record = create_post({ user: user }) 96 | get "/api/v1/posts/#{record.slug}" 97 | parsed = JSON.parse(response.body, object_class: OpenStruct) 98 | expect(response).to have_http_status(200) 99 | expect(parsed.data.id.to_i).to eq(record.id) 100 | end 101 | 102 | it 'Returns a post if sending back id' do 103 | user = create_user(name: 'testtest') 104 | record = create_post({ user: user }) 105 | get "/api/v1/posts/#{record.id}" 106 | parsed = JSON.parse(response.body, object_class: OpenStruct) 107 | expect(response).to have_http_status(200) 108 | expect(parsed.data.id.to_i).to eq(record.id) 109 | end 110 | 111 | it 'Returns 5 comments with the post' do 112 | user = create_user(name: 'testtest') 113 | record = create_post({ user: user }) 114 | create_comment({ user: user, commentable: record }) 115 | create_comment({ user: user, commentable: record }) 116 | create_comment({ user: user, commentable: record }) 117 | create_comment({ user: user, commentable: record }) 118 | create_comment({ user: user, commentable: record }) 119 | get "/api/v1/posts/#{record.id}" 120 | parsed = JSON.parse(response.body, object_class: OpenStruct) 121 | expect(response).to have_http_status(200) 122 | expect(parsed.data.id.to_i).to eq(record.id) 123 | expect(parsed.data.attributes.comments.data.length).to eq(5) 124 | expect(parsed.data.attributes.comments.data.first.attributes.user.id).to eq(user.id) 125 | end 126 | 127 | it 'Returns all comments with param all' do 128 | user = create_user(name: 'testtest') 129 | record = create_post({ user: user }) 130 | create_comment({ user: user, commentable: record }) 131 | create_comment({ user: user, commentable: record }) 132 | create_comment({ user: user, commentable: record }) 133 | create_comment({ user: user, commentable: record }) 134 | create_comment({ user: user, commentable: record }) 135 | create_comment({ user: user, commentable: record }) 136 | get "/api/v1/posts/#{record.id}?all=true" 137 | parsed = JSON.parse(response.body, object_class: OpenStruct) 138 | expect(response).to have_http_status(200) 139 | expect(parsed.data.id.to_i).to eq(record.id) 140 | expect(parsed.data.attributes.comments.data.length).to eq(6) 141 | end 142 | end 143 | 144 | # Update 145 | context 'PUT /api/v1/posts/:id' do 146 | context 'without a user' do 147 | it 'returns a 401' do 148 | record = create_post 149 | url = "/api/v1/posts/#{record.id}" 150 | put url, params: '{ "post": { "title": "post updated 1" } }' 151 | expect(response).to have_http_status(401) 152 | end 153 | end 154 | 155 | context 'as a non-user of post' do 156 | it 'should not let me update a post' do 157 | user = create_user 158 | user2 = create_user 159 | record = create_post({ user: user }) 160 | headers = get_headers(user2.username) 161 | url = "/api/v1/posts/#{record.id}" 162 | put url, params: '{ "post": { "title": "post updated 1" } }', headers: headers 163 | expect(response).to have_http_status(404) 164 | end 165 | end 166 | 167 | context 'as a post owner' do 168 | it 'should let me update a post' do 169 | user = create_user 170 | record = create_post({ user: user }) 171 | headers = get_headers(user.username) 172 | url = "/api/v1/posts/#{record.id}" 173 | put url, params: '{ "post": { "title": "post updated 1" } }', headers: headers 174 | parsed = JSON.parse(response.body, object_class: OpenStruct) 175 | expect(response).to have_http_status(200) 176 | expect(parsed.data.attributes.title).to eq('post updated 1') 177 | end 178 | end 179 | end 180 | end 181 | -------------------------------------------------------------------------------- /spec/requests/users_request_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe "api/v1/users", type: :request do 4 | context "available" do 5 | it 'Returns a status of 200 with no params' do 6 | get '/api/v1/users/available' 7 | parsed = JSON.parse(response.body, object_class: OpenStruct) 8 | expect(response).to have_http_status(200) 9 | expect(parsed.data).to eq(true) 10 | end 11 | 12 | it 'Returns false if username already exists' do 13 | create_user(name: 'testtest') 14 | get '/api/v1/users/available?username=testtest' 15 | parsed = JSON.parse(response.body, object_class: OpenStruct) 16 | expect(response).to have_http_status(200) 17 | expect(parsed.data).to eq(false) 18 | end 19 | 20 | it 'Returns true if username does not already exist' do 21 | create_user(name: 'testtest') 22 | get '/api/v1/users/available?username=testtest2' 23 | parsed = JSON.parse(response.body, object_class: OpenStruct) 24 | expect(response).to have_http_status(200) 25 | expect(parsed.data).to eq(true) 26 | end 27 | 28 | it 'Returns false if email already exists' do 29 | create_user(name: 'testtest') 30 | get '/api/v1/users/available?email=testtest@test.com' 31 | parsed = JSON.parse(response.body, object_class: OpenStruct) 32 | expect(response).to have_http_status(200) 33 | expect(parsed.data).to eq(false) 34 | end 35 | 36 | it 'Returns true if email does not already exist' do 37 | create_user(name: 'testtest') 38 | get '/api/v1/users/available?email=testtest2@test.com' 39 | parsed = JSON.parse(response.body, object_class: OpenStruct) 40 | expect(response).to have_http_status(200) 41 | expect(parsed.data).to eq(true) 42 | end 43 | end 44 | 45 | context "show" do 46 | it 'Returns a status of 404 if does not exist' do 47 | get '/api/v1/users/name' 48 | parsed = JSON.parse(response.body, object_class: OpenStruct) 49 | expect(response).to have_http_status(404) 50 | end 51 | 52 | it 'Returns user if sending back slug' do 53 | user = create_user(name: 'testtest') 54 | get "/api/v1/users/#{user.slug}" 55 | parsed = JSON.parse(response.body, object_class: OpenStruct) 56 | expect(response).to have_http_status(200) 57 | expect(parsed.data.id.to_i).to eq(user.id) 58 | end 59 | 60 | it 'Returns user if sending back id' do 61 | user = create_user(name: 'testtest') 62 | get "/api/v1/users/#{user.id}" 63 | parsed = JSON.parse(response.body, object_class: OpenStruct) 64 | expect(response).to have_http_status(200) 65 | expect(parsed.data.id.to_i).to eq(user.id) 66 | end 67 | end 68 | 69 | context "update" do 70 | it 'Requires a user' do 71 | user = create_user 72 | put "/api/v1/users/#{user.id}" 73 | expect(response).to have_http_status(401) 74 | end 75 | 76 | it 'Updates for the current user' do 77 | user = create_user 78 | headers = get_headers(user.username) 79 | put "/api/v1/users/#{user.id}", 80 | params: '{ "user": { "display_name": "hello" } }', 81 | headers: headers 82 | parsed = JSON.parse(response.body, object_class: OpenStruct) 83 | expect(response).to have_http_status(200) 84 | expect(parsed.user.displayName).to eq("hello") 85 | end 86 | 87 | it 'Does not update for another user' do 88 | user = create_user 89 | user2 = create_user 90 | headers = get_headers(user2.username) 91 | put "/api/v1/users/#{user.id}", 92 | params: '{ "user": { "display_name": "hello" } }', 93 | headers: headers 94 | parsed = JSON.parse(response.body, object_class: OpenStruct) 95 | expect(response).to have_http_status(200) 96 | expect(parsed.user.display_name).not_to eq("hello") 97 | end 98 | 99 | it 'Throws a 500 if error' do 100 | user = create_user 101 | headers = get_headers(user.username) 102 | put "/api/v1/users/#{user.id}", 103 | params: '{ "user123": { "display_name": "hello" } }', 104 | headers: headers 105 | expect(response).to have_http_status(500) 106 | end 107 | end 108 | end 109 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | require 'simplecov' 2 | SimpleCov.start do 3 | add_filter "/config/" 4 | add_filter "/spec/" 5 | add_filter "/lib/devise_custom_failure.rb" 6 | 7 | add_group "Model", "app/models" 8 | add_group "Controllers", "app/controllers" 9 | add_group "Helpers", "app/helpers" 10 | add_group "Jobs", "app/jobs" 11 | add_group "Mailers", "app/mailers" 12 | add_group "Serializers", "app/serializers" 13 | add_group "Policies", "app/policies" 14 | # add_group "Views", "app/views" 15 | end 16 | # This file was generated by the `rails generate rspec:install` command. Conventionally, all 17 | # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. 18 | # The generated `.rspec` file contains `--require spec_helper` which will cause 19 | # this file to always be loaded, without a need to explicitly require it in any 20 | # files. 21 | # 22 | # Given that it is always loaded, you are encouraged to keep this file as 23 | # light-weight as possible. Requiring heavyweight dependencies from this file 24 | # will add to the boot time of your test suite on EVERY test run, even for an 25 | # individual file that may not need all of that loaded. Instead, consider making 26 | # a separate helper file that requires the additional dependencies and performs 27 | # the additional setup, and require it from the spec files that actually need 28 | # it. 29 | # 30 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration 31 | RSpec.configure do |config| 32 | # rspec-expectations config goes here. You can use an alternate 33 | # assertion/expectation library such as wrong or the stdlib/minitest 34 | # assertions if you prefer. 35 | config.expect_with :rspec do |expectations| 36 | # This option will default to `true` in RSpec 4. It makes the `description` 37 | # and `failure_message` of custom matchers include text for helper methods 38 | # defined using `chain`, e.g.: 39 | # be_bigger_than(2).and_smaller_than(4).description 40 | # # => "be bigger than 2 and smaller than 4" 41 | # ...rather than: 42 | # # => "be bigger than 2" 43 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true 44 | end 45 | 46 | # rspec-mocks config goes here. You can use an alternate test double 47 | # library (such as bogus or mocha) by changing the `mock_with` option here. 48 | config.mock_with :rspec do |mocks| 49 | # Prevents you from mocking or stubbing a method that does not exist on 50 | # a real object. This is generally recommended, and will default to 51 | # `true` in RSpec 4. 52 | mocks.verify_partial_doubles = true 53 | end 54 | 55 | # This option will default to `:apply_to_host_groups` in RSpec 4 (and will 56 | # have no way to turn it off -- the option exists only for backwards 57 | # compatibility in RSpec 3). It causes shared context metadata to be 58 | # inherited by the metadata hash of host groups and examples, rather than 59 | # triggering implicit auto-inclusion in groups with matching metadata. 60 | config.shared_context_metadata_behavior = :apply_to_host_groups 61 | 62 | # The settings below are suggested to provide a good initial experience 63 | # with RSpec, but feel free to customize to your heart's content. 64 | =begin 65 | # This allows you to limit a spec run to individual examples or groups 66 | # you care about by tagging them with `:focus` metadata. When nothing 67 | # is tagged with `:focus`, all examples get run. RSpec also provides 68 | # aliases for `it`, `describe`, and `context` that include `:focus` 69 | # metadata: `fit`, `fdescribe` and `fcontext`, respectively. 70 | config.filter_run_when_matching :focus 71 | 72 | # Allows RSpec to persist some state between runs in order to support 73 | # the `--only-failures` and `--next-failure` CLI options. We recommend 74 | # you configure your source control system to ignore this file. 75 | config.example_status_persistence_file_path = "spec/examples.txt" 76 | 77 | # Limits the available syntax to the non-monkey patched syntax that is 78 | # recommended. For more details, see: 79 | # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ 80 | # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ 81 | # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode 82 | config.disable_monkey_patching! 83 | 84 | # Many RSpec users commonly either run the entire suite or an individual 85 | # file, and it's useful to allow more verbose output when running an 86 | # individual spec file. 87 | if config.files_to_run.one? 88 | # Use the documentation formatter for detailed output, 89 | # unless a formatter has already been configured 90 | # (e.g. via a command-line flag). 91 | config.default_formatter = "doc" 92 | end 93 | 94 | # Print the 10 slowest examples and example groups at the 95 | # end of the spec run, to help surface which specs are running 96 | # particularly slow. 97 | config.profile_examples = 10 98 | 99 | # Run specs in random order to surface order dependencies. If you find an 100 | # order dependency and want to debug it, you can fix the order by providing 101 | # the seed, which is printed after each run. 102 | # --seed 1234 103 | config.order = :random 104 | 105 | # Seed global randomization in this process using the `--seed` CLI option. 106 | # Setting this allows you to use `--seed` to deterministically reproduce 107 | # test failures related to randomization by passing the same `--seed` value 108 | # as the one that triggered the failure. 109 | Kernel.srand config.seed 110 | =end 111 | end 112 | -------------------------------------------------------------------------------- /spec/support/object_creators.rb: -------------------------------------------------------------------------------- 1 | module ObjectCreators 2 | def create_allowlisted_jwts(params = {}) 3 | user = params[:user].presence || create_user 4 | user.allowlisted_jwts.create!( 5 | jti: params['jti'].presence || 'TEST', 6 | aud: params['aud'].presence || 'TEST', 7 | exp: Time.at(params['exp'].presence.to_i || Time.now.to_i) 8 | ) 9 | end 10 | 11 | def create_comment(params = {}) 12 | user = params[:user].presence || create_user 13 | commentable = params[:commentable].presence || create_post 14 | last_id = Comment.limit(1).order(id: :desc).pluck(:id).first || 0 15 | Comment.create_comment!(user, { 16 | body: params[:body].presence || "Comment #{last_id+1}", 17 | commentable_id: commentable.id, 18 | commentable_type: commentable.class.name, 19 | }) 20 | end 21 | 22 | def create_post(params = {}) 23 | user = params[:user].presence || create_user 24 | last_id = Post.limit(1).order(id: :desc).pluck(:id).first || 0 25 | Post.create!({ 26 | title: params[:title].presence || "Post #{last_id+1}", 27 | content: params[:content].presence || "Post content #{last_id+1}", 28 | user_id: user.id 29 | }) 30 | end 31 | 32 | def create_user(params = {}) 33 | last_id = User.limit(1).order(id: :desc).pluck(:id).first || 0 34 | user = User.new( 35 | email: params[:name].present? ? "#{params[:name]}@test.com" : "testtest#{last_id+1}@test.com", 36 | username: params[:name].present? ? "#{params[:name]}" : "testtest#{last_id+1}", 37 | password: 'testtest', 38 | password_confirmation: 'testtest' 39 | ) 40 | user.skip_confirmation! 41 | user.save! 42 | user 43 | end 44 | 45 | # CONVENIENCE methods 46 | def get_aud 47 | Digest::SHA256.hexdigest("#{get_os}||||#{get_browser}") 48 | end 49 | 50 | def get_browser 51 | 'Chrome||89' 52 | end 53 | 54 | def get_os 55 | 'Linux||5.0' 56 | end 57 | 58 | def get_headers(login) 59 | jwt = get_jwt(login) 60 | { 61 | "Accept": "application/json", 62 | "Content-Type": "application/json", 63 | 'HTTP_JWT_AUD': get_aud, 64 | 'Authorization': "Bearer #{jwt}" 65 | } 66 | end 67 | 68 | def get_jwt(login) 69 | # NOTE: RSPEC sucks (uses HTTP_ because WTF) 70 | headers = { 'HTTP_JWT_AUD': get_aud } 71 | post '/users/sign_in', params: { 72 | user: { login: login, password: 'testtest' }, 73 | browser: get_browser, 74 | os: get_os 75 | }, headers: headers 76 | JSON.parse(response.body, object_class: OpenStruct).jwt 77 | end 78 | end 79 | 80 | RSpec.configure do |config| 81 | config.include ObjectCreators 82 | end 83 | -------------------------------------------------------------------------------- /storage/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidwparker/programmingtil-rails/9151797fae190b1abb7519240d3245dd58ba5347/storage/.keep -------------------------------------------------------------------------------- /tmp/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidwparker/programmingtil-rails/9151797fae190b1abb7519240d3245dd58ba5347/tmp/.keep -------------------------------------------------------------------------------- /tmp/pids/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidwparker/programmingtil-rails/9151797fae190b1abb7519240d3245dd58ba5347/tmp/pids/.keep -------------------------------------------------------------------------------- /vendor/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/davidwparker/programmingtil-rails/9151797fae190b1abb7519240d3245dd58ba5347/vendor/.keep --------------------------------------------------------------------------------