├── .gitignore ├── .rbenv-gemsets ├── .rspec ├── .ruby-version ├── Gemfile ├── Gemfile.lock ├── README.md ├── Rakefile ├── app ├── channels │ └── application_cable │ │ ├── channel.rb │ │ └── connection.rb ├── controllers │ ├── access_tokens_controller.rb │ ├── application_controller.rb │ ├── articles_controller.rb │ ├── comments_controller.rb │ ├── concerns │ │ └── .keep │ └── registrations_controller.rb ├── jobs │ └── application_job.rb ├── lib │ ├── user_authenticator.rb │ └── user_authenticator │ │ ├── oauth.rb │ │ └── standard.rb ├── mailers │ └── application_mailer.rb ├── models │ ├── access_token.rb │ ├── application_record.rb │ ├── article.rb │ ├── comment.rb │ ├── concerns │ │ └── .keep │ └── user.rb ├── serializers │ ├── access_token_serializer.rb │ ├── article_serializer.rb │ ├── comment_serializer.rb │ ├── error_serializer.rb │ └── user_serializer.rb └── views │ └── layouts │ ├── mailer.html.erb │ └── mailer.text.erb ├── bin ├── bundle ├── rails ├── rake ├── setup ├── spring └── 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 │ ├── active_model_serializers.rb │ ├── application_controller_renderer.rb │ ├── backtrace_silencers.rb │ ├── cors.rb │ ├── filter_parameter_logging.rb │ ├── inflections.rb │ ├── mime_types.rb │ └── wrap_parameters.rb ├── locales │ └── en.yml ├── puma.rb ├── routes.rb ├── spring.rb └── storage.yml ├── db ├── migrate │ ├── 20180425083447_create_articles.rb │ ├── 20180503212840_create_users.rb │ ├── 20180506105306_create_access_tokens.rb │ ├── 20180518211629_add_user_to_articles.rb │ ├── 20180519145812_create_comments.rb │ └── 20180807150152_add_encrypted_password_to_users.rb ├── schema.rb └── seeds.rb ├── lib └── tasks │ └── .keep ├── log └── .keep ├── public └── robots.txt ├── spec ├── controllers │ ├── access_tokens_controller_spec.rb │ ├── articles_controller_spec.rb │ ├── comments_controller_spec.rb │ └── registrations_controller_spec.rb ├── factories │ ├── access_tokens.rb │ ├── articles.rb │ ├── comments.rb │ └── users.rb ├── lib │ ├── user_authenticator │ │ ├── oauth_spec.rb │ │ └── standard_spec.rb │ └── user_authenticator_spec.rb ├── models │ ├── access_token_spec.rb │ ├── article_spec.rb │ ├── comment_spec.rb │ └── user_spec.rb ├── rails_helper.rb ├── routing │ ├── access_tokens_spec.rb │ ├── articles_spec.rb │ ├── comments_routing_spec.rb │ └── registrations_spec.rb ├── spec_helper.rb └── support │ ├── json_api_helpers.rb │ └── shared │ └── json_errors.rb ├── tmp └── .keep └── vendor └── .keep /.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 the default SQLite database. 11 | /db/*.sqlite3 12 | /db/*.sqlite3-journal 13 | 14 | # Ignore all logfiles and tempfiles. 15 | /log/* 16 | /tmp/* 17 | !/log/.keep 18 | !/tmp/.keep 19 | 20 | # Ignore uploaded files in development 21 | /storage/* 22 | 23 | .byebug_history 24 | 25 | # Ignore master key for decrypting credentials and more. 26 | /config/master.key 27 | -------------------------------------------------------------------------------- /.rbenv-gemsets: -------------------------------------------------------------------------------- 1 | rails-api 2 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --require spec_helper 2 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | 2.5.1 -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | git_source(:github) { |repo| "https://github.com/#{repo}.git" } 3 | 4 | ruby '2.5.1' 5 | 6 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' 7 | gem 'rails', '~> 5.2.0' 8 | # Use Puma as the app server 9 | gem 'puma', '~> 3.11' 10 | gem 'rspec-rails' 11 | gem 'factory_bot_rails' 12 | gem 'active_model_serializers' 13 | gem 'kaminari' 14 | gem "octokit", "~> 4.0" 15 | gem 'bcrypt' 16 | # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder 17 | # gem 'jbuilder', '~> 2.5' 18 | # Use Redis adapter to run Action Cable in production 19 | # gem 'redis', '~> 4.0' 20 | # Use ActiveModel has_secure_password 21 | # gem 'bcrypt', '~> 3.1.7' 22 | 23 | # Use ActiveStorage variant 24 | # gem 'mini_magick', '~> 4.8' 25 | 26 | # Use Capistrano for deployment 27 | # gem 'capistrano-rails', group: :development 28 | 29 | # Reduces boot times through caching; required in config/boot.rb 30 | gem 'bootsnap', '>= 1.1.0', require: false 31 | 32 | # Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible 33 | # gem 'rack-cors' 34 | 35 | group :production do 36 | gem 'pg' #postgres db required by heroku by default 37 | end 38 | 39 | group :development, :test do 40 | # Call 'byebug' anywhere in the code to stop execution and get a debugger console 41 | gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] 42 | # Use sqlite3 as the database for Active Record 43 | gem 'sqlite3' 44 | end 45 | 46 | group :development do 47 | gem 'listen', '>= 3.0.5', '< 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 | 54 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem 55 | gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] 56 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | actioncable (5.2.1) 5 | actionpack (= 5.2.1) 6 | nio4r (~> 2.0) 7 | websocket-driver (>= 0.6.1) 8 | actionmailer (5.2.1) 9 | actionpack (= 5.2.1) 10 | actionview (= 5.2.1) 11 | activejob (= 5.2.1) 12 | mail (~> 2.5, >= 2.5.4) 13 | rails-dom-testing (~> 2.0) 14 | actionpack (5.2.1) 15 | actionview (= 5.2.1) 16 | activesupport (= 5.2.1) 17 | rack (~> 2.0) 18 | rack-test (>= 0.6.3) 19 | rails-dom-testing (~> 2.0) 20 | rails-html-sanitizer (~> 1.0, >= 1.0.2) 21 | actionview (5.2.1) 22 | activesupport (= 5.2.1) 23 | builder (~> 3.1) 24 | erubi (~> 1.4) 25 | rails-dom-testing (~> 2.0) 26 | rails-html-sanitizer (~> 1.0, >= 1.0.3) 27 | active_model_serializers (0.10.7) 28 | actionpack (>= 4.1, < 6) 29 | activemodel (>= 4.1, < 6) 30 | case_transform (>= 0.2) 31 | jsonapi-renderer (>= 0.1.1.beta1, < 0.3) 32 | activejob (5.2.1) 33 | activesupport (= 5.2.1) 34 | globalid (>= 0.3.6) 35 | activemodel (5.2.1) 36 | activesupport (= 5.2.1) 37 | activerecord (5.2.1) 38 | activemodel (= 5.2.1) 39 | activesupport (= 5.2.1) 40 | arel (>= 9.0) 41 | activestorage (5.2.1) 42 | actionpack (= 5.2.1) 43 | activerecord (= 5.2.1) 44 | marcel (~> 0.3.1) 45 | activesupport (5.2.1) 46 | concurrent-ruby (~> 1.0, >= 1.0.2) 47 | i18n (>= 0.7, < 2) 48 | minitest (~> 5.1) 49 | tzinfo (~> 1.1) 50 | addressable (2.5.2) 51 | public_suffix (>= 2.0.2, < 4.0) 52 | arel (9.0.0) 53 | bcrypt (3.1.12) 54 | bootsnap (1.3.2) 55 | msgpack (~> 1.0) 56 | builder (3.2.3) 57 | byebug (10.0.2) 58 | case_transform (0.2) 59 | activesupport 60 | concurrent-ruby (1.0.5) 61 | crass (1.0.4) 62 | diff-lcs (1.3) 63 | erubi (1.7.1) 64 | factory_bot (4.11.1) 65 | activesupport (>= 3.0.0) 66 | factory_bot_rails (4.11.1) 67 | factory_bot (~> 4.11.1) 68 | railties (>= 3.0.0) 69 | faraday (0.15.3) 70 | multipart-post (>= 1.2, < 3) 71 | ffi (1.9.25) 72 | globalid (0.4.1) 73 | activesupport (>= 4.2.0) 74 | i18n (1.1.1) 75 | concurrent-ruby (~> 1.0) 76 | jsonapi-renderer (0.2.0) 77 | kaminari (1.1.1) 78 | activesupport (>= 4.1.0) 79 | kaminari-actionview (= 1.1.1) 80 | kaminari-activerecord (= 1.1.1) 81 | kaminari-core (= 1.1.1) 82 | kaminari-actionview (1.1.1) 83 | actionview 84 | kaminari-core (= 1.1.1) 85 | kaminari-activerecord (1.1.1) 86 | activerecord 87 | kaminari-core (= 1.1.1) 88 | kaminari-core (1.1.1) 89 | listen (3.1.5) 90 | rb-fsevent (~> 0.9, >= 0.9.4) 91 | rb-inotify (~> 0.9, >= 0.9.7) 92 | ruby_dep (~> 1.2) 93 | loofah (2.2.2) 94 | crass (~> 1.0.2) 95 | nokogiri (>= 1.5.9) 96 | mail (2.7.1) 97 | mini_mime (>= 0.1.1) 98 | marcel (0.3.3) 99 | mimemagic (~> 0.3.2) 100 | method_source (0.9.0) 101 | mimemagic (0.3.2) 102 | mini_mime (1.0.1) 103 | mini_portile2 (2.3.0) 104 | minitest (5.11.3) 105 | msgpack (1.2.4) 106 | multipart-post (2.0.0) 107 | nio4r (2.3.1) 108 | nokogiri (1.8.5) 109 | mini_portile2 (~> 2.3.0) 110 | octokit (4.13.0) 111 | sawyer (~> 0.8.0, >= 0.5.3) 112 | pg (1.1.3) 113 | public_suffix (3.0.3) 114 | puma (3.12.0) 115 | rack (2.0.5) 116 | rack-test (1.1.0) 117 | rack (>= 1.0, < 3) 118 | rails (5.2.1) 119 | actioncable (= 5.2.1) 120 | actionmailer (= 5.2.1) 121 | actionpack (= 5.2.1) 122 | actionview (= 5.2.1) 123 | activejob (= 5.2.1) 124 | activemodel (= 5.2.1) 125 | activerecord (= 5.2.1) 126 | activestorage (= 5.2.1) 127 | activesupport (= 5.2.1) 128 | bundler (>= 1.3.0) 129 | railties (= 5.2.1) 130 | sprockets-rails (>= 2.0.0) 131 | rails-dom-testing (2.0.3) 132 | activesupport (>= 4.2.0) 133 | nokogiri (>= 1.6) 134 | rails-html-sanitizer (1.0.4) 135 | loofah (~> 2.2, >= 2.2.2) 136 | railties (5.2.1) 137 | actionpack (= 5.2.1) 138 | activesupport (= 5.2.1) 139 | method_source 140 | rake (>= 0.8.7) 141 | thor (>= 0.19.0, < 2.0) 142 | rake (12.3.1) 143 | rb-fsevent (0.10.3) 144 | rb-inotify (0.9.10) 145 | ffi (>= 0.5.0, < 2) 146 | rspec-core (3.8.0) 147 | rspec-support (~> 3.8.0) 148 | rspec-expectations (3.8.2) 149 | diff-lcs (>= 1.2.0, < 2.0) 150 | rspec-support (~> 3.8.0) 151 | rspec-mocks (3.8.0) 152 | diff-lcs (>= 1.2.0, < 2.0) 153 | rspec-support (~> 3.8.0) 154 | rspec-rails (3.8.0) 155 | actionpack (>= 3.0) 156 | activesupport (>= 3.0) 157 | railties (>= 3.0) 158 | rspec-core (~> 3.8.0) 159 | rspec-expectations (~> 3.8.0) 160 | rspec-mocks (~> 3.8.0) 161 | rspec-support (~> 3.8.0) 162 | rspec-support (3.8.0) 163 | ruby_dep (1.5.0) 164 | sawyer (0.8.1) 165 | addressable (>= 2.3.5, < 2.6) 166 | faraday (~> 0.8, < 1.0) 167 | spring (2.0.2) 168 | activesupport (>= 4.2) 169 | spring-watcher-listen (2.0.1) 170 | listen (>= 2.7, < 4.0) 171 | spring (>= 1.2, < 3.0) 172 | sprockets (3.7.2) 173 | concurrent-ruby (~> 1.0) 174 | rack (> 1, < 3) 175 | sprockets-rails (3.2.1) 176 | actionpack (>= 4.0) 177 | activesupport (>= 4.0) 178 | sprockets (>= 3.0.0) 179 | sqlite3 (1.3.13) 180 | thor (0.20.0) 181 | thread_safe (0.3.6) 182 | tzinfo (1.2.5) 183 | thread_safe (~> 0.1) 184 | websocket-driver (0.7.0) 185 | websocket-extensions (>= 0.1.0) 186 | websocket-extensions (0.1.3) 187 | 188 | PLATFORMS 189 | ruby 190 | 191 | DEPENDENCIES 192 | active_model_serializers 193 | bcrypt 194 | bootsnap (>= 1.1.0) 195 | byebug 196 | factory_bot_rails 197 | kaminari 198 | listen (>= 3.0.5, < 3.2) 199 | octokit (~> 4.0) 200 | pg 201 | puma (~> 3.11) 202 | rails (~> 5.2.0) 203 | rspec-rails 204 | spring 205 | spring-watcher-listen (~> 2.0.0) 206 | sqlite3 207 | tzinfo-data 208 | 209 | RUBY VERSION 210 | ruby 2.5.1p57 211 | 212 | BUNDLED WITH 213 | 1.16.6 214 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Overview 2 | 3 | This is a repository for a project described in details in the video course: [Ruby on Rails REST API: The Complete Guide](https://www.udemy.com/ruby-on-rails-api-the-complete-guide/?couponCode=GITHUBREP). 4 | 5 | It's a REST API application followed by https://jsonapi.org standard for API communication. 6 | 7 | ## Features 8 | 9 | 1. Listing recent Articles 10 | 2. Previewing the article's details 11 | 3. Logging in using login/password flow 12 | 4. Registering user using login/password flow 13 | 5. OAUTH integration with Github 14 | 4. Managing own articles (Create/Update/Destroy) 15 | 5. Creating comments to articles 16 | 6. Token-based authorization 17 | 7. Access management check. 18 | 8. TDD implementation. 19 | 20 | ### Useful resources 21 | 22 | - [Driggl's blog about Modern Web Development](https://driggl.com/blog) 23 | - [Modern Web Developers Community Supporting Group](https://facebook.com/groups/driggl) 24 | -------------------------------------------------------------------------------- /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/access_tokens_controller.rb: -------------------------------------------------------------------------------- 1 | class AccessTokensController < ApplicationController 2 | skip_before_action :authorize!, only: :create 3 | 4 | def create 5 | authenticator = UserAuthenticator.new(authentication_params) 6 | authenticator.perform 7 | 8 | render json: authenticator.access_token, status: :created 9 | end 10 | 11 | def destroy 12 | current_user.access_token.destroy 13 | end 14 | 15 | private 16 | 17 | def authentication_params 18 | (standard_auth_params || params.permit(:code)).to_h.symbolize_keys 19 | end 20 | 21 | def standard_auth_params 22 | params.dig(:data, :attributes)&.permit(:login, :password) 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::API 2 | class AuthorizationError < StandardError; end 3 | 4 | rescue_from UserAuthenticator::Oauth::AuthenticationError, with: :authentication_oauth_error 5 | rescue_from UserAuthenticator::Standard::AuthenticationError, with: :authentication_standard_error 6 | rescue_from AuthorizationError, with: :authorization_error 7 | 8 | before_action :authorize! 9 | 10 | private 11 | 12 | def current_page 13 | return 1 unless params[:page] 14 | return params[:page] if params[:page].is_a?(String) 15 | params.dig(:page, :number) if params[:page].is_a?(Hash) 16 | end 17 | 18 | def per_page 19 | return unless params[:page] 20 | return params[:per_page] if params[:per_page].is_a?(String) 21 | params.dig(:page, :size) if params[:page].is_a?(Hash) 22 | end 23 | 24 | 25 | def authorize! 26 | raise AuthorizationError unless current_user 27 | end 28 | 29 | def access_token 30 | provided_token = request.authorization&.gsub(/\ABearer\s/, '') 31 | @access_token = AccessToken.find_by(token: provided_token) 32 | end 33 | 34 | def current_user 35 | @current_user = access_token&.user 36 | end 37 | 38 | def authentication_oauth_error 39 | error = { 40 | "status" => "401", 41 | "source" => { "pointer" => "/code" }, 42 | "title" => "Authentication code is invalid", 43 | "detail" => "You must provide valid code in order to exchange it for token." 44 | } 45 | render json: { "errors": [ error ] }, status: 401 46 | end 47 | 48 | def authentication_standard_error 49 | error = { 50 | "status" => "401", 51 | "source" => { "pointer" => "/data/attributes/password" }, 52 | "title" => "Invalid login or password", 53 | "detail" => "You must provide valid credentials in order to exchange them for token." 54 | } 55 | render json: { "errors": [ error ] }, status: 401 56 | end 57 | 58 | def authorization_error 59 | error = { 60 | "status" => "403", 61 | "source" => { "pointer" => "/headers/authorization" }, 62 | "title" => "Not authorized", 63 | "detail" => "You have no right to access this resource." 64 | } 65 | render json: { "errors": [ error ] }, status: 403 66 | end 67 | end 68 | -------------------------------------------------------------------------------- /app/controllers/articles_controller.rb: -------------------------------------------------------------------------------- 1 | class ArticlesController < ApplicationController 2 | skip_before_action :authorize!, only: [:index, :show] 3 | 4 | def index 5 | articles = Article.recent. 6 | page(current_page). 7 | per(per_page) 8 | render json: articles 9 | end 10 | 11 | def show 12 | render json: Article.find(params[:id]) 13 | end 14 | 15 | def create 16 | article = current_user.articles.build(article_params) 17 | article.save! 18 | render json: article, status: :created 19 | rescue 20 | render json: article, adapter: :json_api, 21 | serializer: ErrorSerializer, 22 | status: :unprocessable_entity 23 | end 24 | 25 | def update 26 | article = current_user.articles.find(params[:id]) 27 | article.update_attributes!(article_params) 28 | render json: article, status: :ok 29 | rescue ActiveRecord::RecordNotFound 30 | authorization_error 31 | rescue 32 | render json: article, adapter: :json_api, 33 | serializer: ErrorSerializer, 34 | status: :unprocessable_entity 35 | end 36 | 37 | def destroy 38 | article = current_user.articles.find(params[:id]) 39 | article.destroy 40 | head :no_content 41 | rescue 42 | authorization_error 43 | end 44 | 45 | private 46 | 47 | def article_params 48 | params.require(:data).require(:attributes). 49 | permit(:title, :content, :slug) || 50 | ActionController::Parameters.new 51 | end 52 | end 53 | -------------------------------------------------------------------------------- /app/controllers/comments_controller.rb: -------------------------------------------------------------------------------- 1 | class CommentsController < ApplicationController 2 | skip_before_action :authorize!, only: [:index] 3 | before_action :load_article 4 | 5 | def index 6 | comments = @article.comments. 7 | page(current_page). 8 | per(per_page) 9 | render json: comments 10 | end 11 | 12 | def create 13 | @comment = @article.comments.build( 14 | comment_params.merge(user: current_user) 15 | ) 16 | 17 | @comment.save! 18 | render json: @comment, status: :created, location: @article 19 | rescue 20 | render json: @comment, adapter: :json_api, 21 | serializer: ErrorSerializer, 22 | status: :unprocessable_entity 23 | end 24 | 25 | private 26 | 27 | def load_article 28 | @article = Article.find(params[:article_id]) 29 | end 30 | 31 | def comment_params 32 | params.require(:data).require(:attributes). 33 | permit(:content) || 34 | ActionController::Parameters.new 35 | end 36 | end 37 | -------------------------------------------------------------------------------- /app/controllers/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/driggl/rails-api-complete-guide/df79b4536c3a54cd9840353d693991df65eb2b85/app/controllers/concerns/.keep -------------------------------------------------------------------------------- /app/controllers/registrations_controller.rb: -------------------------------------------------------------------------------- 1 | class RegistrationsController < ApplicationController 2 | skip_before_action :authorize!, only: :create 3 | 4 | def create 5 | user = User.new(registration_params.merge(provider: 'standard')) 6 | user.save! 7 | render json: user, status: :created 8 | rescue ActiveRecord::RecordInvalid 9 | render json: user, adapter: :json_api, 10 | serializer: ErrorSerializer, 11 | status: :unprocessable_entity 12 | end 13 | 14 | private 15 | 16 | def registration_params 17 | params.require(:data).require(:attributes). 18 | permit(:login, :password) || 19 | ActionController::Parameters.new 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /app/jobs/application_job.rb: -------------------------------------------------------------------------------- 1 | class ApplicationJob < ActiveJob::Base 2 | end 3 | -------------------------------------------------------------------------------- /app/lib/user_authenticator.rb: -------------------------------------------------------------------------------- 1 | class UserAuthenticator 2 | attr_reader :authenticator, :access_token 3 | 4 | def initialize(code: nil, login: nil, password: nil) 5 | @authenticator = if code.present? 6 | Oauth.new(code) 7 | else 8 | Standard.new(login, password) 9 | end 10 | end 11 | 12 | def perform 13 | authenticator.perform 14 | 15 | set_access_token 16 | end 17 | 18 | def user 19 | authenticator.user 20 | end 21 | 22 | private 23 | 24 | def set_access_token 25 | @access_token = if user.access_token.present? 26 | user.access_token 27 | else 28 | user.create_access_token 29 | end 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /app/lib/user_authenticator/oauth.rb: -------------------------------------------------------------------------------- 1 | class UserAuthenticator::Oauth < UserAuthenticator 2 | class AuthenticationError < StandardError; end 3 | 4 | attr_reader :user 5 | 6 | def initialize(code) 7 | @code = code 8 | end 9 | 10 | def perform 11 | raise AuthenticationError if code.blank? 12 | raise AuthenticationError if token.try(:error).present? 13 | 14 | prepare_user 15 | end 16 | 17 | private 18 | 19 | def client 20 | @client ||= Octokit::Client.new( 21 | client_id: ENV['GITHUB_CLIENT_ID'], 22 | client_secret: ENV['GITHUB_CLIENT_SECRET'] 23 | ) 24 | end 25 | 26 | def token 27 | @token ||= client.exchange_code_for_token(code) 28 | rescue Octokit::NotFound 29 | raise AuthenticationError 30 | end 31 | 32 | def user_data 33 | @user_data ||= Octokit::Client.new( 34 | access_token: token 35 | ).user.to_h.slice(:login, :avatar_url, :url, :name) 36 | end 37 | 38 | def prepare_user 39 | @user = if User.exists?(login: user_data[:login]) 40 | User.find_by(login: user_data[:login]) 41 | else 42 | User.create(user_data.merge(provider: 'github')) 43 | end 44 | end 45 | 46 | attr_reader :code 47 | end 48 | 49 | -------------------------------------------------------------------------------- /app/lib/user_authenticator/standard.rb: -------------------------------------------------------------------------------- 1 | class UserAuthenticator::Standard < UserAuthenticator 2 | class AuthenticationError < StandardError; end 3 | 4 | attr_reader :user 5 | 6 | def initialize(login, password) 7 | @login = login 8 | @password = password 9 | end 10 | 11 | def perform 12 | raise AuthenticationError if (login.blank? || password.blank?) 13 | raise AuthenticationError unless User.exists?(login: login) 14 | 15 | user = User.find_by(login: login) 16 | 17 | raise AuthenticationError unless user.password == password 18 | 19 | @user = user 20 | end 21 | 22 | private 23 | 24 | attr_reader :login, :password 25 | end 26 | -------------------------------------------------------------------------------- /app/mailers/application_mailer.rb: -------------------------------------------------------------------------------- 1 | class ApplicationMailer < ActionMailer::Base 2 | default from: 'from@example.com' 3 | layout 'mailer' 4 | end 5 | -------------------------------------------------------------------------------- /app/models/access_token.rb: -------------------------------------------------------------------------------- 1 | class AccessToken < ApplicationRecord 2 | belongs_to :user 3 | after_initialize :generate_token 4 | 5 | validates :token, presence: true, uniqueness: true 6 | 7 | private 8 | 9 | def generate_token 10 | loop do 11 | break if token.present? && !AccessToken.where.not(id: id).exists?(token: token) 12 | self.token = SecureRandom.hex(10) 13 | end 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | class ApplicationRecord < ActiveRecord::Base 2 | self.abstract_class = true 3 | end 4 | -------------------------------------------------------------------------------- /app/models/article.rb: -------------------------------------------------------------------------------- 1 | class Article < ApplicationRecord 2 | validates :title, presence: true 3 | validates :content, presence: true 4 | validates :slug, presence: true, uniqueness: true 5 | 6 | belongs_to :user 7 | 8 | has_many :comments, dependent: :destroy 9 | 10 | scope :recent, -> { order(created_at: :desc) } 11 | end 12 | -------------------------------------------------------------------------------- /app/models/comment.rb: -------------------------------------------------------------------------------- 1 | class Comment < ApplicationRecord 2 | belongs_to :article 3 | belongs_to :user 4 | 5 | validates :content, presence: true 6 | end 7 | -------------------------------------------------------------------------------- /app/models/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/driggl/rails-api-complete-guide/df79b4536c3a54cd9840353d693991df65eb2b85/app/models/concerns/.keep -------------------------------------------------------------------------------- /app/models/user.rb: -------------------------------------------------------------------------------- 1 | class User < ApplicationRecord 2 | include BCrypt 3 | validates :login, presence: true, uniqueness: true 4 | validates :provider, presence: true 5 | validates :password, presence: true, if: -> { provider == 'standard' } 6 | 7 | has_one :access_token, dependent: :destroy 8 | has_many :articles, dependent: :destroy 9 | has_many :comments, dependent: :destroy 10 | 11 | def password 12 | @password ||= Password.new(encrypted_password) if encrypted_password.present? 13 | end 14 | 15 | def password=(new_password) 16 | return @password = new_password if new_password.blank? 17 | @password = Password.create(new_password) 18 | self.encrypted_password = @password 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /app/serializers/access_token_serializer.rb: -------------------------------------------------------------------------------- 1 | class AccessTokenSerializer < ActiveModel::Serializer 2 | attributes :id, :token 3 | end 4 | -------------------------------------------------------------------------------- /app/serializers/article_serializer.rb: -------------------------------------------------------------------------------- 1 | class ArticleSerializer < ActiveModel::Serializer 2 | attributes :id, :title, :content, :slug 3 | end 4 | -------------------------------------------------------------------------------- /app/serializers/comment_serializer.rb: -------------------------------------------------------------------------------- 1 | class CommentSerializer < ActiveModel::Serializer 2 | attributes :id, :content 3 | has_one :article 4 | has_one :user 5 | end 6 | -------------------------------------------------------------------------------- /app/serializers/error_serializer.rb: -------------------------------------------------------------------------------- 1 | class ErrorSerializer < ActiveModel::Serializer::ErrorSerializer 2 | end 3 | -------------------------------------------------------------------------------- /app/serializers/user_serializer.rb: -------------------------------------------------------------------------------- 1 | class UserSerializer < ActiveModel::Serializer 2 | attributes :id, :login, :avatar_url, :url, :name 3 | end 4 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.text.erb: -------------------------------------------------------------------------------- 1 | <%= yield %> 2 | -------------------------------------------------------------------------------- /bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 3 | load Gem.bin_path('bundler', 'bundle') 4 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | begin 3 | load File.expand_path('../spring', __FILE__) 4 | rescue LoadError => e 5 | raise unless e.message.include?('spring') 6 | end 7 | APP_PATH = File.expand_path('../config/application', __dir__) 8 | require_relative '../config/boot' 9 | require 'rails/commands' 10 | -------------------------------------------------------------------------------- /bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | begin 3 | load File.expand_path('../spring', __FILE__) 4 | rescue LoadError => e 5 | raise unless e.message.include?('spring') 6 | end 7 | require_relative '../config/boot' 8 | require 'rake' 9 | Rake.application.run 10 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 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 starting point to setup your application. 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 | # cp 'config/database.yml.sample', 'config/database.yml' 23 | # end 24 | 25 | puts "\n== Preparing database ==" 26 | system! 'bin/rails db:setup' 27 | 28 | puts "\n== Removing old logs and tempfiles ==" 29 | system! 'bin/rails log:clear tmp:clear' 30 | 31 | puts "\n== Restarting application server ==" 32 | system! 'bin/rails restart' 33 | end 34 | -------------------------------------------------------------------------------- /bin/spring: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | # This file loads spring without using Bundler, in order to be fast. 4 | # It gets overwritten when you run the `spring binstub` command. 5 | 6 | unless defined?(Spring) 7 | require 'rubygems' 8 | require 'bundler' 9 | 10 | lockfile = Bundler::LockfileParser.new(Bundler.default_lockfile.read) 11 | spring = lockfile.specs.detect { |spec| spec.name == "spring" } 12 | if spring 13 | Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path 14 | gem 'spring', spring.version 15 | require 'spring/binstub' 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /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_view/railtie" 12 | require "action_cable/engine" 13 | # require "sprockets/railtie" 14 | # require "rails/test_unit/railtie" 15 | 16 | # Require the gems listed in Gemfile, including any gems 17 | # you've limited to :test, :development, or :production. 18 | Bundler.require(*Rails.groups) 19 | 20 | module Api 21 | class Application < Rails::Application 22 | # Initialize configuration defaults for originally generated Rails version. 23 | config.load_defaults 5.2 24 | 25 | # Settings in config/environments/* take precedence over those specified here. 26 | # Application configuration can go into files in config/initializers 27 | # -- all .rb files in that directory are automatically loaded after loading 28 | # the framework and any gems in your application. 29 | 30 | # Only loads a smaller set of middleware suitable for API only apps. 31 | # Middleware like session, flash, cookies can be added back manually. 32 | # Skip views, helpers and assets when generating a new resource. 33 | config.api_only = true 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /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: async 6 | 7 | production: 8 | adapter: redis 9 | url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> 10 | channel_prefix: api_production 11 | -------------------------------------------------------------------------------- /config/credentials.yml.enc: -------------------------------------------------------------------------------- 1 | tlyy4Di5V4Qv35TKKK0uh7oqUHmGg5HBxhEJs0EOGQ6cM3Jhg/8Nd70pb1T1khZjs6z8E2BPfgnPXwce/phn5SFNsquNd7hcsiuL17iSyu1rVHUPgOa+6pkdl9gXmAunGVTHyjekSXUphZB8MB/3AfcFsaTFKNCcIXPGIJW7NFiqWsJs4op0uszH0W5ocr2apDwTbqpHknpauNBbJu7DksveCFNTtPMfh12lL0UL/6pLLXo8SeQPMfcuKSDOf0z+x4PyMEvZV9fiwfcPqpdmaF5QCb4J3MyjzO3AMgG5JwW2Y6JeMfZxouiA9IJIBTAEusn58lUDBvTuTWlco1jl5MbGb+Z0FP5Ijfz4of2kmklgQIk+XPQO4zlrpg2QYOdw2h9up9/mM70jsL1KbfTFo9JdcvitWPWkQ/Ad--XlHvdQd8QV0FjSVQ--BldUKnIX9bw4Heyi5YaG9Q== -------------------------------------------------------------------------------- /config/database.yml: -------------------------------------------------------------------------------- 1 | # SQLite version 3.x 2 | # gem install sqlite3 3 | # 4 | # Ensure the SQLite 3 gem is defined in your Gemfile 5 | # gem 'sqlite3' 6 | # 7 | default: &default 8 | adapter: sqlite3 9 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> 10 | timeout: 5000 11 | 12 | development: 13 | <<: *default 14 | database: db/development.sqlite3 15 | 16 | # Warning: The database defined as "test" will be erased and 17 | # re-generated from your development database when you run "rake". 18 | # Do not set this db to the same as development or production. 19 | test: 20 | <<: *default 21 | database: db/test.sqlite3 22 | 23 | production: 24 | <<: *default 25 | database: db/production.sqlite3 26 | -------------------------------------------------------------------------------- /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.action_controller.perform_caching = true 19 | 20 | config.cache_store = :memory_store 21 | config.public_file_server.headers = { 22 | 'Cache-Control' => "public, max-age=#{2.days.to_i}" 23 | } 24 | else 25 | config.action_controller.perform_caching = false 26 | 27 | config.cache_store = :null_store 28 | end 29 | 30 | # Store uploaded files on the local file system (see config/storage.yml for options) 31 | config.active_storage.service = :local 32 | 33 | # Don't care if the mailer can't send. 34 | config.action_mailer.raise_delivery_errors = false 35 | 36 | config.action_mailer.perform_caching = false 37 | 38 | # Print deprecation notices to the Rails logger. 39 | config.active_support.deprecation = :log 40 | 41 | # Raise an error on page load if there are pending migrations. 42 | config.active_record.migration_error = :page_load 43 | 44 | # Highlight code that triggered database queries in logs. 45 | config.active_record.verbose_query_logs = true 46 | 47 | 48 | # Raises error for missing translations 49 | # config.action_view.raise_on_missing_translations = true 50 | 51 | # Use an evented file watcher to asynchronously detect changes in source code, 52 | # routes, locales, etc. This feature depends on the listen gem. 53 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker 54 | end 55 | -------------------------------------------------------------------------------- /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 | config.action_controller.perform_caching = true 16 | 17 | # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] 18 | # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). 19 | # config.require_master_key = true 20 | 21 | # Disable serving static files from the `/public` folder by default since 22 | # Apache or NGINX already handles this. 23 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 24 | 25 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 26 | # config.action_controller.asset_host = 'http://assets.example.com' 27 | 28 | # Specifies the header that your server uses for sending files. 29 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 30 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 31 | 32 | # Store uploaded files on the local file system (see config/storage.yml for options) 33 | config.active_storage.service = :local 34 | 35 | # Mount Action Cable outside main process or domain 36 | # config.action_cable.mount_path = nil 37 | # config.action_cable.url = 'wss://example.com/cable' 38 | # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] 39 | 40 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 41 | # config.force_ssl = true 42 | 43 | # Use the lowest log level to ensure availability of diagnostic information 44 | # when problems arise. 45 | config.log_level = :debug 46 | 47 | # Prepend all log lines with the following tags. 48 | config.log_tags = [ :request_id ] 49 | 50 | # Use a different cache store in production. 51 | # config.cache_store = :mem_cache_store 52 | 53 | # Use a real queuing backend for Active Job (and separate queues per environment) 54 | # config.active_job.queue_adapter = :resque 55 | # config.active_job.queue_name_prefix = "api_#{Rails.env}" 56 | 57 | config.action_mailer.perform_caching = false 58 | 59 | # Ignore bad email addresses and do not raise email delivery errors. 60 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 61 | # config.action_mailer.raise_delivery_errors = false 62 | 63 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 64 | # the I18n.default_locale when a translation cannot be found). 65 | config.i18n.fallbacks = true 66 | 67 | # Send deprecation notices to registered listeners. 68 | config.active_support.deprecation = :notify 69 | 70 | # Use default logging formatter so that PID and timestamp are not suppressed. 71 | config.log_formatter = ::Logger::Formatter.new 72 | 73 | # Use a different logger for distributed setups. 74 | # require 'syslog/logger' 75 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 76 | 77 | if ENV["RAILS_LOG_TO_STDOUT"].present? 78 | logger = ActiveSupport::Logger.new(STDOUT) 79 | logger.formatter = config.log_formatter 80 | config.logger = ActiveSupport::TaggedLogging.new(logger) 81 | end 82 | 83 | # Do not dump schema after migrations. 84 | config.active_record.dump_schema_after_migration = false 85 | end 86 | -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # The test environment is used exclusively to run your application's 5 | # test suite. You never need to work with it otherwise. Remember that 6 | # your test database is "scratch space" for the test suite and is wiped 7 | # and recreated between test runs. Don't rely on the data there! 8 | config.cache_classes = true 9 | 10 | # Do not eager load code on boot. This avoids loading your whole application 11 | # just for the purpose of running a single test. If you are using a tool that 12 | # preloads Rails for running tests, you may have to set it to true. 13 | config.eager_load = false 14 | 15 | # Configure public file server for tests with Cache-Control for performance. 16 | config.public_file_server.enabled = true 17 | config.public_file_server.headers = { 18 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}" 19 | } 20 | 21 | # Show full error reports and disable caching. 22 | config.consider_all_requests_local = true 23 | config.action_controller.perform_caching = false 24 | 25 | # Raise exceptions instead of rendering exception templates. 26 | config.action_dispatch.show_exceptions = false 27 | 28 | # Disable request forgery protection in test environment. 29 | config.action_controller.allow_forgery_protection = false 30 | 31 | # Store uploaded files on the local file system in a temporary directory 32 | config.active_storage.service = :test 33 | 34 | config.action_mailer.perform_caching = false 35 | 36 | # Tell Action Mailer not to deliver emails to the real world. 37 | # The :test delivery method accumulates sent emails in the 38 | # ActionMailer::Base.deliveries array. 39 | config.action_mailer.delivery_method = :test 40 | 41 | # Print deprecation notices to the stderr. 42 | config.active_support.deprecation = :stderr 43 | 44 | # Raises error for missing translations 45 | # config.action_view.raise_on_missing_translations = true 46 | end 47 | -------------------------------------------------------------------------------- /config/initializers/active_model_serializers.rb: -------------------------------------------------------------------------------- 1 | ActiveModelSerializers.config.adapter = :json_api 2 | -------------------------------------------------------------------------------- /config/initializers/application_controller_renderer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # ActiveSupport::Reloader.to_prepare do 4 | # ApplicationController.renderer.defaults.merge!( 5 | # http_host: 'example.org', 6 | # https: false 7 | # ) 8 | # end 9 | -------------------------------------------------------------------------------- /config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| 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 'example.com' 11 | # 12 | # resource '*', 13 | # headers: :any, 14 | # methods: [:get, :post, :put, :patch, :delete, :options, :head] 15 | # end 16 | # end 17 | -------------------------------------------------------------------------------- /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/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/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 http://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 | threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } 8 | threads threads_count, threads_count 9 | 10 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000. 11 | # 12 | port ENV.fetch("PORT") { 3000 } 13 | 14 | # Specifies the `environment` that Puma will run in. 15 | # 16 | environment ENV.fetch("RAILS_ENV") { "development" } 17 | 18 | # Specifies the number of `workers` to boot in clustered mode. 19 | # Workers are forked webserver processes. If using threads and workers together 20 | # the concurrency of the application would be max `threads` * `workers`. 21 | # Workers do not work on JRuby or Windows (both of which do not support 22 | # processes). 23 | # 24 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 } 25 | 26 | # Use the `preload_app!` method when specifying a `workers` number. 27 | # This directive tells Puma to first boot the application and load code 28 | # before forking the application. This takes advantage of Copy On Write 29 | # process behavior so workers use less memory. 30 | # 31 | # preload_app! 32 | 33 | # Allow puma to be restarted by `rails restart` command. 34 | plugin :tmp_restart 35 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html 3 | post 'login', to: 'access_tokens#create' 4 | delete 'logout', to: 'access_tokens#destroy' 5 | post 'sign_up', to: 'registrations#create' 6 | 7 | resources :articles do 8 | resources :comments, only: [:index, :create] 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /config/spring.rb: -------------------------------------------------------------------------------- 1 | %w[ 2 | .ruby-version 3 | .rbenv-vars 4 | tmp/restart.txt 5 | tmp/caching-dev.txt 6 | ].each { |path| Spring.watch(path) } 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/20180425083447_create_articles.rb: -------------------------------------------------------------------------------- 1 | class CreateArticles < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :articles do |t| 4 | t.string :title 5 | t.text :content 6 | t.string :slug 7 | 8 | t.timestamps 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /db/migrate/20180503212840_create_users.rb: -------------------------------------------------------------------------------- 1 | class CreateUsers < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :users do |t| 4 | t.string :login, null: false 5 | t.string :name 6 | t.string :url 7 | t.string :avatar_url 8 | t.string :provider 9 | 10 | t.timestamps 11 | end 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /db/migrate/20180506105306_create_access_tokens.rb: -------------------------------------------------------------------------------- 1 | class CreateAccessTokens < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :access_tokens do |t| 4 | t.string :token, null: false 5 | t.references :user, foreign_key: true 6 | 7 | t.timestamps 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /db/migrate/20180518211629_add_user_to_articles.rb: -------------------------------------------------------------------------------- 1 | class AddUserToArticles < ActiveRecord::Migration[5.2] 2 | def change 3 | add_reference :articles, :user, foreign_key: true 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /db/migrate/20180519145812_create_comments.rb: -------------------------------------------------------------------------------- 1 | class CreateComments < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :comments do |t| 4 | t.text :content 5 | t.references :article, foreign_key: true 6 | t.references :user, foreign_key: true 7 | 8 | t.timestamps 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /db/migrate/20180807150152_add_encrypted_password_to_users.rb: -------------------------------------------------------------------------------- 1 | class AddEncryptedPasswordToUsers < ActiveRecord::Migration[5.2] 2 | def change 3 | add_column :users, :encrypted_password, :string 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /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 | # Note that this schema.rb definition is the authoritative source for your 6 | # database schema. If you need to create the application database on another 7 | # system, you should be using db:schema:load, not running all the migrations 8 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 9 | # you'll amass, the slower it'll run and the greater likelihood for issues). 10 | # 11 | # It's strongly recommended that you check this file into your version control system. 12 | 13 | ActiveRecord::Schema.define(version: 2018_08_07_150152) do 14 | 15 | create_table "access_tokens", force: :cascade do |t| 16 | t.string "token", null: false 17 | t.integer "user_id" 18 | t.datetime "created_at", null: false 19 | t.datetime "updated_at", null: false 20 | t.index ["user_id"], name: "index_access_tokens_on_user_id" 21 | end 22 | 23 | create_table "articles", force: :cascade do |t| 24 | t.string "title" 25 | t.text "content" 26 | t.string "slug" 27 | t.datetime "created_at", null: false 28 | t.datetime "updated_at", null: false 29 | t.integer "user_id" 30 | t.index ["user_id"], name: "index_articles_on_user_id" 31 | end 32 | 33 | create_table "comments", force: :cascade do |t| 34 | t.text "content" 35 | t.integer "article_id" 36 | t.integer "user_id" 37 | t.datetime "created_at", null: false 38 | t.datetime "updated_at", null: false 39 | t.index ["article_id"], name: "index_comments_on_article_id" 40 | t.index ["user_id"], name: "index_comments_on_user_id" 41 | end 42 | 43 | create_table "users", force: :cascade do |t| 44 | t.string "login", null: false 45 | t.string "name" 46 | t.string "url" 47 | t.string "avatar_url" 48 | t.string "provider" 49 | t.datetime "created_at", null: false 50 | t.datetime "updated_at", null: false 51 | t.string "encrypted_password" 52 | end 53 | 54 | end 55 | -------------------------------------------------------------------------------- /db/seeds.rb: -------------------------------------------------------------------------------- 1 | user = User.create( 2 | { login: 'jsmith', name: 'John Smith', provider: 'github' } 3 | ) 4 | Article.create([ 5 | { title: 'Article title 1', 6 | content: 'Article content 1', 7 | slug: 'article-title-1', 8 | user: user 9 | }, 10 | { title: 'Article title 2', 11 | content: 'Article content 2', 12 | slug: 'article-title-2', 13 | user: user 14 | }, 15 | { title: 'Article title 3', 16 | content: 'Article content 3', 17 | slug: 'article-title-3', 18 | user: user 19 | } 20 | ]) 21 | -------------------------------------------------------------------------------- /lib/tasks/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/driggl/rails-api-complete-guide/df79b4536c3a54cd9840353d693991df65eb2b85/lib/tasks/.keep -------------------------------------------------------------------------------- /log/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/driggl/rails-api-complete-guide/df79b4536c3a54cd9840353d693991df65eb2b85/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/controllers/access_tokens_controller_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe AccessTokensController, type: :controller do 4 | describe 'POST #create' do 5 | let(:params) do 6 | { 7 | data: { 8 | attributes: { login: "jsmith", password: "secret" } 9 | } 10 | } 11 | end 12 | 13 | context 'when no auth_data provided' do 14 | subject { post :create } 15 | it_behaves_like "unauthorized_standard_requests" 16 | end 17 | 18 | context "when invalid login provided" do 19 | let(:user) { create :user, login: 'invalid', password: 'secret' } 20 | subject { post :create, params: params } 21 | 22 | before { user } 23 | 24 | it_behaves_like "unauthorized_standard_requests" 25 | end 26 | 27 | context "when invalid password provided" do 28 | let(:user) { create :user, login: 'jsmith', password: 'invalid' } 29 | subject { post :create, params: params } 30 | 31 | before { user } 32 | 33 | it_behaves_like "unauthorized_standard_requests" 34 | end 35 | 36 | context "when valid data provided" do 37 | let(:user) { create :user, login: 'jsmith', password: 'secret' } 38 | subject { post :create, params: params } 39 | 40 | before { user } 41 | 42 | it 'should return 201 status code' do 43 | subject 44 | expect(response).to have_http_status(:created) 45 | end 46 | 47 | it 'should return proper json body' do 48 | subject 49 | expect(json_data['attributes']).to eq( 50 | { 'token' => user.access_token.token } 51 | ) 52 | end 53 | end 54 | 55 | context 'when invalid code provided' do 56 | let(:github_error) { 57 | double("Sawyer::Resource", error: "bad_verification_code") 58 | } 59 | 60 | before do 61 | allow_any_instance_of(Octokit::Client).to receive( 62 | :exchange_code_for_token).and_return(github_error) 63 | end 64 | 65 | subject { post :create, params: { code: 'invalid_code' } } 66 | 67 | it_behaves_like "unauthorized_oauth_requests" 68 | end 69 | 70 | context 'when success request' do 71 | let(:user_data) do 72 | { 73 | login: 'jsmith1', 74 | url: 'http://example.com', 75 | avatar_url: 'http://example.com/avatar', 76 | name: 'John Smith' 77 | } 78 | end 79 | 80 | before do 81 | allow_any_instance_of(Octokit::Client).to receive( 82 | :exchange_code_for_token).and_return('validaccesstoken') 83 | 84 | allow_any_instance_of(Octokit::Client).to receive( 85 | :user).and_return(user_data) 86 | end 87 | 88 | subject { post :create, params: { code: 'valid_code' } } 89 | 90 | it 'should return 201 status code' do 91 | subject 92 | expect(response).to have_http_status(:created) 93 | end 94 | 95 | it 'should return proper json body' do 96 | expect{ subject }.to change{ User.count }.by(1) 97 | user = User.find_by(login: 'jsmith1') 98 | expect(json_data['attributes']).to eq( 99 | { 'token' => user.access_token.token } 100 | ) 101 | end 102 | end 103 | end 104 | 105 | describe 'DELETE #destroy' do 106 | subject { delete :destroy } 107 | 108 | context 'when no authorization header provided' do 109 | 110 | it_behaves_like 'forbidden_requests' 111 | end 112 | 113 | context 'when invalid authorization header provided' do 114 | before { request.headers['authorization'] = 'Invalid token' } 115 | 116 | it_behaves_like 'forbidden_requests' 117 | end 118 | 119 | context 'when valid request' do 120 | let(:user) { create :user } 121 | let(:access_token) { user.create_access_token } 122 | 123 | before { request.headers['authorization'] = "Bearer #{access_token.token}" } 124 | 125 | it 'should return 204 status code' do 126 | subject 127 | expect(response).to have_http_status(:no_content) 128 | end 129 | 130 | it 'should remove the proper access token' do 131 | expect{ subject }.to change{ AccessToken.count }.by(-1) 132 | end 133 | end 134 | end 135 | end 136 | -------------------------------------------------------------------------------- /spec/controllers/articles_controller_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | describe ArticlesController do 4 | describe '#index' do 5 | subject { get :index } 6 | 7 | it 'should return success response' do 8 | subject 9 | expect(response).to have_http_status(:ok) 10 | end 11 | 12 | it 'should return proper json' do 13 | create_list :article, 2 14 | subject 15 | Article.recent.each_with_index do |article, index| 16 | expect(json_data[index]['attributes']).to eq({ 17 | "title" => article.title, 18 | "content" => article.content, 19 | "slug" => article.slug 20 | }) 21 | end 22 | end 23 | 24 | it 'should return articles in the proper order' do 25 | old_article = create :article 26 | newer_article = create :article 27 | subject 28 | expect(json_data.first['id']).to eq(newer_article.id.to_s) 29 | expect(json_data.last['id']).to eq(old_article.id.to_s) 30 | end 31 | 32 | it 'should paginate results' do 33 | create_list :article, 3 34 | get :index, params: { page: 2, per_page: 1 } 35 | expect(json_data.length).to eq 1 36 | expected_article = Article.recent.second.id.to_s 37 | expect(json_data.first['id']).to eq(expected_article) 38 | end 39 | end 40 | 41 | describe '#show' do 42 | let(:article) { create :article } 43 | subject { get :show, params: { id: article.id } } 44 | 45 | it 'should return success response' do 46 | subject 47 | expect(response).to have_http_status(:ok) 48 | end 49 | 50 | it 'should return proper json' do 51 | subject 52 | expect(json_data['attributes']).to eq({ 53 | "title" => article.title, 54 | "content" => article.content, 55 | "slug" => article.slug 56 | }) 57 | end 58 | end 59 | 60 | describe '#create' do 61 | subject { post :create } 62 | 63 | context 'when no code provided' do 64 | it_behaves_like 'forbidden_requests' 65 | end 66 | 67 | context 'when invalid code provided' do 68 | before { request.headers['authorization'] = 'Invalid token' } 69 | it_behaves_like 'forbidden_requests' 70 | end 71 | 72 | context 'when authorized' do 73 | let(:access_token) { create :access_token } 74 | before { request.headers['authorization'] = "Bearer #{access_token.token}" } 75 | 76 | context 'when invalid parameters provided' do 77 | let(:invalid_attributes) do 78 | { 79 | data: { 80 | attributes: { 81 | title: '', 82 | content: '' 83 | } 84 | } 85 | } 86 | end 87 | 88 | subject { post :create, params: invalid_attributes } 89 | 90 | it 'should return 422 status code' do 91 | subject 92 | expect(response).to have_http_status(:unprocessable_entity) 93 | end 94 | 95 | it 'should return proper error json' do 96 | subject 97 | expect(json['errors']).to include( 98 | { 99 | "source" => { "pointer" => "/data/attributes/title" }, 100 | "detail" => "can't be blank" 101 | }, 102 | { 103 | "source" => { "pointer" => "/data/attributes/content" }, 104 | "detail" => "can't be blank" 105 | }, 106 | { 107 | "source" => { "pointer" => "/data/attributes/slug" }, 108 | "detail" => "can't be blank" 109 | } 110 | ) 111 | end 112 | end 113 | 114 | context 'when success request sent' do 115 | let(:access_token) { create :access_token } 116 | before { request.headers['authorization'] = "Bearer #{access_token.token}" } 117 | 118 | let(:valid_attributes) do 119 | { 120 | 'data' => { 121 | 'attributes' => { 122 | 'title' => 'Awesome article', 123 | 'content' => 'Super content', 124 | 'slug' => 'awesome-article' 125 | } 126 | } 127 | } 128 | end 129 | 130 | subject { post :create, params: valid_attributes } 131 | 132 | it 'should have 201 status code' do 133 | subject 134 | expect(response).to have_http_status(:created) 135 | end 136 | 137 | it 'should have proper json body' do 138 | subject 139 | expect(json_data['attributes']).to include( 140 | valid_attributes['data']['attributes'] 141 | ) 142 | end 143 | 144 | it 'should create the article' do 145 | expect{ subject }.to change{ Article.count }.by(1) 146 | end 147 | end 148 | end 149 | end 150 | 151 | describe '#update' do 152 | let(:user) { create :user } 153 | let(:article) { create :article, user: user } 154 | let(:access_token) { user.create_access_token } 155 | 156 | subject { patch :update, params: { id: article.id } } 157 | 158 | context 'when no code provided' do 159 | it_behaves_like 'forbidden_requests' 160 | end 161 | 162 | context 'when invalid code provided' do 163 | before { request.headers['authorization'] = 'Invalid token' } 164 | it_behaves_like 'forbidden_requests' 165 | end 166 | 167 | context 'when trying to update not owned article' do 168 | let(:other_user) { create :user } 169 | let(:other_article) { create :article, user: other_user } 170 | 171 | subject { patch :update, params: { id: other_article.id } } 172 | before { request.headers['authorization'] = "Bearer #{access_token.token}" } 173 | 174 | it_behaves_like 'forbidden_requests' 175 | end 176 | 177 | context 'when authorized' do 178 | before { request.headers['authorization'] = "Bearer #{access_token.token}" } 179 | 180 | context 'when invalid parameters provided' do 181 | let(:invalid_attributes) do 182 | { 183 | data: { 184 | attributes: { 185 | title: '', 186 | content: '' 187 | } 188 | } 189 | } 190 | end 191 | 192 | subject do 193 | patch :update, params: invalid_attributes.merge(id: article.id) 194 | end 195 | 196 | it 'should return 422 status code' do 197 | subject 198 | expect(response).to have_http_status(:unprocessable_entity) 199 | end 200 | 201 | it 'should return proper error json' do 202 | subject 203 | expect(json['errors']).to include( 204 | { 205 | "source" => { "pointer" => "/data/attributes/title" }, 206 | "detail" => "can't be blank" 207 | }, 208 | { 209 | "source" => { "pointer" => "/data/attributes/content" }, 210 | "detail" => "can't be blank" 211 | } 212 | ) 213 | end 214 | end 215 | 216 | context 'when success request sent' do 217 | before { request.headers['authorization'] = "Bearer #{access_token.token}" } 218 | 219 | let(:valid_attributes) do 220 | { 221 | 'data' => { 222 | 'attributes' => { 223 | 'title' => 'Awesome article', 224 | 'content' => 'Super content', 225 | 'slug' => 'awesome-article' 226 | } 227 | } 228 | } 229 | end 230 | 231 | subject do 232 | patch :update, params: valid_attributes.merge(id: article.id) 233 | end 234 | 235 | it 'should have 200 status code' do 236 | subject 237 | expect(response).to have_http_status(:ok) 238 | end 239 | 240 | it 'should have proper json body' do 241 | subject 242 | expect(json_data['attributes']).to include( 243 | valid_attributes['data']['attributes'] 244 | ) 245 | end 246 | 247 | it 'should update the article' do 248 | subject 249 | expect(article.reload.title).to eq( 250 | valid_attributes['data']['attributes']['title'] 251 | ) 252 | end 253 | end 254 | end 255 | end 256 | 257 | describe '#destroy' do 258 | let(:user) { create :user } 259 | let(:article) { create :article, user: user } 260 | let(:access_token) { user.create_access_token } 261 | 262 | subject { delete :destroy, params: { id: article.id } } 263 | 264 | context 'when no code provided' do 265 | it_behaves_like 'forbidden_requests' 266 | end 267 | 268 | context 'when invalid code provided' do 269 | before { request.headers['authorization'] = 'Invalid token' } 270 | it_behaves_like 'forbidden_requests' 271 | end 272 | 273 | context 'when trying to remove not owned article' do 274 | let(:other_user) { create :user } 275 | let(:other_article) { create :article, user: other_user } 276 | 277 | subject { delete :destroy, params: { id: other_article.id } } 278 | before { request.headers['authorization'] = "Bearer #{access_token.token}" } 279 | 280 | it_behaves_like 'forbidden_requests' 281 | end 282 | 283 | context 'when authorized' do 284 | before { request.headers['authorization'] = "Bearer #{access_token.token}" } 285 | 286 | context 'when success request sent' do 287 | before { request.headers['authorization'] = "Bearer #{access_token.token}" } 288 | 289 | it 'should have 204 status code' do 290 | subject 291 | expect(response).to have_http_status(:no_content) 292 | end 293 | 294 | it 'should have empty json body' do 295 | subject 296 | expect(response.body).to be_blank 297 | end 298 | 299 | it 'should destroy the article' do 300 | article 301 | expect{ subject }.to change{ user.articles.count }.by(-1) 302 | end 303 | end 304 | end 305 | end 306 | end 307 | -------------------------------------------------------------------------------- /spec/controllers/comments_controller_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe CommentsController, type: :controller do 4 | let(:article) { create :article } 5 | 6 | describe "GET #index" do 7 | subject { get :index, params: { article_id: article.id } } 8 | 9 | it "returns a success response" do 10 | subject 11 | expect(response).to have_http_status(:ok) 12 | end 13 | 14 | it 'should return only comments belonging to article' do 15 | comment = create :comment, article: article 16 | create :comment 17 | subject 18 | expect(json_data.length).to eq(1) 19 | expect(json_data.first['id']).to eq(comment.id.to_s) 20 | end 21 | 22 | it 'should paginate results' do 23 | comments = create_list :comment, 3, article: article 24 | get :index, params: { article_id: article.id, per_page: 1, page: 2 } 25 | expect(json_data.length).to eq(1) 26 | comment = comments.second 27 | expect(json_data.first['id']).to eq(comment.id.to_s) 28 | end 29 | 30 | it 'should have proper json body' do 31 | comment = create :comment, article: article 32 | subject 33 | expect(json_data.first['attributes']).to eq({ 34 | 'content' => comment.content 35 | }) 36 | end 37 | 38 | it 'should have related objects information in the response' do 39 | user = create :user 40 | create :comment, article: article, user: user 41 | subject 42 | relationships = json_data.first['relationships'] 43 | expect(relationships['article']['data']['id']).to eq(article.id.to_s) 44 | expect(relationships['user']['data']['id']).to eq(user.id.to_s) 45 | end 46 | end 47 | 48 | describe "POST #create" do 49 | context 'when not authorized' do 50 | subject { post :create, params: { article_id: article.id } } 51 | 52 | it_behaves_like 'forbidden_requests' 53 | end 54 | 55 | context 'when authorized' do 56 | let(:valid_attributes) do 57 | { data: { attributes: { content: 'My awesome comment for article' } } } 58 | end 59 | 60 | let(:invalid_attributes) { { data: { attributes: { content: '' } } } } 61 | 62 | let(:user) { create :user } 63 | let(:access_token) { user.create_access_token } 64 | 65 | before { request.headers['authorization'] = "Bearer #{access_token.token}" } 66 | 67 | context "with valid params" do 68 | subject do 69 | post :create, params: valid_attributes.merge(article_id: article.id) 70 | end 71 | 72 | it 'returns 201 status code' do 73 | subject 74 | expect(response).to have_http_status(:created) 75 | end 76 | 77 | it "creates a new Comment" do 78 | expect { subject }.to change(article.comments, :count).by(1) 79 | end 80 | 81 | it "renders a JSON response with the new comment" do 82 | subject 83 | expect(json_data['attributes']).to eq({ 84 | 'content' => 'My awesome comment for article' 85 | }) 86 | end 87 | end 88 | 89 | context "with invalid params" do 90 | subject do 91 | post :create, params: invalid_attributes.merge(article_id: article.id) 92 | end 93 | 94 | it 'should return 422 status code' do 95 | subject 96 | expect(response).to have_http_status(:unprocessable_entity) 97 | end 98 | 99 | it "renders a JSON response with errors for the new comment" do 100 | subject 101 | expect(json['errors']).to include({ 102 | "source" => { "pointer" => "/data/attributes/content" }, 103 | "detail" => "can't be blank" 104 | }) 105 | end 106 | end 107 | end 108 | 109 | end 110 | end 111 | -------------------------------------------------------------------------------- /spec/controllers/registrations_controller_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | describe RegistrationsController do 4 | describe '#create' do 5 | subject { post :create, params: params } 6 | context 'when invalid data provided' do 7 | let(:params) do 8 | { 9 | data: { 10 | attributes: { 11 | login: nil, 12 | password: nil 13 | } 14 | } 15 | } 16 | end 17 | 18 | it 'should return unprocessable_entity status code' do 19 | subject 20 | expect(response).to have_http_status(:unprocessable_entity) 21 | end 22 | 23 | it 'should not create a user' do 24 | expect{ subject }.not_to change{ User.count } 25 | end 26 | 27 | it 'should return error messages in response body' do 28 | subject 29 | expect(json['errors']).to include( 30 | { 31 | 'source' => { 'pointer' => '/data/attributes/login' }, 32 | 'detail' => "can't be blank" 33 | }, 34 | { 35 | 'source' => { 'pointer' => '/data/attributes/password' }, 36 | 'detail' => "can't be blank" 37 | } 38 | ) 39 | end 40 | end 41 | 42 | context 'when valid data provided' do 43 | let(:params) do 44 | { 45 | data: { 46 | attributes: { 47 | login: 'jsmith', 48 | password: 'secretpassword' 49 | } 50 | } 51 | } 52 | end 53 | 54 | it 'should return 201 http status code' do 55 | subject 56 | expect(response).to have_http_status(:created) 57 | end 58 | 59 | it 'should create a user' do 60 | expect(User.exists?(login: 'jsmith')).to be_falsey 61 | expect{ subject }.to change{ User.count }.by(1) 62 | expect(User.exists?(login: 'jsmith')).to be_truthy 63 | end 64 | 65 | it 'should return proper json' do 66 | subject 67 | expect(json_data['attributes']).to eq({ 68 | 'login' => 'jsmith', 69 | 'avatar-url' => nil, 70 | 'url' => nil, 71 | 'name' => nil 72 | }) 73 | end 74 | end 75 | end 76 | end 77 | -------------------------------------------------------------------------------- /spec/factories/access_tokens.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :access_token do 3 | #token is generated after initialization 4 | association :user 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /spec/factories/articles.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :article do 3 | sequence(:title) { |n| "My awesome article #{n}" } 4 | sequence(:content) { |n| "The content of my awesome article #{n}" } 5 | sequence(:slug) { |n| "my-awesome-article-#{n}" } 6 | association :user 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /spec/factories/comments.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :comment do 3 | content "My comment" 4 | association :article 5 | association :user 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /spec/factories/users.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :user do 3 | sequence(:login) { |n| "jsmith#{n}" } 4 | name "John Smith" 5 | url "http://example.com" 6 | avatar_url "http://example.com/avatar" 7 | provider "github" 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /spec/lib/user_authenticator/oauth_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | describe UserAuthenticator::Oauth do 4 | describe '#perform' do 5 | let(:authenticator) { described_class.new('sample_code') } 6 | 7 | subject { authenticator.perform } 8 | 9 | context 'when code is incorrect' do 10 | let(:error) { 11 | double("Sawyer::Resource", error: "bad_verification_code") 12 | } 13 | 14 | before do 15 | allow_any_instance_of(Octokit::Client).to receive( 16 | :exchange_code_for_token).and_return(error) 17 | end 18 | 19 | it 'should raise an error' do 20 | expect{ subject }.to raise_error( 21 | UserAuthenticator::Oauth::AuthenticationError 22 | ) 23 | expect(authenticator.user).to be_nil 24 | end 25 | end 26 | 27 | context 'when code is correct' do 28 | let(:user_data) do 29 | { 30 | login: 'jsmith1', 31 | url: 'http://example.com', 32 | avatar_url: 'http://example.com/avatar', 33 | name: 'John Smith' 34 | } 35 | end 36 | 37 | before do 38 | allow_any_instance_of(Octokit::Client).to receive( 39 | :exchange_code_for_token).and_return('validaccesstoken') 40 | 41 | allow_any_instance_of(Octokit::Client).to receive( 42 | :user).and_return(user_data) 43 | end 44 | 45 | it 'should save the user when does not exists' do 46 | expect{ subject }.to change{ User.count }.by(1) 47 | expect(User.last.name).to eq('John Smith') 48 | end 49 | 50 | it 'should reuse already registered user' do 51 | user = create :user, user_data 52 | expect{ subject }.not_to change{ User.count } 53 | expect(authenticator.user).to eq(user) 54 | end 55 | end 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /spec/lib/user_authenticator/standard_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | describe UserAuthenticator::Standard do 4 | describe "#perform" do 5 | let(:authenticator) { described_class.new('jsmith', 'password') } 6 | subject { authenticator.perform } 7 | 8 | shared_examples_for 'invalid authentication' do 9 | before { user } 10 | 11 | it "should raise an error" do 12 | expect{ subject }.to raise_error( 13 | UserAuthenticator::Standard::AuthenticationError 14 | ) 15 | expect(authenticator.user).to be_nil 16 | end 17 | end 18 | 19 | context "when invalid login" do 20 | let(:user) { create :user, login: 'ddoe', password: 'password' } 21 | it_behaves_like 'invalid authentication' 22 | end 23 | 24 | context "when invalid password" do 25 | let(:user) { create :user, login: 'jsmith', password: 'secret' } 26 | it_behaves_like 'invalid authentication' 27 | end 28 | 29 | context "when successed auth" do 30 | let(:user) { create :user, login: 'jsmith', password: 'password' } 31 | 32 | before { user } 33 | 34 | it 'should set the user found in db' do 35 | expect { subject }.not_to change{ User.count } 36 | expect(authenticator.user).to eq(user) 37 | end 38 | end 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /spec/lib/user_authenticator_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | describe UserAuthenticator do 4 | let(:user) { create :user, login: 'jsmith', password: 'secret' } 5 | 6 | shared_examples_for "authenticator" do 7 | it 'should create and set user access token' do 8 | expect(authenticator.authenticator).to receive(:perform).and_return(true) 9 | expect(authenticator.authenticator).to receive(:user). 10 | at_least(:once).and_return(user) 11 | expect { authenticator.perform }.to change{ AccessToken.count }.by(1) 12 | expect(authenticator.access_token).to be_present 13 | end 14 | end 15 | 16 | context "when initialized with code" do 17 | let(:authenticator) { described_class.new(code: 'sample') } 18 | let(:authenticator_class) { UserAuthenticator::Oauth } 19 | 20 | describe "#initialize" do 21 | it "should initialize proper authenticator" do 22 | expect(authenticator_class).to receive(:new).with('sample') 23 | authenticator 24 | end 25 | end 26 | 27 | it_behaves_like "authenticator" 28 | end 29 | 30 | context "when initialized with login & password" do 31 | let(:authenticator) { described_class.new(login: 'jsmith', password: 'secret') } 32 | let(:authenticator_class) { UserAuthenticator::Standard } 33 | 34 | describe "#initialize" do 35 | it "should initialize proper authenticator" do 36 | expect(authenticator_class).to receive(:new).with('jsmith', 'secret') 37 | authenticator 38 | end 39 | end 40 | 41 | it_behaves_like "authenticator" 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /spec/models/access_token_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe AccessToken, type: :model do 4 | describe '#validations' do 5 | it 'should have valid factory' do 6 | expect(build :access_token).to be_valid 7 | end 8 | 9 | it 'should validate token' do 10 | access_token = create :access_token 11 | expect(build :access_token, token: '').to be_invalid 12 | expect(build :access_token, token: access_token.token).to be_invalid 13 | end 14 | end 15 | 16 | describe '#new' do 17 | it 'should have a token present after initialize' do 18 | expect(AccessToken.new.token).to be_present 19 | end 20 | 21 | it 'should generate uniq token' do 22 | user = create :user 23 | expect{ user.create_access_token }.to change{ AccessToken.count }.by(1) 24 | expect(user.build_access_token).to be_valid 25 | end 26 | 27 | it 'should generate token once' do 28 | user = create :user 29 | access_token = user.create_access_token 30 | expect(access_token.token).to eq(access_token.reload.token) 31 | end 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /spec/models/article_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe Article, type: :model do 4 | describe '#validations' do 5 | it 'should test that the factory is valid' do 6 | expect(build :article).to be_valid 7 | end 8 | 9 | it 'should validate the presence of the title' do 10 | article = build :article, title: '' 11 | expect(article).not_to be_valid 12 | expect(article.errors.messages[:title]).to include("can't be blank") 13 | end 14 | 15 | it 'should validate the presence of the content' do 16 | article = build :article, content: '' 17 | expect(article).not_to be_valid 18 | expect(article.errors.messages[:content]).to include("can't be blank") 19 | end 20 | 21 | it 'should validate the presence of the slug' do 22 | article = build :article, slug: '' 23 | expect(article).not_to be_valid 24 | expect(article.errors.messages[:slug]).to include("can't be blank") 25 | end 26 | 27 | it 'should validate uniqueness of the slug' do 28 | article = create :article 29 | invalid_article = build :article, slug: article.slug 30 | expect(invalid_article).not_to be_valid 31 | end 32 | end 33 | 34 | describe '.recent' do 35 | it 'should list recent article first' do 36 | old_article = create :article 37 | newer_article = create :article 38 | expect(described_class.recent).to eq( 39 | [ newer_article, old_article ] 40 | ) 41 | old_article.update_column :created_at, Time.now 42 | expect(described_class.recent).to eq( 43 | [ old_article, newer_article ] 44 | ) 45 | end 46 | end 47 | end 48 | -------------------------------------------------------------------------------- /spec/models/comment_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe Comment, type: :model do 4 | describe '#validations' do 5 | it 'should have valid factory' do 6 | expect(build :comment).to be_valid 7 | end 8 | 9 | it 'should test presence of attributes' do 10 | comment = Comment.new 11 | expect(comment).not_to be_valid 12 | expect(comment.errors.messages).to include({ 13 | user: ['must exist'], 14 | article: ['must exist'], 15 | content: ["can't be blank"] 16 | }) 17 | end 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /spec/models/user_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe User, type: :model do 4 | describe "#validations" do 5 | it 'should have valid factory' do 6 | user = build :user 7 | expect(user).to be_valid 8 | end 9 | 10 | it 'should validate presence of attributes' do 11 | user = build :user, login: nil, provider: nil 12 | expect(user).not_to be_valid 13 | expect(user.errors.messages[:login]).to include("can't be blank") 14 | expect(user.errors.messages[:provider]).to include("can't be blank") 15 | end 16 | 17 | it 'should validate presence of password for standard provider' do 18 | user = build :user, login: 'jsmith', provider: 'standard', password: nil 19 | expect(user).not_to be_valid 20 | expect(user.errors.messages[:password]).to include("can't be blank") 21 | end 22 | 23 | it 'should validate uniqueness of login' do 24 | user = create :user 25 | other_user = build :user, login: user.login 26 | expect(other_user).not_to be_valid 27 | other_user.login = 'newlogin' 28 | expect(other_user).to be_valid 29 | end 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /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 | 10 | # Requires supporting ruby files with custom matchers and macros, etc, in 11 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are 12 | # run as spec files by default. This means that files in spec/support that end 13 | # in _spec.rb will both be required and run as specs, causing the specs to be 14 | # run twice. It is recommended that you do not name files matching this glob to 15 | # end with _spec.rb. You can configure this pattern with the --pattern 16 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. 17 | # 18 | # The following line is provided for convenience purposes. It has the downside 19 | # of increasing the boot-up time by auto-requiring all files in the support 20 | # directory. Alternatively, in the individual `*_spec.rb` files, manually 21 | # require only the support files necessary. 22 | # 23 | Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } 24 | 25 | # Checks for pending migrations and applies them before tests are run. 26 | # If you are not using ActiveRecord, you can remove this line. 27 | ActiveRecord::Migration.maintain_test_schema! 28 | 29 | RSpec.configure do |config| 30 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 31 | config.fixture_path = "#{::Rails.root}/spec/fixtures" 32 | 33 | # If you're not using ActiveRecord, or you'd prefer not to run each of your 34 | # examples within a transaction, remove the following line or assign false 35 | # instead of true. 36 | config.use_transactional_fixtures = true 37 | config.include FactoryBot::Syntax::Methods 38 | config.include JsonApiHelpers 39 | # RSpec Rails can automatically mix in different behaviours to your tests 40 | # based on their file location, for example enabling you to call `get` and 41 | # `post` in specs under `spec/controllers`. 42 | # 43 | # You can disable this behaviour by removing the line below, and instead 44 | # explicitly tag your specs with their type, e.g.: 45 | # 46 | # RSpec.describe UsersController, :type => :controller do 47 | # # ... 48 | # end 49 | # 50 | # The different available types are documented in the features, such as in 51 | # https://relishapp.com/rspec/rspec-rails/docs 52 | config.infer_spec_type_from_file_location! 53 | 54 | # Filter lines from Rails gems in backtraces. 55 | config.filter_rails_from_backtrace! 56 | # arbitrary gems may also be filtered via: 57 | # config.filter_gems_from_backtrace("gem name") 58 | end 59 | -------------------------------------------------------------------------------- /spec/routing/access_tokens_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | describe 'access tokens routes' do 4 | it 'should route to access_tokens create action' do 5 | expect(post '/login').to route_to('access_tokens#create') 6 | end 7 | 8 | it 'should route to access_tokens destroy action' do 9 | expect(delete '/logout').to route_to('access_tokens#destroy') 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /spec/routing/articles_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | describe 'articles routes' do 4 | it 'should route to articles index' do 5 | expect(get '/articles').to route_to('articles#index') 6 | end 7 | 8 | it 'should route to articles show' do 9 | expect(get '/articles/1').to route_to('articles#show', id: '1') 10 | end 11 | 12 | it 'should route to articles create' do 13 | expect(post '/articles').to route_to('articles#create') 14 | end 15 | 16 | it 'should route to articles update' do 17 | expect(put '/articles/1').to route_to('articles#update', id: '1') 18 | expect(patch '/articles/1').to route_to('articles#update', id: '1') 19 | end 20 | 21 | it 'should route to articles destroy' do 22 | expect(delete '/articles/1').to route_to('articles#destroy', id: '1') 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /spec/routing/comments_routing_spec.rb: -------------------------------------------------------------------------------- 1 | require "rails_helper" 2 | 3 | RSpec.describe CommentsController, type: :routing do 4 | describe "routing" do 5 | it "routes to #index" do 6 | expect(:get => "articles/1/comments").to route_to("comments#index", article_id: '1') 7 | end 8 | 9 | it "routes to #create" do 10 | expect(:post => "articles/1/comments").to route_to("comments#create", article_id: '1') 11 | end 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /spec/routing/registrations_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | describe 'registration routes' do 4 | it 'should route to registrations#create' do 5 | expect(post '/sign_up').to route_to('registrations#create') 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /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/json_api_helpers.rb: -------------------------------------------------------------------------------- 1 | module JsonApiHelpers 2 | def json 3 | JSON.parse(response.body) 4 | end 5 | 6 | def json_data 7 | json["data"] 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /spec/support/shared/json_errors.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | shared_examples_for "unauthorized_standard_requests" do 4 | let(:authentication_error) do 5 | { 6 | "status" => "401", 7 | "source" => { "pointer" => "/data/attributes/password" }, 8 | "title" => "Invalid login or password", 9 | "detail" => "You must provide valid credentials in order to exchange them for token." 10 | } 11 | end 12 | 13 | it 'should return 401 status code' do 14 | subject 15 | expect(response).to have_http_status(401) 16 | end 17 | 18 | it 'should return proper error body' do 19 | subject 20 | expect(json['errors']).to include(authentication_error) 21 | end 22 | end 23 | 24 | shared_examples_for "unauthorized_oauth_requests" do 25 | let(:authentication_error) do 26 | { 27 | "status" => "401", 28 | "source" => { "pointer" => "/code" }, 29 | "title" => "Authentication code is invalid", 30 | "detail" => "You must provide valid code in order to exchange it for token." 31 | } 32 | end 33 | 34 | it 'should return 401 status code' do 35 | subject 36 | expect(response).to have_http_status(401) 37 | end 38 | 39 | it 'should return proper error body' do 40 | subject 41 | expect(json['errors']).to include(authentication_error) 42 | end 43 | end 44 | 45 | shared_examples_for 'forbidden_requests' do 46 | let(:authorization_error) do 47 | { 48 | "status" => "403", 49 | "source" => { "pointer" => "/headers/authorization" }, 50 | "title" => "Not authorized", 51 | "detail" => "You have no right to access this resource." 52 | } 53 | end 54 | 55 | it 'should return 403 status code' do 56 | subject 57 | expect(response).to have_http_status(:forbidden) 58 | end 59 | 60 | it 'should return proper error json' do 61 | subject 62 | expect(json['errors']).to include(authorization_error) 63 | end 64 | end 65 | -------------------------------------------------------------------------------- /tmp/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/driggl/rails-api-complete-guide/df79b4536c3a54cd9840353d693991df65eb2b85/tmp/.keep -------------------------------------------------------------------------------- /vendor/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/driggl/rails-api-complete-guide/df79b4536c3a54cd9840353d693991df65eb2b85/vendor/.keep --------------------------------------------------------------------------------