├── .bin └── rubocop ├── .circleci └── config.yml ├── .gitignore ├── .lvimrc ├── .pryrc ├── .rspec ├── .rubocop.yml ├── .rubocop_airbnb.yml ├── .ruby-version ├── Dockerfile ├── Gemfile ├── Gemfile.lock ├── Makefile ├── README.md ├── Rakefile ├── app ├── channels │ └── application_cable │ │ ├── channel.rb │ │ └── connection.rb ├── controllers │ ├── application_controller.rb │ ├── authenticated_controller.rb │ ├── concerns │ │ └── .keep │ ├── posts_controller.rb │ ├── sessions_controller.rb │ ├── users │ │ └── profile_image_controller.rb │ └── users_controller.rb ├── jobs │ └── application_job.rb ├── mailers │ └── application_mailer.rb ├── models │ ├── application_record.rb │ ├── concerns │ │ └── .keep │ ├── post.rb │ └── user.rb ├── services │ └── uploaders │ │ └── user_profile.rb └── views │ ├── layouts │ ├── mailer.html.erb │ └── mailer.text.erb │ ├── posts │ ├── _post.json.jbuilder │ ├── index.json.jbuilder │ └── show.json.jbuilder │ └── users │ ├── _user.json.jbuilder │ ├── profile_image │ ├── _user.json.jbuilder │ └── show.json.jbuilder │ ├── show.json.jbuilder │ └── success.json.jbuilder ├── bin ├── bundle ├── rails ├── rake ├── rspec ├── rubocop ├── setup └── update ├── config.ru ├── config ├── application.rb ├── boot.rb ├── cable.yml ├── credentials.yml.enc ├── database.yml ├── environment.rb ├── environments │ ├── development.rb │ ├── production.rb │ └── test.rb ├── initializers │ ├── application_controller_renderer.rb │ ├── ar_innodb_row_format.rb │ ├── backtrace_silencers.rb │ ├── cors.rb │ ├── devise.rb │ ├── devise_token_auth.rb │ ├── filter_parameter_logging.rb │ ├── inflections.rb │ ├── mime_types.rb │ ├── new_framework_defaults_6_0.rb │ └── wrap_parameters.rb ├── locales │ ├── devise.en.yml │ └── en.yml ├── puma.rb ├── routes.rb ├── spring.rb └── storage.yml ├── db ├── migrate │ ├── 20190415153210_devise_token_auth_create_users.rb │ ├── 20190424135040_create_posts.rb │ ├── 20190719152628_add_uuid_to_users.rb │ └── 20191206153351_add_foreign_key_constraint_to_active_storage_attachments_for_blob_id.active_storage.rb ├── schema.rb └── seeds.rb ├── docker-compose.yml ├── docker ├── bin │ ├── rails_start.sh │ └── wait_for_mysql.sh └── mysql │ └── conf.d │ └── mysql.cnf ├── lib └── tasks │ └── .keep ├── log └── .keep ├── public └── robots.txt ├── spec ├── factories │ ├── posts.rb │ ├── sequences.rb │ └── users.rb ├── fixtures │ └── files │ │ └── user_icon.png ├── rails_helper.rb ├── requests │ ├── posts │ │ ├── create_spec.rb │ │ ├── delete_spec.rb │ │ ├── index_spec.rb │ │ ├── show_spec.rb │ │ └── update_spec.rb │ └── users │ │ ├── profile_image │ │ └── create_spec.rb │ │ ├── show_spec.rb │ │ ├── success_spec.rb │ │ └── update_spec.rb ├── spec_helper.rb └── support │ └── requests │ └── auth_helpers.rb ├── storage └── .keep ├── tmp └── .keep └── vendor └── .keep /.bin/rubocop: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | docker-compose exec -T rails_api bundle exec rubocop $@ 3 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | build: 4 | machine: 5 | image: circleci/classic:edge 6 | working_directory: ~/repo 7 | steps: 8 | - checkout 9 | - run: 10 | name: Install Docker Compose 11 | command: | 12 | curl -L https://github.com/docker/compose/releases/download/1.19.0/docker-compose-`uname -s`-`uname -m` > ~/docker-compose 13 | chmod +x ~/docker-compose 14 | sudo mv ~/docker-compose /usr/local/bin/docker-compose 15 | - run: 16 | name: docker-compose up 17 | command: | 18 | set -x 19 | docker-compose up --build -d 20 | - run: 21 | name: docker-compose stop 22 | command: | 23 | set -x 24 | docker-compose stop 25 | - run: 26 | name: docker-compose up 27 | command: | 28 | set -x 29 | docker-compose up -d 30 | - run: 31 | name: bundle install 32 | command: | 33 | set -x 34 | docker-compose exec rails_api bin/bundle install --path=vendor/bundle 35 | - run: 36 | name: test 37 | command: | 38 | mkdir /tmp/test-results 39 | TEST_FILES="$(circleci tests glob 'spec/**/*_spec.rb' | circleci tests split --split-by=timings)" 40 | docker-compose exec rails_api bin/rspec --format progress \ 41 | --format RspecJunitFormatter \ 42 | --out /tmp/test-results/rspec.xml \ 43 | $TEST_FILES 44 | - run: 45 | name: rubocop 46 | command: | 47 | docker-compose exec rails_api bin/bundle exec rubocop 48 | - run: 49 | name: docker-compose down 50 | command: docker-compose down 51 | 52 | # collect reports 53 | # - store_test_results: 54 | # path: /tmp/test-results 55 | # - store_artifacts: 56 | # path: /tmp/test-results 57 | # destination: test-results 58 | -------------------------------------------------------------------------------- /.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 pidfiles, but keep the directory. 17 | /tmp/pids/* 18 | !/tmp/pids/ 19 | !/tmp/pids/.keep 20 | 21 | # Ignore uploaded files in development 22 | /storage/* 23 | !/storage/.keep 24 | 25 | .byebug_history 26 | 27 | # Ignore master key for decrypting credentials and more. 28 | /config/master.key 29 | 30 | # Ignore bundler directory 31 | vendor/bundle 32 | 33 | # Ignore upload directory 34 | public/uploads/* 35 | 36 | .DS_Store 37 | -------------------------------------------------------------------------------- /.lvimrc: -------------------------------------------------------------------------------- 1 | let g:ale_ruby_rubocop_executable = './.bin/rubocop' 2 | -------------------------------------------------------------------------------- /.pryrc: -------------------------------------------------------------------------------- 1 | if defined?(PryByebug) 2 | Pry.commands.alias_command '_c', 'continue' 3 | Pry.commands.alias_command '_s', 'step' 4 | Pry.commands.alias_command '_n', 'next' 5 | Pry.commands.alias_command '_f', 'finish' 6 | Pry.commands.alias_command '_w', 'whereami' 7 | end 8 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --require spec_helper 2 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | inherit_from: 2 | - .rubocop_airbnb.yml 3 | 4 | AllCops: 5 | TargetRubyVersion: 2.5 6 | Exclude: 7 | - '.git/**/*' 8 | - 'node_modules/**/*' 9 | - 'bin/*' 10 | - 'config/initializers/*' 11 | - 'spec/spec_helper.rb' 12 | - 'db/schema.rb' 13 | - 'db/**/*' 14 | - 'log/**/*' 15 | - 'tmp/**/*' 16 | - 'vendor/**/*' 17 | -------------------------------------------------------------------------------- /.rubocop_airbnb.yml: -------------------------------------------------------------------------------- 1 | require: 2 | - rubocop-airbnb 3 | 4 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | 2.5.6 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ruby:2.5.6 2 | 3 | RUN gem install bundler -v 1.17.3 4 | 5 | ENV APP_ROOT /app 6 | 7 | WORKDIR $APP_ROOT 8 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | git_source(:github) { |repo| "https://github.com/#{repo}.git" } 3 | 4 | ruby '2.5.6' 5 | 6 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails', branch: 'main' 7 | gem 'rails', '~> 6.0.4' 8 | # Use mysql as the database for Active Record 9 | gem 'mysql2', '>= 0.4.4', '< 0.6.0' 10 | # Use Puma as the app server 11 | gem 'puma', '~> 4.3' 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 ActiveStorage variant 20 | # gem 'mini_magick', '~> 4.8' 21 | 22 | # Use Capistrano for deployment 23 | # gem 'capistrano-rails', group: :development 24 | 25 | # Reduces boot times through caching; required in config/boot.rb 26 | gem 'bootsnap', '>= 1.4.2', require: false 27 | 28 | # Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible 29 | # gem 'rack-cors' 30 | 31 | group :development, :test do 32 | # Call 'byebug' anywhere in the code to stop execution and get a debugger console 33 | gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] 34 | 35 | gem 'pry-byebug' 36 | gem 'pry-stack_explorer' 37 | 38 | gem 'rspec-rails', '~> 3.8' 39 | gem 'factory_bot_rails' 40 | gem 'database_cleaner' 41 | gem 'rspec-request_describer' 42 | gem 'rspec-json_matcher' 43 | gem 'rspec_junit_formatter' 44 | end 45 | 46 | group :development do 47 | gem 'listen', '~> 3.2' 48 | # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring 49 | gem 'spring' 50 | gem 'spring-watcher-listen', '~> 2.0.0' 51 | end 52 | 53 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem 54 | gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] 55 | 56 | gem 'devise_token_auth', '~> 1.1.3' 57 | 58 | gem 'rubocop-airbnb' 59 | 60 | gem 'rack-cors', :require => 'rack/cors' 61 | 62 | gem 'carrierwave', '~> 2.1' 63 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | actioncable (6.0.4) 5 | actionpack (= 6.0.4) 6 | nio4r (~> 2.0) 7 | websocket-driver (>= 0.6.1) 8 | actionmailbox (6.0.4) 9 | actionpack (= 6.0.4) 10 | activejob (= 6.0.4) 11 | activerecord (= 6.0.4) 12 | activestorage (= 6.0.4) 13 | activesupport (= 6.0.4) 14 | mail (>= 2.7.1) 15 | actionmailer (6.0.4) 16 | actionpack (= 6.0.4) 17 | actionview (= 6.0.4) 18 | activejob (= 6.0.4) 19 | mail (~> 2.5, >= 2.5.4) 20 | rails-dom-testing (~> 2.0) 21 | actionpack (6.0.4) 22 | actionview (= 6.0.4) 23 | activesupport (= 6.0.4) 24 | rack (~> 2.0, >= 2.0.8) 25 | rack-test (>= 0.6.3) 26 | rails-dom-testing (~> 2.0) 27 | rails-html-sanitizer (~> 1.0, >= 1.2.0) 28 | actiontext (6.0.4) 29 | actionpack (= 6.0.4) 30 | activerecord (= 6.0.4) 31 | activestorage (= 6.0.4) 32 | activesupport (= 6.0.4) 33 | nokogiri (>= 1.8.5) 34 | actionview (6.0.4) 35 | activesupport (= 6.0.4) 36 | builder (~> 3.1) 37 | erubi (~> 1.4) 38 | rails-dom-testing (~> 2.0) 39 | rails-html-sanitizer (~> 1.1, >= 1.2.0) 40 | activejob (6.0.4) 41 | activesupport (= 6.0.4) 42 | globalid (>= 0.3.6) 43 | activemodel (6.0.4) 44 | activesupport (= 6.0.4) 45 | activerecord (6.0.4) 46 | activemodel (= 6.0.4) 47 | activesupport (= 6.0.4) 48 | activestorage (6.0.4) 49 | actionpack (= 6.0.4) 50 | activejob (= 6.0.4) 51 | activerecord (= 6.0.4) 52 | marcel (~> 1.0.0) 53 | activesupport (6.0.4) 54 | concurrent-ruby (~> 1.0, >= 1.0.2) 55 | i18n (>= 0.7, < 2) 56 | minitest (~> 5.1) 57 | tzinfo (~> 1.1) 58 | zeitwerk (~> 2.2, >= 2.2.2) 59 | addressable (2.8.0) 60 | public_suffix (>= 2.0.2, < 5.0) 61 | ast (2.4.0) 62 | awesome_print (1.8.0) 63 | bcrypt (3.1.13) 64 | binding_of_caller (0.8.0) 65 | debug_inspector (>= 0.0.1) 66 | bootsnap (1.4.5) 67 | msgpack (~> 1.0) 68 | builder (3.2.4) 69 | byebug (11.0.1) 70 | carrierwave (2.1.1) 71 | activemodel (>= 5.0.0) 72 | activesupport (>= 5.0.0) 73 | addressable (~> 2.6) 74 | image_processing (~> 1.1) 75 | mimemagic (>= 0.3.0) 76 | mini_mime (>= 0.1.3) 77 | ssrf_filter (~> 1.0) 78 | coderay (1.1.2) 79 | concurrent-ruby (1.1.9) 80 | crass (1.0.6) 81 | database_cleaner (1.7.0) 82 | debug_inspector (0.0.3) 83 | devise (4.7.1) 84 | bcrypt (~> 3.0) 85 | orm_adapter (~> 0.1) 86 | railties (>= 4.1.0) 87 | responders 88 | warden (~> 1.2.3) 89 | devise_token_auth (1.1.3) 90 | bcrypt (~> 3.0) 91 | devise (> 3.5.2, < 5) 92 | rails (>= 4.2.0, < 6.1) 93 | diff-lcs (1.3) 94 | erubi (1.10.0) 95 | factory_bot (5.0.2) 96 | activesupport (>= 4.2.0) 97 | factory_bot_rails (5.0.2) 98 | factory_bot (~> 5.0.2) 99 | railties (>= 4.2.0) 100 | ffi (1.14.2) 101 | globalid (0.4.2) 102 | activesupport (>= 4.2.0) 103 | i18n (1.8.10) 104 | concurrent-ruby (~> 1.0) 105 | image_processing (1.12.1) 106 | mini_magick (>= 4.9.5, < 5) 107 | ruby-vips (>= 2.0.17, < 3) 108 | jaro_winkler (1.5.2) 109 | jbuilder (2.9.1) 110 | activesupport (>= 4.2.0) 111 | json (2.3.1) 112 | listen (3.2.1) 113 | rb-fsevent (~> 0.10, >= 0.10.3) 114 | rb-inotify (~> 0.9, >= 0.9.10) 115 | loofah (2.10.0) 116 | crass (~> 1.0.2) 117 | nokogiri (>= 1.5.9) 118 | mail (2.7.1) 119 | mini_mime (>= 0.1.1) 120 | marcel (1.0.1) 121 | method_source (0.9.2) 122 | mimemagic (0.4.3) 123 | nokogiri (~> 1) 124 | rake 125 | mini_magick (4.11.0) 126 | mini_mime (1.1.0) 127 | mini_portile2 (2.5.3) 128 | minitest (5.14.4) 129 | msgpack (1.3.1) 130 | mysql2 (0.5.2) 131 | nio4r (2.5.7) 132 | nokogiri (1.11.7) 133 | mini_portile2 (~> 2.5.0) 134 | racc (~> 1.4) 135 | orm_adapter (0.5.0) 136 | parallel (1.17.0) 137 | parser (2.6.2.1) 138 | ast (~> 2.4.0) 139 | powerpack (0.1.2) 140 | pry (0.12.2) 141 | coderay (~> 1.1.0) 142 | method_source (~> 0.9.0) 143 | pry-byebug (3.7.0) 144 | byebug (~> 11.0) 145 | pry (~> 0.10) 146 | pry-stack_explorer (0.4.9.3) 147 | binding_of_caller (>= 0.7) 148 | pry (>= 0.9.11) 149 | public_suffix (4.0.6) 150 | puma (4.3.8) 151 | nio4r (~> 2.0) 152 | racc (1.5.2) 153 | rack (2.2.3) 154 | rack-cors (1.0.5) 155 | rack (>= 1.6.0) 156 | rack-test (1.1.0) 157 | rack (>= 1.0, < 3) 158 | rails (6.0.4) 159 | actioncable (= 6.0.4) 160 | actionmailbox (= 6.0.4) 161 | actionmailer (= 6.0.4) 162 | actionpack (= 6.0.4) 163 | actiontext (= 6.0.4) 164 | actionview (= 6.0.4) 165 | activejob (= 6.0.4) 166 | activemodel (= 6.0.4) 167 | activerecord (= 6.0.4) 168 | activestorage (= 6.0.4) 169 | activesupport (= 6.0.4) 170 | bundler (>= 1.3.0) 171 | railties (= 6.0.4) 172 | sprockets-rails (>= 2.0.0) 173 | rails-dom-testing (2.0.3) 174 | activesupport (>= 4.2.0) 175 | nokogiri (>= 1.6) 176 | rails-html-sanitizer (1.3.0) 177 | loofah (~> 2.3) 178 | railties (6.0.4) 179 | actionpack (= 6.0.4) 180 | activesupport (= 6.0.4) 181 | method_source 182 | rake (>= 0.8.7) 183 | thor (>= 0.20.3, < 2.0) 184 | rainbow (3.0.0) 185 | rake (13.0.3) 186 | rb-fsevent (0.10.4) 187 | rb-inotify (0.10.1) 188 | ffi (~> 1.0) 189 | responders (3.0.0) 190 | actionpack (>= 5.0) 191 | railties (>= 5.0) 192 | rspec-core (3.8.1) 193 | rspec-support (~> 3.8.0) 194 | rspec-expectations (3.8.4) 195 | diff-lcs (>= 1.2.0, < 2.0) 196 | rspec-support (~> 3.8.0) 197 | rspec-json_matcher (0.1.6) 198 | awesome_print 199 | json 200 | rspec-mocks (3.8.1) 201 | diff-lcs (>= 1.2.0, < 2.0) 202 | rspec-support (~> 3.8.0) 203 | rspec-rails (3.8.2) 204 | actionpack (>= 3.0) 205 | activesupport (>= 3.0) 206 | railties (>= 3.0) 207 | rspec-core (~> 3.8.0) 208 | rspec-expectations (~> 3.8.0) 209 | rspec-mocks (~> 3.8.0) 210 | rspec-support (~> 3.8.0) 211 | rspec-request_describer (0.3.1) 212 | actionpack (>= 5.0.0) 213 | rspec-support (3.8.2) 214 | rspec_junit_formatter (0.4.1) 215 | rspec-core (>= 2, < 4, != 2.12.0) 216 | rubocop (0.58.2) 217 | jaro_winkler (~> 1.5.1) 218 | parallel (~> 1.10) 219 | parser (>= 2.5, != 2.5.1.1) 220 | powerpack (~> 0.1) 221 | rainbow (>= 2.2.2, < 4.0) 222 | ruby-progressbar (~> 1.7) 223 | unicode-display_width (~> 1.0, >= 1.0.1) 224 | rubocop-airbnb (2.0.0) 225 | rubocop (~> 0.58.0) 226 | rubocop-rspec (~> 1.30.0) 227 | rubocop-rspec (1.30.0) 228 | rubocop (>= 0.58.0) 229 | ruby-progressbar (1.10.0) 230 | ruby-vips (2.0.17) 231 | ffi (~> 1.9) 232 | spring (2.0.2) 233 | activesupport (>= 4.2) 234 | spring-watcher-listen (2.0.1) 235 | listen (>= 2.7, < 4.0) 236 | spring (>= 1.2, < 3.0) 237 | sprockets (4.0.2) 238 | concurrent-ruby (~> 1.0) 239 | rack (> 1, < 3) 240 | sprockets-rails (3.2.2) 241 | actionpack (>= 4.0) 242 | activesupport (>= 4.0) 243 | sprockets (>= 3.0.0) 244 | ssrf_filter (1.0.7) 245 | thor (1.1.0) 246 | thread_safe (0.3.6) 247 | tzinfo (1.2.9) 248 | thread_safe (~> 0.1) 249 | unicode-display_width (1.5.0) 250 | warden (1.2.8) 251 | rack (>= 2.0.6) 252 | websocket-driver (0.7.5) 253 | websocket-extensions (>= 0.1.0) 254 | websocket-extensions (0.1.5) 255 | zeitwerk (2.4.2) 256 | 257 | PLATFORMS 258 | ruby 259 | 260 | DEPENDENCIES 261 | bootsnap (>= 1.4.2) 262 | byebug 263 | carrierwave (~> 2.1) 264 | database_cleaner 265 | devise_token_auth (~> 1.1.3) 266 | factory_bot_rails 267 | jbuilder (~> 2.7) 268 | listen (~> 3.2) 269 | mysql2 (>= 0.4.4, < 0.6.0) 270 | pry-byebug 271 | pry-stack_explorer 272 | puma (~> 4.3) 273 | rack-cors 274 | rails (~> 6.0.4) 275 | rspec-json_matcher 276 | rspec-rails (~> 3.8) 277 | rspec-request_describer 278 | rspec_junit_formatter 279 | rubocop-airbnb 280 | spring 281 | spring-watcher-listen (~> 2.0.0) 282 | tzinfo-data 283 | 284 | RUBY VERSION 285 | ruby 2.5.6p201 286 | 287 | BUNDLED WITH 288 | 1.17.3 289 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: tasks 2 | 3 | CMD= 4 | 5 | tasks: 6 | @echo Usage: make [task] 7 | @echo ------------------- 8 | @echo 9 | @cat Makefile 10 | 11 | docker_up: 12 | docker-compose up --build 13 | 14 | docker_up_background: 15 | docker-compose up -d 16 | 17 | docker_init: 18 | $(MAKE) docker_db 19 | $(MAKE) docker_seed 20 | 21 | docker_db: 22 | docker-compose exec rails_api bundle exec rails db:create 23 | docker-compose exec rails_api bundle exec rails db:migrate 24 | 25 | docker_seed: 26 | docker-compose exec rails_api bundle exec rake db:seed 27 | 28 | # e.g. $ make docker_exec CMD='bundle exec rspec' 29 | docker_exec: 30 | docker-compose exec rails_api $(CMD) 31 | 32 | docker_bash: 33 | $(MAKE) docker_exec CMD='bash' 34 | 35 | docker_attach: 36 | docker attach `docker ps -q -f name=rails-api-for-nuxtjs_rails_api` 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # README 2 | 3 | This branch uses MySQL. (Switch to [PostgreSQL](https://github.com/walkersumida/rails-api-for-front/tree/postgres)) 4 | 5 | [![CircleCI](https://circleci.com/gh/walkersumida/rails-api-for-front.svg?style=svg)](https://circleci.com/gh/walkersumida/rails-api-for-front) 6 | 7 | ## Run application 8 | 9 | ```bash 10 | make docker_up 11 | ``` 12 | 13 | ## Demo user 14 | 15 | | email | password | 16 | ----|---- 17 | | demo@xxx.com | demodemo | 18 | -------------------------------------------------------------------------------- /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/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::API 2 | include DeviseTokenAuth::Concerns::SetUserByToken 3 | end 4 | -------------------------------------------------------------------------------- /app/controllers/authenticated_controller.rb: -------------------------------------------------------------------------------- 1 | class AuthenticatedController < ApplicationController 2 | before_action :authenticate_user! 3 | end 4 | -------------------------------------------------------------------------------- /app/controllers/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walkersumida/rails-api-for-front/9942074aad6853cedd32063d30ec3875c14fd242/app/controllers/concerns/.keep -------------------------------------------------------------------------------- /app/controllers/posts_controller.rb: -------------------------------------------------------------------------------- 1 | class PostsController < AuthenticatedController 2 | before_action :set_post, only: %i(show update destroy) 3 | 4 | def index 5 | @posts = current_user.posts 6 | end 7 | 8 | def show 9 | # noop 10 | end 11 | 12 | def create 13 | @post = current_user.posts.build(post_params) 14 | 15 | if @post.save 16 | render :show, status: :created 17 | else 18 | render json: @post.errors, status: :unprocessable_entity 19 | end 20 | end 21 | 22 | def update 23 | if @post.update(post_params) 24 | render :show 25 | else 26 | render json: @post.errors, status: :unprocessable_entity 27 | end 28 | end 29 | 30 | def destroy 31 | @post.destroy 32 | end 33 | 34 | private 35 | 36 | def set_post 37 | @post = current_user.posts.find(params[:id]) 38 | end 39 | 40 | def post_params 41 | params.require(:post).permit(:title, :body, :status) 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /app/controllers/sessions_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class SessionsController < DeviseTokenAuth::SessionsController 4 | def render_create_success 5 | render 'users/success', formats: :json 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /app/controllers/users/profile_image_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Users::ProfileImageController < AuthenticatedController 4 | def create 5 | if current_user.update(user_params) 6 | render :show 7 | else 8 | render json: current_user.errors, status: :unprocessable_entity 9 | end 10 | end 11 | 12 | private 13 | 14 | def user_uuid 15 | params[:uuid] == 'me' ? current_user.uuid : params[:uuid] 16 | end 17 | 18 | def user_params 19 | params.permit(:image) 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /app/controllers/users_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class UsersController < AuthenticatedController 4 | before_action :set_user, only: %i(show) 5 | 6 | def show 7 | # noop 8 | end 9 | 10 | def update 11 | if current_user.update(user_params) 12 | render :show 13 | else 14 | render json: current_user.errors, status: :unprocessable_entity 15 | end 16 | end 17 | 18 | private 19 | 20 | def user_uuid 21 | params[:uuid] == 'me' ? current_user.uuid : params[:uuid] 22 | end 23 | 24 | def set_user 25 | @user = User.find_by!(uuid: user_uuid) 26 | end 27 | 28 | def user_params 29 | params.require(:user).permit(:nickname) 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /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/application_record.rb: -------------------------------------------------------------------------------- 1 | class ApplicationRecord < ActiveRecord::Base 2 | self.abstract_class = true 3 | end 4 | -------------------------------------------------------------------------------- /app/models/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walkersumida/rails-api-for-front/9942074aad6853cedd32063d30ec3875c14fd242/app/models/concerns/.keep -------------------------------------------------------------------------------- /app/models/post.rb: -------------------------------------------------------------------------------- 1 | class Post < ApplicationRecord 2 | belongs_to :user 3 | end 4 | -------------------------------------------------------------------------------- /app/models/user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'carrierwave/orm/activerecord' 4 | 5 | class User < ActiveRecord::Base 6 | # Include default devise modules. Others available are: 7 | # :confirmable, :lockable, :timeoutable and :omniauthable 8 | devise :database_authenticatable, :registerable, 9 | :recoverable, :rememberable, :trackable, :validatable 10 | include DeviseTokenAuth::Concerns::User 11 | 12 | mount_uploader :image, Uploaders::UserProfile 13 | 14 | has_many :posts, dependent: :destroy 15 | 16 | before_validation :generate_uuid 17 | 18 | def generate_uuid 19 | self.uuid ||= SecureRandom.uuid 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /app/services/uploaders/user_profile.rb: -------------------------------------------------------------------------------- 1 | module Uploaders 2 | class UserProfile < CarrierWave::Uploader::Base 3 | # Include RMagick or MiniMagick support: 4 | # include CarrierWave::RMagick 5 | # include CarrierWave::MiniMagick 6 | 7 | # Choose what kind of storage to use for this uploader: 8 | storage :file 9 | # storage :fog 10 | 11 | # Override the directory where uploaded files will be stored. 12 | # This is a sensible default for uploaders that are meant to be mounted: 13 | def store_dir 14 | "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.uuid}" 15 | end 16 | 17 | # Provide a default URL as a default if there hasn't been a file uploaded: 18 | # def default_url(*args) 19 | # # For Rails 3.1+ asset pipeline compatibility: 20 | # # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"] 21 | # .compact.join('_')) 22 | # 23 | # "/images/fallback/" + [version_name, "default.png"].compact.join('_') 24 | # end 25 | 26 | # Process files as they are uploaded: 27 | # process scale: [200, 300] 28 | # 29 | # def scale(width, height) 30 | # # do something 31 | # end 32 | 33 | # Create different versions of your uploaded files: 34 | # version :thumb do 35 | # process resize_to_fit: [50, 50] 36 | # end 37 | 38 | # Add a white list of extensions which are allowed to be uploaded. 39 | # For images you might use something like this: 40 | # def extension_whitelist 41 | # %w(jpg jpeg gif png) 42 | # end 43 | 44 | # Override the filename of the uploaded files: 45 | # Avoid using model.id or version_name here, see uploader/store.rb for details. 46 | # def filename 47 | # "something.jpg" if original_filename 48 | # end 49 | end 50 | end 51 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /app/views/posts/_post.json.jbuilder: -------------------------------------------------------------------------------- 1 | json.extract! post, :id, :user_id, :title, :body, :status, :created_at, :updated_at 2 | -------------------------------------------------------------------------------- /app/views/posts/index.json.jbuilder: -------------------------------------------------------------------------------- 1 | json.array! @posts, partial: 'posts/post', as: :post 2 | -------------------------------------------------------------------------------- /app/views/posts/show.json.jbuilder: -------------------------------------------------------------------------------- 1 | json.partial! 'posts/post', post: @post 2 | -------------------------------------------------------------------------------- /app/views/users/_user.json.jbuilder: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | json.id user.uuid 4 | json.email user.email 5 | json.name user.name 6 | json.nickname user.nickname 7 | json.image user.image 8 | -------------------------------------------------------------------------------- /app/views/users/profile_image/_user.json.jbuilder: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | json.image user.image 4 | -------------------------------------------------------------------------------- /app/views/users/profile_image/show.json.jbuilder: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | json.partial! 'users/profile_image/user', user: (@user || current_user) 4 | -------------------------------------------------------------------------------- /app/views/users/show.json.jbuilder: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | json.partial! 'users/user', user: (@user || current_user) 4 | -------------------------------------------------------------------------------- /app/views/users/success.json.jbuilder: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | json.partial! 'users/user', user: @resource 4 | -------------------------------------------------------------------------------- /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 || ">= 0.a" 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 ||= begin 65 | env_var_version || cli_arg_version || 66 | lockfile_version || "#{Gem::Requirement.default}.a" 67 | end 68 | end 69 | 70 | def load_bundler! 71 | ENV["BUNDLE_GEMFILE"] ||= gemfile 72 | 73 | # must dup string for RG < 1.8 compatibility 74 | activate_bundler(bundler_version.dup) 75 | end 76 | 77 | def activate_bundler(bundler_version) 78 | if Gem::Version.correct?(bundler_version) && Gem::Version.new(bundler_version).release < Gem::Version.new("2.0") 79 | bundler_version = "< 2" 80 | end 81 | gem_error = activation_error_handling do 82 | gem "bundler", bundler_version 83 | end 84 | return if gem_error.nil? 85 | require_error = activation_error_handling do 86 | require "bundler/version" 87 | end 88 | return if require_error.nil? && Gem::Requirement.new(bundler_version).satisfied_by?(Gem::Version.new(Bundler::VERSION)) 89 | warn "Activating bundler (#{bundler_version}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_version}'`" 90 | exit 42 91 | end 92 | 93 | def activation_error_handling 94 | yield 95 | nil 96 | rescue StandardError, LoadError => e 97 | e 98 | end 99 | end 100 | 101 | m.load_bundler! 102 | 103 | if m.invoked_as_script? 104 | load Gem.bin_path("bundler", "bundle") 105 | end 106 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | APP_PATH = File.expand_path('../config/application', __dir__) 3 | require_relative '../config/boot' 4 | require 'rails/commands' 5 | -------------------------------------------------------------------------------- /bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require_relative '../config/boot' 3 | require 'rake' 4 | Rake.application.run 5 | -------------------------------------------------------------------------------- /bin/rspec: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # 5 | # This file was generated by Bundler. 6 | # 7 | # The application 'rspec' is installed as part of a gem, and 8 | # this file is here to facilitate running it. 9 | # 10 | 11 | require "pathname" 12 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", 13 | Pathname.new(__FILE__).realpath) 14 | 15 | bundle_binstub = File.expand_path("../bundle", __FILE__) 16 | 17 | if File.file?(bundle_binstub) 18 | if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/ 19 | load(bundle_binstub) 20 | else 21 | abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. 22 | Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") 23 | end 24 | end 25 | 26 | require "rubygems" 27 | require "bundler/setup" 28 | 29 | load Gem.bin_path("rspec-core", "rspec") 30 | -------------------------------------------------------------------------------- /bin/rubocop: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # 5 | # This file was generated by Bundler. 6 | # 7 | # The application 'rubocop' is installed as part of a gem, and 8 | # this file is here to facilitate running it. 9 | # 10 | 11 | require "pathname" 12 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", 13 | Pathname.new(__FILE__).realpath) 14 | 15 | bundle_binstub = File.expand_path("../bundle", __FILE__) 16 | 17 | if File.file?(bundle_binstub) 18 | if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/ 19 | load(bundle_binstub) 20 | else 21 | abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. 22 | Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") 23 | end 24 | end 25 | 26 | require "rubygems" 27 | require "bundler/setup" 28 | 29 | load Gem.bin_path("rubocop", "rubocop") 30 | -------------------------------------------------------------------------------- /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 setup or update your development environment automatically. 13 | # This script is idempotent, so that you can run it at anytime 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/update: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'fileutils' 3 | include FileUtils 4 | 5 | # path to your application root. 6 | APP_ROOT = File.expand_path('..', __dir__) 7 | 8 | def system!(*args) 9 | system(*args) || abort("\n== Command #{args} failed ==") 10 | end 11 | 12 | chdir APP_ROOT do 13 | # This script is a way to update your development environment automatically. 14 | # Add necessary update 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== Updating database ==" 21 | system! 'bin/rails db:migrate' 22 | 23 | puts "\n== Removing old logs and tempfiles ==" 24 | system! 'bin/rails log:clear tmp:clear' 25 | 26 | puts "\n== Restarting application server ==" 27 | system! 'bin/rails restart' 28 | end 29 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 RailsApiForNuxtjs 23 | class Application < Rails::Application 24 | # Initialize configuration defaults for originally generated Rails version. 25 | config.load_defaults 6.0 26 | 27 | # Settings in config/environments/* take precedence over those specified here. 28 | # Application configuration can go into files in config/initializers 29 | # -- all .rb files in that directory are automatically loaded after loading 30 | # the framework and any gems in your application. 31 | 32 | # Only loads a smaller set of middleware suitable for API only apps. 33 | # Middleware like session, flash, cookies can be added back manually. 34 | # Skip views, helpers and assets when generating a new resource. 35 | config.api_only = true 36 | config.autoload_paths += %W(#{config.root}/app/services) 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /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: rails_api_for_nuxtjs_production 11 | -------------------------------------------------------------------------------- /config/credentials.yml.enc: -------------------------------------------------------------------------------- 1 | c2BvkZhaeyUwsZv7EVkXuEPgtsnE/r5ENcoe9SnCQSCwhOnrdBBddyO7T2r3eCabHpNuUfA3nIwdn+mjTSQgtPpV/Q545hlRavoUHHMLoRb1XTfVIFhzBa0r1T6X118IETu8Nb7GhLsrc81jWmxIA0xXUo7uFYm/jlBK/ypKKSiII2LtLe3lzPrnzSJmWZqS3vi3riV3T6EDcvWb9U7jexVpQ6JQf6izBCYiNZWVVDRInDm5G++WjVnDkIUXEzG+/bhz6coDicUHq6/1jsXBIwCnar/YwnCEBOnF4M2nEKUeUX0+IJCMg2dfip1cvup6L7SITy6GuTqCJQfKCLJAEiNvUQ2va54JV73eC+4WgehRAhF5VtVfBp6SrpX3Bh9S3Zej/FyUEd48XIZkHpW2S0P2s9KrQ9js3juN--hCFYYrwWx0J4Ni6G--H1REQ6Kpv7sIrNGeMfQZZQ== -------------------------------------------------------------------------------- /config/database.yml: -------------------------------------------------------------------------------- 1 | # MySQL. Versions 5.1.10 and up are supported. 2 | # 3 | # Install the MySQL driver 4 | # gem install mysql2 5 | # 6 | # Ensure the MySQL gem is defined in your Gemfile 7 | # gem 'mysql2' 8 | # 9 | # And be sure to use new-style password hashing: 10 | # https://dev.mysql.com/doc/refman/5.7/en/password-hashing.html 11 | # 12 | default: &default 13 | adapter: mysql2 14 | charset: utf8mb4 15 | encoding: utf8mb4 16 | collation: utf8mb4_general_ci 17 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> 18 | username: <%= ENV['DB_USERNAME'] || 'root' %> 19 | password: <%= ENV['DB_PASSWORD'] || 'root' %> 20 | host: <%= ENV['DB_HOST'] || '127.0.0.1' %> 21 | 22 | development: 23 | <<: *default 24 | database: rails-api-for-nuxtjs_development 25 | 26 | # Warning: The database defined as "test" will be erased and 27 | # re-generated from your development database when you run "rake". 28 | # Do not set this db to the same as development or production. 29 | test: 30 | <<: *default 31 | database: rails-api-for-nuxtjs_test 32 | 33 | # As with config/secrets.yml, you never want to store sensitive information, 34 | # like your database password, in your source code. If your source code is 35 | # ever seen by anyone, they now have access to your database. 36 | # 37 | # Instead, provide the password as a unix environment variable when you boot 38 | # the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database 39 | # for a full rundown on how to provide these environment variables in a 40 | # production deployment. 41 | # 42 | # On Heroku and other platform providers, you may have a full connection URL 43 | # available as an environment variable. For example: 44 | # 45 | # DATABASE_URL="mysql2://myuser:mypass@localhost/somedatabase" 46 | # 47 | # You can use this database configuration with: 48 | # 49 | # production: 50 | # url: <%= ENV['DATABASE_URL'] %> 51 | # 52 | production: 53 | <<: *default 54 | database: rails-api-for-nuxtjs_production 55 | username: rails-api-for-nuxtjs 56 | password: <%= ENV['RAILS-API-FOR-NUXTJS_DATABASE_PASSWORD'] %> 57 | -------------------------------------------------------------------------------- /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 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # In the development environment your application's code is reloaded on 5 | # every request. This slows down response time but is perfect for development 6 | # since you don't have to restart the web server when you make code changes. 7 | config.cache_classes = false 8 | 9 | # Do not eager load code on boot. 10 | config.eager_load = false 11 | 12 | # Show full error reports. 13 | config.consider_all_requests_local = true 14 | 15 | # Enable/disable caching. By default caching is disabled. 16 | # Run rails dev:cache to toggle caching. 17 | if Rails.root.join('tmp', 'caching-dev.txt').exist? 18 | config.cache_store = :memory_store 19 | config.public_file_server.headers = { 20 | 'Cache-Control' => "public, max-age=#{2.days.to_i}", 21 | } 22 | else 23 | config.action_controller.perform_caching = false 24 | 25 | config.cache_store = :null_store 26 | end 27 | 28 | # Store uploaded files on the local file system (see config/storage.yml for options). 29 | config.active_storage.service = :local 30 | 31 | # Don't care if the mailer can't send. 32 | config.action_mailer.raise_delivery_errors = false 33 | 34 | config.action_mailer.perform_caching = false 35 | 36 | # Print deprecation notices to the Rails logger. 37 | config.active_support.deprecation = :log 38 | 39 | # Raise an error on page load if there are pending migrations. 40 | config.active_record.migration_error = :page_load 41 | 42 | # Highlight code that triggered database queries in logs. 43 | config.active_record.verbose_query_logs = true 44 | 45 | # Raises error for missing translations. 46 | # config.action_view.raise_on_missing_translations = true 47 | 48 | # Use an evented file watcher to asynchronously detect changes in source code, 49 | # routes, locales, etc. This feature depends on the listen gem. 50 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker 51 | end 52 | -------------------------------------------------------------------------------- /config/environments/production.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 | 16 | # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] 17 | # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). 18 | # config.require_master_key = true 19 | 20 | # Disable serving static files from the `/public` folder by default since 21 | # Apache or NGINX already handles this. 22 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 23 | 24 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 25 | # config.action_controller.asset_host = 'http://assets.example.com' 26 | 27 | # Specifies the header that your server uses for sending files. 28 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 29 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 30 | 31 | # Store uploaded files on the local file system (see config/storage.yml for options). 32 | config.active_storage.service = :local 33 | 34 | # Mount Action Cable outside main process or domain. 35 | # config.action_cable.mount_path = nil 36 | # config.action_cable.url = 'wss://example.com/cable' 37 | # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] 38 | 39 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 40 | # config.force_ssl = true 41 | 42 | # Use the lowest log level to ensure availability of diagnostic information 43 | # when problems arise. 44 | config.log_level = :debug 45 | 46 | # Prepend all log lines with the following tags. 47 | config.log_tags = [:request_id] 48 | 49 | # Use a different cache store in production. 50 | # config.cache_store = :mem_cache_store 51 | 52 | # Use a real queuing backend for Active Job (and separate queues per environment). 53 | # config.active_job.queue_adapter = :resque 54 | # config.active_job.queue_name_prefix = "rails_api_for_nuxtjs_production" 55 | 56 | config.action_mailer.perform_caching = false 57 | 58 | # Ignore bad email addresses and do not raise email delivery errors. 59 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 60 | # config.action_mailer.raise_delivery_errors = false 61 | 62 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 63 | # the I18n.default_locale when a translation cannot be found). 64 | config.i18n.fallbacks = true 65 | 66 | # Send deprecation notices to registered listeners. 67 | config.active_support.deprecation = :notify 68 | 69 | # Use default logging formatter so that PID and timestamp are not suppressed. 70 | config.log_formatter = ::Logger::Formatter.new 71 | 72 | # Use a different logger for distributed setups. 73 | # require 'syslog/logger' 74 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 75 | 76 | if ENV["RAILS_LOG_TO_STDOUT"].present? 77 | logger = ActiveSupport::Logger.new(STDOUT) 78 | logger.formatter = config.log_formatter 79 | config.logger = ActiveSupport::TaggedLogging.new(logger) 80 | end 81 | 82 | # Do not dump schema after migrations. 83 | config.active_record.dump_schema_after_migration = false 84 | 85 | # Inserts middleware to perform automatic connection switching. 86 | # The `database_selector` hash is used to pass options to the DatabaseSelector 87 | # middleware. The `delay` is used to determine how long to wait after a write 88 | # to send a subsequent read to the primary. 89 | # 90 | # The `database_resolver` class is used by the middleware to determine which 91 | # database is appropriate to use based on the time delay. 92 | # 93 | # The `database_resolver_context` class is used by the middleware to set 94 | # timestamps for the last write to the primary. The resolver uses the context 95 | # class timestamps to determine how long to wait before reading from the 96 | # replica. 97 | # 98 | # By default Rails will store a last write timestamp in the session. The 99 | # DatabaseSelector middleware is designed as such you can define your own 100 | # strategy for connection switching and pass that into the middleware through 101 | # these configuration options. 102 | # config.active_record.database_selector = { delay: 2.seconds } 103 | # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver 104 | # config.active_record.database_resolver_context = 105 | # ActiveRecord::Middleware::DatabaseSelector::Resolver::Session 106 | end 107 | -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | # The test environment is used exclusively to run your application's 2 | # test suite. You never need to work with it otherwise. Remember that 3 | # your test database is "scratch space" for the test suite and is wiped 4 | # and recreated between test runs. Don't rely on the data there! 5 | 6 | Rails.application.configure do 7 | # Settings specified here will take precedence over those in config/application.rb. 8 | 9 | config.cache_classes = false 10 | config.action_view.cache_template_loading = true 11 | 12 | # Do not eager load code on boot. This avoids loading your whole application 13 | # just for the purpose of running a single test. If you are using a tool that 14 | # preloads Rails for running tests, you may have to set it to true. 15 | config.eager_load = false 16 | 17 | # Configure public file server for tests with Cache-Control for performance. 18 | config.public_file_server.enabled = true 19 | config.public_file_server.headers = { 20 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}", 21 | } 22 | 23 | # Show full error reports and disable caching. 24 | config.consider_all_requests_local = true 25 | config.action_controller.perform_caching = false 26 | config.cache_store = :null_store 27 | 28 | # Raise exceptions instead of rendering exception templates. 29 | config.action_dispatch.show_exceptions = false 30 | 31 | # Disable request forgery protection in test environment. 32 | config.action_controller.allow_forgery_protection = false 33 | 34 | # Store uploaded files on the local file system in a temporary directory. 35 | config.active_storage.service = :test 36 | 37 | config.action_mailer.perform_caching = false 38 | 39 | # Tell Action Mailer not to deliver emails to the real world. 40 | # The :test delivery method accumulates sent emails in the 41 | # ActionMailer::Base.deliveries array. 42 | config.action_mailer.delivery_method = :test 43 | 44 | # Print deprecation notices to the stderr. 45 | config.active_support.deprecation = :stderr 46 | 47 | # Raises error for missing translations. 48 | # config.action_view.raise_on_missing_translations = true 49 | end 50 | 51 | # carrierwave gem 52 | CarrierWave.configure do |config| 53 | config.storage = :file 54 | config.enable_processing = false 55 | end 56 | -------------------------------------------------------------------------------- /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/ar_innodb_row_format.rb: -------------------------------------------------------------------------------- 1 | module Utf8mb4 2 | def create_table(table_name, options = {}) 3 | table_options = options.merge(options: 'ENGINE=InnoDB ROW_FORMAT=DYNAMIC') 4 | super(table_name, table_options) do |td| 5 | yield td if block_given? 6 | end 7 | end 8 | end 9 | 10 | ActiveSupport.on_load :active_record do 11 | module ActiveRecord::ConnectionAdapters 12 | class AbstractMysqlAdapter 13 | prepend Utf8mb4 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /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| line =~ /my_noisy_library/ } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 7 | # Rails.backtrace_cleaner.remove_silencers! 8 | -------------------------------------------------------------------------------- /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 | allow do 10 | origins '*' 11 | resource '*', 12 | headers: :any, 13 | expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'], 14 | methods: [:get, :post, :options, :delete, :put, :patch] 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /config/initializers/devise.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Use this hook to configure devise mailer, warden hooks and so forth. 4 | # Many of these configuration options can be set straight in your model. 5 | Devise.setup do |config| 6 | # The secret key used by Devise. Devise uses this key to generate 7 | # random tokens. Changing this key will render invalid all existing 8 | # confirmation, reset password and unlock tokens in the database. 9 | # Devise will use the `secret_key_base` as its `secret_key` 10 | # by default. You can change it below and use your own secret key. 11 | # config.secret_key = '4b10705a9a38885586cd2c7547a8310817ba90405190f93793657e8424d5c6abe165d46987a56ca4c2a6ffefd0fafdd71c10ee63b2cd592bc4531a34c38d1dfa' 12 | 13 | # ==> Controller configuration 14 | # Configure the parent class to the devise controllers. 15 | # config.parent_controller = 'DeviseController' 16 | 17 | # ==> Mailer Configuration 18 | # Configure the e-mail address which will be shown in Devise::Mailer, 19 | # note that it will be overwritten if you use your own mailer class 20 | # with default "from" parameter. 21 | config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' 22 | 23 | # Configure the class responsible to send e-mails. 24 | # config.mailer = 'Devise::Mailer' 25 | 26 | # Configure the parent class responsible to send e-mails. 27 | # config.parent_mailer = 'ActionMailer::Base' 28 | 29 | # ==> ORM configuration 30 | # Load and configure the ORM. Supports :active_record (default) and 31 | # :mongoid (bson_ext recommended) by default. Other ORMs may be 32 | # available as additional gems. 33 | require 'devise/orm/active_record' 34 | 35 | # ==> Configuration for any authentication mechanism 36 | # Configure which keys are used when authenticating a user. The default is 37 | # just :email. You can configure it to use [:username, :subdomain], so for 38 | # authenticating a user, both parameters are required. Remember that those 39 | # parameters are used only when authenticating and not when retrieving from 40 | # session. If you need permissions, you should implement that in a before filter. 41 | # You can also supply a hash where the value is a boolean determining whether 42 | # or not authentication should be aborted when the value is not present. 43 | # config.authentication_keys = [:email] 44 | 45 | # Configure parameters from the request object used for authentication. Each entry 46 | # given should be a request method and it will automatically be passed to the 47 | # find_for_authentication method and considered in your model lookup. For instance, 48 | # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. 49 | # The same considerations mentioned for authentication_keys also apply to request_keys. 50 | # config.request_keys = [] 51 | 52 | # Configure which authentication keys should be case-insensitive. 53 | # These keys will be downcased upon creating or modifying a user and when used 54 | # to authenticate or find a user. Default is :email. 55 | config.case_insensitive_keys = [:email] 56 | 57 | # Configure which authentication keys should have whitespace stripped. 58 | # These keys will have whitespace before and after removed upon creating or 59 | # modifying a user and when used to authenticate or find a user. Default is :email. 60 | config.strip_whitespace_keys = [:email] 61 | 62 | # Tell if authentication through request.params is enabled. True by default. 63 | # It can be set to an array that will enable params authentication only for the 64 | # given strategies, for example, `config.params_authenticatable = [:database]` will 65 | # enable it only for database (email + password) authentication. 66 | # config.params_authenticatable = true 67 | 68 | # Tell if authentication through HTTP Auth is enabled. False by default. 69 | # It can be set to an array that will enable http authentication only for the 70 | # given strategies, for example, `config.http_authenticatable = [:database]` will 71 | # enable it only for database authentication. The supported strategies are: 72 | # :database = Support basic authentication with authentication key + password 73 | # config.http_authenticatable = false 74 | 75 | # If 401 status code should be returned for AJAX requests. True by default. 76 | # config.http_authenticatable_on_xhr = true 77 | 78 | # The realm used in Http Basic Authentication. 'Application' by default. 79 | # config.http_authentication_realm = 'Application' 80 | 81 | # It will change confirmation, password recovery and other workflows 82 | # to behave the same regardless if the e-mail provided was right or wrong. 83 | # Does not affect registerable. 84 | # config.paranoid = true 85 | 86 | # By default Devise will store the user in session. You can skip storage for 87 | # particular strategies by setting this option. 88 | # Notice that if you are skipping storage for all authentication paths, you 89 | # may want to disable generating routes to Devise's sessions controller by 90 | # passing skip: :sessions to `devise_for` in your config/routes.rb 91 | config.skip_session_storage = [:http_auth] 92 | 93 | # By default, Devise cleans up the CSRF token on authentication to 94 | # avoid CSRF token fixation attacks. This means that, when using AJAX 95 | # requests for sign in and sign up, you need to get a new CSRF token 96 | # from the server. You can disable this option at your own risk. 97 | # config.clean_up_csrf_token_on_authentication = true 98 | 99 | # When false, Devise will not attempt to reload routes on eager load. 100 | # This can reduce the time taken to boot the app but if your application 101 | # requires the Devise mappings to be loaded during boot time the application 102 | # won't boot properly. 103 | # config.reload_routes = true 104 | 105 | # ==> Configuration for :database_authenticatable 106 | # For bcrypt, this is the cost for hashing the password and defaults to 11. If 107 | # using other algorithms, it sets how many times you want the password to be hashed. 108 | # 109 | # Limiting the stretches to just one in testing will increase the performance of 110 | # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use 111 | # a value less than 10 in other environments. Note that, for bcrypt (the default 112 | # algorithm), the cost increases exponentially with the number of stretches (e.g. 113 | # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). 114 | config.stretches = Rails.env.test? ? 1 : 11 115 | 116 | # Set up a pepper to generate the hashed password. 117 | # config.pepper = 'b54687fb971e727701e65e4da360ffe2ad332b25cececc397b277cfc30e61a056219e50a714c2fec894d412951f6ead69b00b19523ec7cb4636aa96057908be4' 118 | 119 | # Send a notification to the original email when the user's email is changed. 120 | # config.send_email_changed_notification = false 121 | 122 | # Send a notification email when the user's password is changed. 123 | # config.send_password_change_notification = false 124 | 125 | # ==> Configuration for :confirmable 126 | # A period that the user is allowed to access the website even without 127 | # confirming their account. For instance, if set to 2.days, the user will be 128 | # able to access the website for two days without confirming their account, 129 | # access will be blocked just in the third day. 130 | # You can also set it to nil, which will allow the user to access the website 131 | # without confirming their account. 132 | # Default is 0.days, meaning the user cannot access the website without 133 | # confirming their account. 134 | # config.allow_unconfirmed_access_for = 2.days 135 | 136 | # A period that the user is allowed to confirm their account before their 137 | # token becomes invalid. For example, if set to 3.days, the user can confirm 138 | # their account within 3 days after the mail was sent, but on the fourth day 139 | # their account can't be confirmed with the token any more. 140 | # Default is nil, meaning there is no restriction on how long a user can take 141 | # before confirming their account. 142 | # config.confirm_within = 3.days 143 | 144 | # If true, requires any email changes to be confirmed (exactly the same way as 145 | # initial account confirmation) to be applied. Requires additional unconfirmed_email 146 | # db field (see migrations). Until confirmed, new email is stored in 147 | # unconfirmed_email column, and copied to email column on successful confirmation. 148 | config.reconfirmable = true 149 | 150 | # Defines which key will be used when confirming an account 151 | # config.confirmation_keys = [:email] 152 | 153 | # ==> Configuration for :rememberable 154 | # The time the user will be remembered without asking for credentials again. 155 | # config.remember_for = 2.weeks 156 | 157 | # Invalidates all the remember me tokens when the user signs out. 158 | config.expire_all_remember_me_on_sign_out = true 159 | 160 | # If true, extends the user's remember period when remembered via cookie. 161 | # config.extend_remember_period = false 162 | 163 | # Options to be passed to the created cookie. For instance, you can set 164 | # secure: true in order to force SSL only cookies. 165 | # config.rememberable_options = {} 166 | 167 | # ==> Configuration for :validatable 168 | # Range for password length. 169 | config.password_length = 6..128 170 | 171 | # Email regex used to validate email formats. It simply asserts that 172 | # one (and only one) @ exists in the given string. This is mainly 173 | # to give user feedback and not to assert the e-mail validity. 174 | config.email_regexp = /\A[^@\s]+@[^@\s]+\z/ 175 | 176 | # ==> Configuration for :timeoutable 177 | # The time you want to timeout the user session without activity. After this 178 | # time the user will be asked for credentials again. Default is 30 minutes. 179 | # config.timeout_in = 30.minutes 180 | 181 | # ==> Configuration for :lockable 182 | # Defines which strategy will be used to lock an account. 183 | # :failed_attempts = Locks an account after a number of failed attempts to sign in. 184 | # :none = No lock strategy. You should handle locking by yourself. 185 | # config.lock_strategy = :failed_attempts 186 | 187 | # Defines which key will be used when locking and unlocking an account 188 | # config.unlock_keys = [:email] 189 | 190 | # Defines which strategy will be used to unlock an account. 191 | # :email = Sends an unlock link to the user email 192 | # :time = Re-enables login after a certain amount of time (see :unlock_in below) 193 | # :both = Enables both strategies 194 | # :none = No unlock strategy. You should handle unlocking by yourself. 195 | # config.unlock_strategy = :both 196 | 197 | # Number of authentication tries before locking an account if lock_strategy 198 | # is failed attempts. 199 | # config.maximum_attempts = 20 200 | 201 | # Time interval to unlock the account if :time is enabled as unlock_strategy. 202 | # config.unlock_in = 1.hour 203 | 204 | # Warn on the last attempt before the account is locked. 205 | # config.last_attempt_warning = true 206 | 207 | # ==> Configuration for :recoverable 208 | # 209 | # Defines which key will be used when recovering the password for an account 210 | # config.reset_password_keys = [:email] 211 | 212 | # Time interval you can reset your password with a reset password key. 213 | # Don't put a too small interval or your users won't have the time to 214 | # change their passwords. 215 | config.reset_password_within = 6.hours 216 | 217 | # When set to false, does not sign a user in automatically after their password is 218 | # reset. Defaults to true, so a user is signed in automatically after a reset. 219 | # config.sign_in_after_reset_password = true 220 | 221 | # ==> Configuration for :encryptable 222 | # Allow you to use another hashing or encryption algorithm besides bcrypt (default). 223 | # You can use :sha1, :sha512 or algorithms from others authentication tools as 224 | # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20 225 | # for default behavior) and :restful_authentication_sha1 (then you should set 226 | # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper). 227 | # 228 | # Require the `devise-encryptable` gem when using anything other than bcrypt 229 | # config.encryptor = :sha512 230 | 231 | # ==> Scopes configuration 232 | # Turn scoped views on. Before rendering "sessions/new", it will first check for 233 | # "users/sessions/new". It's turned off by default because it's slower if you 234 | # are using only default views. 235 | # config.scoped_views = false 236 | 237 | # Configure the default scope given to Warden. By default it's the first 238 | # devise role declared in your routes (usually :user). 239 | # config.default_scope = :user 240 | 241 | # Set this configuration to false if you want /users/sign_out to sign out 242 | # only the current scope. By default, Devise signs out all scopes. 243 | # config.sign_out_all_scopes = true 244 | 245 | # ==> Navigation configuration 246 | # Lists the formats that should be treated as navigational. Formats like 247 | # :html, should redirect to the sign in page when the user does not have 248 | # access, but formats like :xml or :json, should return 401. 249 | # 250 | # If you have any extra navigational formats, like :iphone or :mobile, you 251 | # should add them to the navigational formats lists. 252 | # 253 | # The "*/*" below is required to match Internet Explorer requests. 254 | # config.navigational_formats = ['*/*', :html] 255 | 256 | # The default HTTP method used to sign out a resource. Default is :delete. 257 | config.sign_out_via = :delete 258 | 259 | # ==> OmniAuth 260 | # Add a new OmniAuth provider. Check the wiki for more information on setting 261 | # up on your models and hooks. 262 | # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' 263 | 264 | # ==> Warden configuration 265 | # If you want to use other strategies, that are not supported by Devise, or 266 | # change the failure app, you can configure them inside the config.warden block. 267 | # 268 | # config.warden do |manager| 269 | # manager.intercept_401 = false 270 | # manager.default_strategies(scope: :user).unshift :some_external_strategy 271 | # end 272 | 273 | # ==> Mountable engine configurations 274 | # When using Devise inside an engine, let's call it `MyEngine`, and this engine 275 | # is mountable, there are some extra configurations to be taken into account. 276 | # The following options are available, assuming the engine is mounted as: 277 | # 278 | # mount MyEngine, at: '/my_engine' 279 | # 280 | # The router that invoked `devise_for`, in the example above, would be: 281 | # config.router_name = :my_engine 282 | # 283 | # When using OmniAuth, Devise cannot automatically set OmniAuth path, 284 | # so you need to do it manually. For the users scope, it would be: 285 | # config.omniauth_path_prefix = '/my_engine/users/auth' 286 | 287 | # ==> Turbolinks configuration 288 | # If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly: 289 | # 290 | # ActiveSupport.on_load(:devise_failure_app) do 291 | # include Turbolinks::Controller 292 | # end 293 | 294 | # ==> Configuration for :registerable 295 | 296 | # When set to false, does not sign a user in automatically after their password is 297 | # changed. Defaults to true, so a user is signed in automatically after changing a password. 298 | # config.sign_in_after_change_password = true 299 | end 300 | -------------------------------------------------------------------------------- /config/initializers/devise_token_auth.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | DeviseTokenAuth.setup do |config| 4 | # By default the authorization headers will change after each request. The 5 | # client is responsible for keeping track of the changing tokens. Change 6 | # this to false to prevent the Authorization header from changing after 7 | # each request. 8 | # config.change_headers_on_each_request = true 9 | 10 | # By default, users will need to re-authenticate after 2 weeks. This setting 11 | # determines how long tokens will remain valid after they are issued. 12 | # config.token_lifespan = 2.weeks 13 | 14 | # Sets the max number of concurrent devices per user, which is 10 by default. 15 | # After this limit is reached, the oldest tokens will be removed. 16 | # config.max_number_of_devices = 10 17 | 18 | # Sometimes it's necessary to make several requests to the API at the same 19 | # time. In this case, each request in the batch will need to share the same 20 | # auth token. This setting determines how far apart the requests can be while 21 | # still using the same auth token. 22 | # config.batch_request_buffer_throttle = 5.seconds 23 | 24 | # This route will be the prefix for all oauth2 redirect callbacks. For 25 | # example, using the default '/omniauth', the github oauth2 provider will 26 | # redirect successful authentications to '/omniauth/github/callback' 27 | # config.omniauth_prefix = "/omniauth" 28 | 29 | # By default sending current password is not needed for the password update. 30 | # Uncomment to enforce current_password param to be checked before all 31 | # attribute updates. Set it to :password if you want it to be checked only if 32 | # password is updated. 33 | # config.check_current_password_before_update = :attributes 34 | 35 | # By default we will use callbacks for single omniauth. 36 | # It depends on fields like email, provider and uid. 37 | # config.default_callbacks = true 38 | 39 | # Makes it possible to change the headers names 40 | # config.headers_names = {:'access-token' => 'access-token', 41 | # :'client' => 'client', 42 | # :'expiry' => 'expiry', 43 | # :'uid' => 'uid', 44 | # :'token-type' => 'token-type' } 45 | 46 | # By default, only Bearer Token authentication is implemented out of the box. 47 | # If, however, you wish to integrate with legacy Devise authentication, you can 48 | # do so by enabling this flag. NOTE: This feature is highly experimental! 49 | # config.enable_standard_devise_support = false 50 | end 51 | -------------------------------------------------------------------------------- /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 += [:password] 5 | -------------------------------------------------------------------------------- /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/new_framework_defaults_6_0.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | # 3 | # This file contains migration options to ease your Rails 6.0 upgrade. 4 | # 5 | # Once upgraded flip defaults one by one to migrate to the new default. 6 | # 7 | # Read the Guide for Upgrading Ruby on Rails for more info on each option. 8 | 9 | # Don't force requests from old versions of IE to be UTF-8 encoded. 10 | # Rails.application.config.action_view.default_enforce_utf8 = false 11 | 12 | # Embed purpose and expiry metadata inside signed and encrypted 13 | # cookies for increased security. 14 | # 15 | # This option is not backwards compatible with earlier Rails versions. 16 | # It's best enabled when your entire app is migrated and stable on 6.0. 17 | # Rails.application.config.action_dispatch.use_cookies_with_metadata = true 18 | 19 | # Change the return value of `ActionDispatch::Response#content_type` to Content-Type header without modification. 20 | # Rails.application.config.action_dispatch.return_only_media_type_on_content_type = false 21 | 22 | # Return false instead of self when enqueuing is aborted from a callback. 23 | # Rails.application.config.active_job.return_false_on_aborted_enqueue = true 24 | 25 | # Send Active Storage analysis and purge jobs to dedicated queues. 26 | # Rails.application.config.active_storage.queues.analysis = :active_storage_analysis 27 | # Rails.application.config.active_storage.queues.purge = :active_storage_purge 28 | 29 | # When assigning to a collection of attachments declared via `has_many_attached`, replace existing 30 | # attachments instead of appending. Use #attach to add new attachments without replacing existing ones. 31 | # Rails.application.config.active_storage.replace_on_assign_to_many = true 32 | 33 | # Use ActionMailer::MailDeliveryJob for sending parameterized and normal mail. 34 | # 35 | # The default delivery jobs (ActionMailer::Parameterized::DeliveryJob, ActionMailer::DeliveryJob), 36 | # will be removed in Rails 6.1. This setting is not backwards compatible with earlier Rails versions. 37 | # If you send mail in the background, job workers need to have a copy of 38 | # MailDeliveryJob to ensure all delivery jobs are processed properly. 39 | # Make sure your entire app is migrated and stable on 6.0 before using this setting. 40 | # Rails.application.config.action_mailer.delivery_job = "ActionMailer::MailDeliveryJob" 41 | 42 | # Enable the same cache key to be reused when the object being cached of type 43 | # `ActiveRecord::Relation` changes by moving the volatile information (max updated at and count) 44 | # of the relation's cache key into the cache version to support recycling cache key. 45 | # Rails.application.config.active_record.collection_cache_versioning = true 46 | -------------------------------------------------------------------------------- /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/plataformatec/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 confirm 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 | # Files in the config/locales directory are used for internationalization 2 | # and are automatically loaded by Rails. If you want to use locales other 3 | # than English, add the necessary files in this directory. 4 | # 5 | # To use the locales, use `I18n.t`: 6 | # 7 | # I18n.t 'hello' 8 | # 9 | # In views, this is aliased to just `t`: 10 | # 11 | # <%= t('hello') %> 12 | # 13 | # To use a different locale, set it with `I18n.locale`: 14 | # 15 | # I18n.locale = :es 16 | # 17 | # This would use the information in config/locales/es.yml. 18 | # 19 | # The following keys must be escaped otherwise they will not be retrieved by 20 | # the default I18n backend: 21 | # 22 | # true, false, on, off, yes, no 23 | # 24 | # Instead, surround them with single quotes. 25 | # 26 | # en: 27 | # 'true': 'foo' 28 | # 29 | # To learn more, please read the Rails Internationalization guide 30 | # available at https://guides.rubyonrails.org/i18n.html. 31 | 32 | en: 33 | hello: "Hello world" 34 | -------------------------------------------------------------------------------- /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 `port` that Puma will listen on to receive requests; default is 3000. 12 | # 13 | port ENV.fetch("PORT") { 3000 } 14 | 15 | # Specifies the `environment` that Puma will run in. 16 | # 17 | environment ENV.fetch("RAILS_ENV") { "development" } 18 | 19 | # Specifies the `pidfile` that Puma will use. 20 | pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } 21 | 22 | # Specifies the number of `workers` to boot in clustered mode. 23 | # Workers are forked web server processes. If using threads and workers together 24 | # the concurrency of the application would be max `threads` * `workers`. 25 | # Workers do not work on JRuby or Windows (both of which do not support 26 | # processes). 27 | # 28 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 } 29 | 30 | # Use the `preload_app!` method when specifying a `workers` number. 31 | # This directive tells Puma to first boot the application and load code 32 | # before forking the application. This takes advantage of Copy On Write 33 | # process behavior so workers use less memory. 34 | # 35 | # preload_app! 36 | 37 | # Allow puma to be restarted by `rails restart` command. 38 | plugin :tmp_restart 39 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html 3 | 4 | format = { format: 'json' } 5 | 6 | resources :posts, defaults: format 7 | resources :users, param: :uuid, defaults: format, only: %w(show update) do 8 | member do 9 | post 'profile_image', to: 'users/profile_image#create' 10 | end 11 | end 12 | mount_devise_token_auth_for 'User', at: 'auth', controllers: { sessions: 'sessions' } 13 | # TODO: root url 14 | # root to: 'home#index' 15 | end 16 | -------------------------------------------------------------------------------- /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/20190415153210_devise_token_auth_create_users.rb: -------------------------------------------------------------------------------- 1 | class DeviseTokenAuthCreateUsers < ActiveRecord::Migration[5.2] 2 | def change 3 | 4 | create_table(:users) do |t| 5 | ## Required 6 | t.string :provider, :null => false, :default => "email" 7 | t.string :uid, :null => false, :default => "" 8 | 9 | ## Database authenticatable 10 | t.string :encrypted_password, :null => false, :default => "" 11 | 12 | ## Recoverable 13 | t.string :reset_password_token 14 | t.datetime :reset_password_sent_at 15 | t.boolean :allow_password_change, :default => false 16 | 17 | ## Rememberable 18 | t.datetime :remember_created_at 19 | 20 | ## Trackable 21 | t.integer :sign_in_count, :default => 0 22 | t.datetime :current_sign_in_at 23 | t.datetime :last_sign_in_at 24 | t.string :current_sign_in_ip 25 | t.string :last_sign_in_ip 26 | 27 | ## Confirmable 28 | t.string :confirmation_token 29 | t.datetime :confirmed_at 30 | t.datetime :confirmation_sent_at 31 | t.string :unconfirmed_email # Only if using reconfirmable 32 | 33 | ## Lockable 34 | t.integer :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts 35 | t.string :unlock_token # Only if unlock strategy is :email or :both 36 | t.datetime :locked_at 37 | 38 | ## User Info 39 | t.string :name 40 | t.string :nickname 41 | t.string :image 42 | t.string :email 43 | 44 | ## Tokens 45 | t.text :tokens 46 | 47 | t.timestamps 48 | end 49 | 50 | add_index :users, :email, unique: true 51 | add_index :users, [:uid, :provider], unique: true 52 | add_index :users, :reset_password_token, unique: true 53 | add_index :users, :confirmation_token, unique: true 54 | add_index :users, :unlock_token, unique: true 55 | end 56 | end 57 | -------------------------------------------------------------------------------- /db/migrate/20190424135040_create_posts.rb: -------------------------------------------------------------------------------- 1 | class CreatePosts < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :posts do |t| 4 | t.bigint :user_id 5 | t.string :title 6 | t.text :body 7 | t.integer :status 8 | 9 | t.timestamps 10 | end 11 | add_index :posts, :user_id 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /db/migrate/20190719152628_add_uuid_to_users.rb: -------------------------------------------------------------------------------- 1 | class AddUuidToUsers < ActiveRecord::Migration[5.2] 2 | def change 3 | add_column :users, :uuid, :string, after: :id 4 | add_index :users, :uuid, unique: true 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /db/migrate/20191206153351_add_foreign_key_constraint_to_active_storage_attachments_for_blob_id.active_storage.rb: -------------------------------------------------------------------------------- 1 | # This migration comes from active_storage (originally 20180723000244) 2 | class AddForeignKeyConstraintToActiveStorageAttachmentsForBlobId < ActiveRecord::Migration[6.0] 3 | def up 4 | return if foreign_key_exists?(:active_storage_attachments, column: :blob_id) 5 | 6 | if table_exists?(:active_storage_blobs) 7 | add_foreign_key :active_storage_attachments, :active_storage_blobs, column: :blob_id 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /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 `rails 6 | # db:schema:load`. When creating a new database, `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: 2019_12_06_153351) do 14 | 15 | create_table "posts", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC", force: :cascade do |t| 16 | t.bigint "user_id" 17 | t.string "title" 18 | t.text "body" 19 | t.integer "status" 20 | t.datetime "created_at", null: false 21 | t.datetime "updated_at", null: false 22 | t.index ["user_id"], name: "index_posts_on_user_id" 23 | end 24 | 25 | create_table "users", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC", force: :cascade do |t| 26 | t.string "uuid" 27 | t.string "provider", default: "email", null: false 28 | t.string "uid", default: "", null: false 29 | t.string "encrypted_password", default: "", null: false 30 | t.string "reset_password_token" 31 | t.datetime "reset_password_sent_at" 32 | t.boolean "allow_password_change", default: false 33 | t.datetime "remember_created_at" 34 | t.integer "sign_in_count", default: 0 35 | t.datetime "current_sign_in_at" 36 | t.datetime "last_sign_in_at" 37 | t.string "current_sign_in_ip" 38 | t.string "last_sign_in_ip" 39 | t.string "confirmation_token" 40 | t.datetime "confirmed_at" 41 | t.datetime "confirmation_sent_at" 42 | t.string "unconfirmed_email" 43 | t.integer "failed_attempts", default: 0, null: false 44 | t.string "unlock_token" 45 | t.datetime "locked_at" 46 | t.string "name" 47 | t.string "nickname" 48 | t.string "image" 49 | t.string "email" 50 | t.text "tokens" 51 | t.datetime "created_at", null: false 52 | t.datetime "updated_at", null: false 53 | t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true 54 | t.index ["email"], name: "index_users_on_email", unique: true 55 | t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true 56 | t.index ["uid", "provider"], name: "index_users_on_uid_and_provider", unique: true 57 | t.index ["unlock_token"], name: "index_users_on_unlock_token", unique: true 58 | t.index ["uuid"], name: "index_users_on_uuid", unique: true 59 | end 60 | 61 | end 62 | -------------------------------------------------------------------------------- /db/seeds.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # This file should contain all the record creation needed to seed the database with its default values. 4 | # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). 5 | # 6 | # Examples: 7 | # 8 | # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) 9 | # Character.create(name: 'Luke', movie: movies.first) 10 | 11 | # Demo user 12 | FactoryBot.create(:login_user) if User.all.count.zero? 13 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | rails_api: 4 | tty: true 5 | stdin_open: true 6 | build: 7 | context: . 8 | dockerfile: Dockerfile 9 | entrypoint: sh /app/docker/bin/wait_for_mysql.sh sh /app/docker/bin/rails_start.sh 10 | ports: 11 | - 3000:3000 12 | volumes: 13 | - .:/app:cached 14 | - bundle:/usr/local/bundle:cached 15 | - temp:/app/vendor 16 | - temp:/app/tmp 17 | - temp:/app/.git 18 | environment: 19 | - DB_USERNAME=root 20 | - DB_PASSWORD=root 21 | - DB_HOST=mysql 22 | - DOCKER_HOST=0.0.0.0 23 | depends_on: 24 | - mysql 25 | mysql: 26 | image: mysql:5.7 27 | ports: 28 | - 3306:3306 29 | volumes: 30 | - ./docker/mysql/conf.d:/etc/mysql/conf.d 31 | - mysql-data:/var/lib/mysql 32 | environment: 33 | MYSQL_ROOT_PASSWORD: root 34 | 35 | volumes: 36 | bundle: 37 | temp: 38 | mysql-data: 39 | -------------------------------------------------------------------------------- /docker/bin/rails_start.sh: -------------------------------------------------------------------------------- 1 | bundle install --path=vendor/bundle 2 | bundle exec rake db:create 3 | bundle exec rake db:migrate 4 | bundle exec rake db:seed 5 | [ -f /tmp/rails_api.pid ] && rm /tmp/rails_api.pid || echo "Not found" 6 | bundle exec rails s -P /tmp/rails_api.pid -b '0.0.0.0' 7 | -------------------------------------------------------------------------------- /docker/bin/wait_for_mysql.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # wait_for_mysql.sh 3 | 4 | set -e 5 | 6 | cmd="$@" 7 | host="$DB_HOST" 8 | user="$DB_USERNAME" 9 | export MYSQL_PWD="$DB_PASSWORD" 10 | 11 | until mysql -u$user -h$host -e 'SELECT 1' &> /dev/null; do 12 | >&2 echo "MySQL is unavailable - sleeping" 13 | sleep 1 14 | done 15 | 16 | >&2 echo "MySQL is up - executing command" 17 | 18 | exec $cmd 19 | -------------------------------------------------------------------------------- /docker/mysql/conf.d/mysql.cnf: -------------------------------------------------------------------------------- 1 | [mysqld] 2 | skip-host-cache 3 | skip-name-resolve 4 | 5 | character-set-server = utf8mb4 6 | collation-server = utf8mb4_general_ci 7 | init-connect = SET NAMES utf8mb4 8 | skip-character-set-client-handshake 9 | innodb_large_prefix = ON 10 | innodb_file_format = Barracuda 11 | 12 | [client] 13 | default-character-set = utf8mb4 14 | 15 | [mysqldump] 16 | default-character-set = utf8mb4 17 | 18 | [mysql] 19 | default-character-set = utf8mb4 20 | -------------------------------------------------------------------------------- /lib/tasks/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walkersumida/rails-api-for-front/9942074aad6853cedd32063d30ec3875c14fd242/lib/tasks/.keep -------------------------------------------------------------------------------- /log/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walkersumida/rails-api-for-front/9942074aad6853cedd32063d30ec3875c14fd242/log/.keep -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | -------------------------------------------------------------------------------- /spec/factories/posts.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :post do 3 | title { 'title' } 4 | body { 'body' } 5 | status { 1 } 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /spec/factories/sequences.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | sequence(:name) { |n| "Walker Sumida#{n}" } 3 | sequence(:email) { |n| "user#{n}@example.org" } 4 | sequence(:uuid) { |_n| SecureRandom.uuid } 5 | sequence(:access_token) { |_n| SecureRandom.uuid } 6 | end 7 | -------------------------------------------------------------------------------- /spec/factories/users.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | FactoryBot.define do 4 | factory :login_user, class: 'User' do 5 | uuid { SecureRandom.uuid } 6 | uid { generate(:uuid) } 7 | email { 'demo@xxx.com' } 8 | name { generate(:name) } 9 | password { 'demodemo' } 10 | confirmed_at { Time.now } 11 | confirmation_token { nil } 12 | 13 | factory :user do 14 | uid { generate(:uuid) } 15 | email { generate(:email) } 16 | name { generate(:name) } 17 | end 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /spec/fixtures/files/user_icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walkersumida/rails-api-for-front/9942074aad6853cedd32063d30ec3875c14fd242/spec/fixtures/files/user_icon.png -------------------------------------------------------------------------------- /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', __FILE__) 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 'carrierwave/test/matchers' 10 | 11 | # Requires supporting ruby files with custom matchers and macros, etc, in 12 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are 13 | # run as spec files by default. This means that files in spec/support that end 14 | # in _spec.rb will both be required and run as specs, causing the specs to be 15 | # run twice. It is recommended that you do not name files matching this glob to 16 | # end with _spec.rb. You can configure this pattern with the --pattern 17 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. 18 | # 19 | # The following line is provided for convenience purposes. It has the downside 20 | # of increasing the boot-up time by auto-requiring all files in the support 21 | # directory. Alternatively, in the individual `*_spec.rb` files, manually 22 | # require only the support files necessary. 23 | # 24 | Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f } 25 | 26 | # Checks for pending migrations and applies them before tests are run. 27 | # If you are not using ActiveRecord, you can remove these lines. 28 | begin 29 | ActiveRecord::Migration.maintain_test_schema! 30 | rescue ActiveRecord::PendingMigrationError => e 31 | puts e.to_s.strip 32 | exit 1 33 | end 34 | RSpec.configure do |config| 35 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 36 | config.fixture_path = "#{::Rails.root}/spec/fixtures" 37 | 38 | # If you're not using ActiveRecord, or you'd prefer not to run each of your 39 | # examples within a transaction, remove the following line or assign false 40 | # instead of true. 41 | config.use_transactional_fixtures = true 42 | 43 | # RSpec Rails can automatically mix in different behaviours to your tests 44 | # based on their file location, for example enabling you to call `get` and 45 | # `post` in specs under `spec/controllers`. 46 | # 47 | # You can disable this behaviour by removing the line below, and instead 48 | # explicitly tag your specs with their type, e.g.: 49 | # 50 | # RSpec.describe UsersController, :type => :controller do 51 | # # ... 52 | # end 53 | # 54 | # The different available types are documented in the features, such as in 55 | # https://relishapp.com/rspec/rspec-rails/docs 56 | config.infer_spec_type_from_file_location! 57 | 58 | # Filter lines from Rails gems in backtraces. 59 | config.filter_rails_from_backtrace! 60 | # arbitrary gems may also be filtered via: 61 | # config.filter_gems_from_backtrace("gem name") 62 | 63 | config.include ActiveSupport::Testing::TimeHelpers 64 | config.include FactoryBot::Syntax::Methods 65 | config.include RSpec::JsonMatcher 66 | config.include RSpec::RequestDescriber, type: :request 67 | config.include Requests::AuthHelpers::Includables, type: :request 68 | config.extend Requests::AuthHelpers::Extensions, type: :request 69 | 70 | config.before :each do 71 | freeze_time 72 | end 73 | config.after :each do 74 | travel_back 75 | end 76 | end 77 | -------------------------------------------------------------------------------- /spec/requests/posts/create_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'POST /posts', type: :request do 4 | let(:user) { create(:user) } 5 | let(:valid_attributes) do 6 | { 7 | title: 'title', 8 | body: 'body', 9 | } 10 | end 11 | let(:params) do 12 | { post: valid_attributes } 13 | end 14 | let(:post_obj) do 15 | Post.find(JSON.parse(response.body)['id']) 16 | end 17 | 18 | sign_in(:user) 19 | 20 | it 'get posts' do 21 | is_expected.to eq(201) 22 | 23 | expect(response.body).to be_json_as( 24 | { 25 | id: post_obj.id, 26 | user_id: post_obj.user_id, 27 | title: post_obj.title, 28 | body: post_obj.body, 29 | status: post_obj.status, 30 | created_at: post_obj.created_at, 31 | updated_at: post_obj.updated_at, 32 | } 33 | ) 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /spec/requests/posts/delete_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'DELETE /posts/:id', type: :request do 4 | let(:id) { post.id } 5 | let(:user) { create(:user) } 6 | let(:post) { create(:post, user_id: user.id) } 7 | 8 | sign_in(:user) 9 | 10 | it 'get posts' do 11 | is_expected.to eq(204) 12 | 13 | expect(Post.find_by(id: post.id)).to eq(nil) 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /spec/requests/posts/index_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'GET /posts', type: :request do 4 | let(:user) { create(:user) } 5 | let!(:post) { create(:post, user_id: user.id) } 6 | 7 | sign_in(:user) 8 | 9 | it 'get posts' do 10 | is_expected.to eq(200) 11 | 12 | expect(response.body).to be_json_as([ 13 | { 14 | id: post.id, 15 | user_id: post.user_id, 16 | title: post.title, 17 | body: post.body, 18 | status: post.status, 19 | created_at: post.created_at, 20 | updated_at: post.updated_at, 21 | }, 22 | ]) 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /spec/requests/posts/show_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'GET /posts/:id', type: :request do 4 | let(:id) { post.id } 5 | let(:user) { create(:user) } 6 | let(:post) { create(:post, user_id: user.id) } 7 | 8 | sign_in(:user) 9 | 10 | it 'get posts' do 11 | is_expected.to eq(200) 12 | 13 | expect(response.body).to be_json_as( 14 | { 15 | id: post.id, 16 | user_id: post.user_id, 17 | title: post.title, 18 | body: post.body, 19 | status: post.status, 20 | created_at: post.created_at, 21 | updated_at: post.updated_at, 22 | } 23 | ) 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /spec/requests/posts/update_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'PATCH /posts/:id', type: :request do 4 | let(:id) { post.id } 5 | let(:user) { create(:user) } 6 | let(:post) { create(:post, user_id: user.id, title: 'title') } 7 | let(:valid_attributes) do 8 | { 9 | title: updated_title, 10 | } 11 | end 12 | let(:params) do 13 | { post: valid_attributes } 14 | end 15 | let(:updated_title) { 'updated title' } 16 | 17 | sign_in(:user) 18 | 19 | it 'get posts' do 20 | is_expected.to eq(200) 21 | 22 | expect(response.body).to be_json_as( 23 | { 24 | id: post.id, 25 | user_id: post.user_id, 26 | title: updated_title, 27 | body: post.body, 28 | status: post.status, 29 | created_at: post.created_at, 30 | updated_at: post.updated_at, 31 | } 32 | ) 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /spec/requests/users/profile_image/create_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'POST /users/:uuid/profile_image', type: :request do 4 | let(:user) { create(:user) } 5 | let(:uuid) { 'me' } 6 | let(:file_name) { 'user_icon.png' } 7 | let(:params) do 8 | { image: fixture_file_upload(file_fixture(file_name)) } 9 | end 10 | 11 | sign_in(:user) 12 | 13 | it 'upload profile image' do 14 | is_expected.to eq(200) 15 | 16 | expect(response.body).to be_json_as( 17 | { 18 | image: { url: "/uploads/user/image/#{user.uuid}/#{file_name}" }, 19 | } 20 | ) 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /spec/requests/users/show_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'GET /users/:uuid', type: :request do 4 | let(:user) { create(:user) } 5 | 6 | sign_in(:user) 7 | 8 | context ':uuid param is uuid' do 9 | let(:uuid) { user.uuid } 10 | 11 | it 'get user' do 12 | is_expected.to eq(200) 13 | 14 | expect(response.body).to be_json_as( 15 | { 16 | id: user.uuid, 17 | email: user.email, 18 | name: user.name, 19 | nickname: user.nickname, 20 | image: { url: nil }, 21 | } 22 | ) 23 | end 24 | end 25 | 26 | context ':uuid param is `me`' do 27 | let(:uuid) { 'me' } 28 | 29 | it 'get user' do 30 | is_expected.to eq(200) 31 | 32 | expect(response.body).to be_json_as( 33 | { 34 | id: user.uuid, 35 | email: user.email, 36 | name: user.name, 37 | nickname: user.nickname, 38 | image: { url: nil }, 39 | } 40 | ) 41 | end 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /spec/requests/users/success_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'POST /auth/sign_in', type: :request do 4 | let(:email) { user.email } 5 | let(:password) { 'password' } 6 | let(:user) { create(:user, password: password, nickname: 'nickname') } 7 | let(:valid_attributes) do 8 | { 9 | email: email, 10 | password: password, 11 | } 12 | end 13 | let(:params) do 14 | valid_attributes 15 | end 16 | 17 | it 'get user' do 18 | is_expected.to eq(200) 19 | 20 | expect(response.body).to be_json_as( 21 | { 22 | id: user.uuid, 23 | email: user.email, 24 | name: user.name, 25 | nickname: user.nickname, 26 | image: { url: nil }, 27 | } 28 | ) 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /spec/requests/users/update_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'PATCH /users/:uuid', type: :request do 4 | let(:uuid) { user.uuid } 5 | let(:user) { create(:user, nickname: 'nickname') } 6 | let(:valid_attributes) do 7 | { 8 | nickname: updated_nickname, 9 | } 10 | end 11 | let(:params) do 12 | { user: valid_attributes } 13 | end 14 | let(:updated_nickname) { 'updated nickname' } 15 | 16 | sign_in(:user) 17 | 18 | it 'get user' do 19 | is_expected.to eq(200) 20 | 21 | expect(response.body).to be_json_as( 22 | { 23 | id: user.uuid, 24 | email: user.email, 25 | name: user.name, 26 | nickname: updated_nickname, 27 | image: { url: nil }, 28 | } 29 | ) 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # This file was generated by the `rails generate rspec:install` command. Conventionally, all 2 | # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. 3 | # The generated `.rspec` file contains `--require spec_helper` which will cause 4 | # this file to always be loaded, without a need to explicitly require it in any 5 | # files. 6 | # 7 | # Given that it is always loaded, you are encouraged to keep this file as 8 | # light-weight as possible. Requiring heavyweight dependencies from this file 9 | # will add to the boot time of your test suite on EVERY test run, even for an 10 | # individual file that may not need all of that loaded. Instead, consider making 11 | # a separate helper file that requires the additional dependencies and performs 12 | # the additional setup, and require it from the spec files that actually need 13 | # it. 14 | # 15 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration 16 | RSpec.configure do |config| 17 | # rspec-expectations config goes here. You can use an alternate 18 | # assertion/expectation library such as wrong or the stdlib/minitest 19 | # assertions if you prefer. 20 | config.expect_with :rspec do |expectations| 21 | # This option will default to `true` in RSpec 4. It makes the `description` 22 | # and `failure_message` of custom matchers include text for helper methods 23 | # defined using `chain`, e.g.: 24 | # be_bigger_than(2).and_smaller_than(4).description 25 | # # => "be bigger than 2 and smaller than 4" 26 | # ...rather than: 27 | # # => "be bigger than 2" 28 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true 29 | end 30 | 31 | # rspec-mocks config goes here. You can use an alternate test double 32 | # library (such as bogus or mocha) by changing the `mock_with` option here. 33 | config.mock_with :rspec do |mocks| 34 | # Prevents you from mocking or stubbing a method that does not exist on 35 | # a real object. This is generally recommended, and will default to 36 | # `true` in RSpec 4. 37 | mocks.verify_partial_doubles = true 38 | end 39 | 40 | # This option will default to `:apply_to_host_groups` in RSpec 4 (and will 41 | # have no way to turn it off -- the option exists only for backwards 42 | # compatibility in RSpec 3). It causes shared context metadata to be 43 | # inherited by the metadata hash of host groups and examples, rather than 44 | # triggering implicit auto-inclusion in groups with matching metadata. 45 | config.shared_context_metadata_behavior = :apply_to_host_groups 46 | 47 | # The settings below are suggested to provide a good initial experience 48 | # with RSpec, but feel free to customize to your heart's content. 49 | =begin 50 | # This allows you to limit a spec run to individual examples or groups 51 | # you care about by tagging them with `:focus` metadata. When nothing 52 | # is tagged with `:focus`, all examples get run. RSpec also provides 53 | # aliases for `it`, `describe`, and `context` that include `:focus` 54 | # metadata: `fit`, `fdescribe` and `fcontext`, respectively. 55 | config.filter_run_when_matching :focus 56 | 57 | # Allows RSpec to persist some state between runs in order to support 58 | # the `--only-failures` and `--next-failure` CLI options. We recommend 59 | # you configure your source control system to ignore this file. 60 | config.example_status_persistence_file_path = "spec/examples.txt" 61 | 62 | # Limits the available syntax to the non-monkey patched syntax that is 63 | # recommended. For more details, see: 64 | # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ 65 | # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ 66 | # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode 67 | config.disable_monkey_patching! 68 | 69 | # Many RSpec users commonly either run the entire suite or an individual 70 | # file, and it's useful to allow more verbose output when running an 71 | # individual spec file. 72 | if config.files_to_run.one? 73 | # Use the documentation formatter for detailed output, 74 | # unless a formatter has already been configured 75 | # (e.g. via a command-line flag). 76 | config.default_formatter = "doc" 77 | end 78 | 79 | # Print the 10 slowest examples and example groups at the 80 | # end of the spec run, to help surface which specs are running 81 | # particularly slow. 82 | config.profile_examples = 10 83 | 84 | # Run specs in random order to surface order dependencies. If you find an 85 | # order dependency and want to debug it, you can fix the order by providing 86 | # the seed, which is printed after each run. 87 | # --seed 1234 88 | config.order = :random 89 | 90 | # Seed global randomization in this process using the `--seed` CLI option. 91 | # Setting this allows you to use `--seed` to deterministically reproduce 92 | # test failures related to randomization by passing the same `--seed` value 93 | # as the one that triggered the failure. 94 | Kernel.srand config.seed 95 | =end 96 | end 97 | -------------------------------------------------------------------------------- /spec/support/requests/auth_helpers.rb: -------------------------------------------------------------------------------- 1 | # https://github.com/lynndylanhurley/devise_token_auth/wiki/Testing-(with-Rspec) 2 | module Requests 3 | module AuthHelpers 4 | module Extensions 5 | def sign_in(user) 6 | let(:auth_helpers_auth_token) do 7 | public_send(user).create_new_auth_token 8 | end 9 | end 10 | end 11 | 12 | module Includables 13 | HTTP_HELPERS_TO_OVERRIDE = 14 | [:get, :post, :patch, :put, :delete].freeze 15 | # Override helpers for Rails 5.0 16 | # see http://api.rubyonrails.org/v5.0/classes/ActionDispatch/Integration/RequestHelpers.html 17 | HTTP_HELPERS_TO_OVERRIDE.each do |helper| 18 | define_method(helper) do |path, **args| 19 | add_auth_headers(args) 20 | args == {} ? super(path) : super(path, **args) 21 | end 22 | end 23 | 24 | private 25 | 26 | def add_auth_headers(args) 27 | return unless defined? auth_helpers_auth_token 28 | args[:headers] ||= {} 29 | args[:headers].merge!(auth_helpers_auth_token) 30 | end 31 | end 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /storage/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walkersumida/rails-api-for-front/9942074aad6853cedd32063d30ec3875c14fd242/storage/.keep -------------------------------------------------------------------------------- /tmp/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walkersumida/rails-api-for-front/9942074aad6853cedd32063d30ec3875c14fd242/tmp/.keep -------------------------------------------------------------------------------- /vendor/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walkersumida/rails-api-for-front/9942074aad6853cedd32063d30ec3875c14fd242/vendor/.keep --------------------------------------------------------------------------------