├── log └── .keep ├── storage └── .keep ├── tmp ├── .keep └── pids │ └── .keep ├── vendor └── .keep ├── lib └── tasks │ └── .keep ├── .ruby-version ├── app ├── models │ ├── concerns │ │ └── .keep │ ├── application_record.rb │ └── user.rb ├── controllers │ ├── concerns │ │ ├── .keep │ │ └── renderer.rb │ ├── application_controller.rb │ ├── api │ │ └── v1 │ │ │ ├── base_controller.rb │ │ │ └── users_controller.rb │ ├── swagger_controller.rb │ ├── swagger │ │ ├── models │ │ │ ├── meta.rb │ │ │ ├── unauthorized.rb │ │ │ ├── user_input.rb │ │ │ ├── oauth_token_input.rb │ │ │ ├── error.rb │ │ │ ├── oauth_token.rb │ │ │ ├── user.rb │ │ │ └── oauth_token_info.rb │ │ └── controllers │ │ │ ├── users_controller.rb │ │ │ └── oauth_token_controller.rb │ └── apidocs_controller.rb ├── views │ └── layouts │ │ ├── mailer.text.erb │ │ ├── mailer.html.erb │ │ └── swagger.html.erb ├── serializers │ ├── user_serializer.rb │ └── base_serializer.rb ├── mailers │ └── application_mailer.rb └── jobs │ └── application_job.rb ├── .rspec ├── public └── robots.txt ├── bin ├── rake ├── rails ├── setup └── bundle ├── config.ru ├── config ├── environment.rb ├── initializers │ ├── mime_types.rb │ ├── filter_parameter_logging.rb │ ├── application_controller_renderer.rb │ ├── cors.rb │ ├── backtrace_silencers.rb │ ├── wrap_parameters.rb │ ├── inflections.rb │ ├── devise.rb │ └── doorkeeper.rb ├── boot.rb ├── credentials.yml.enc ├── routes.rb ├── locales │ ├── en.yml │ ├── devise.en.yml │ └── doorkeeper.en.yml ├── storage.yml ├── application.rb ├── puma.rb ├── environments │ ├── test.rb │ ├── development.rb │ └── production.rb └── database.yml ├── spec ├── factories │ └── users.rb ├── support │ └── json_helpers.rb ├── serializers │ ├── user_serializer_spec.rb │ └── base_serializer_spec.rb ├── models │ └── user_spec.rb ├── requests │ └── api │ │ └── v1 │ │ └── users_spec.rb ├── concerns │ └── renderer_spec.rb ├── rails_helper.rb └── spec_helper.rb ├── Rakefile ├── db ├── seeds.rb ├── migrate │ ├── 20200704195412_devise_create_users.rb │ └── 20200906143918_create_doorkeeper_tables.rb └── schema.rb ├── .rubocop.yml ├── .gitignore ├── README.md ├── .rubocop_todo.yml ├── Gemfile └── Gemfile.lock /log/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /storage/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tmp/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /vendor/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lib/tasks/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tmp/pids/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | 2.6.5 2 | -------------------------------------------------------------------------------- /app/models/concerns/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --require spec_helper 2 | -------------------------------------------------------------------------------- /app/controllers/concerns/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.text.erb: -------------------------------------------------------------------------------- 1 | <%= yield %> 2 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | -------------------------------------------------------------------------------- /app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationController < ActionController::API 4 | end 5 | -------------------------------------------------------------------------------- /app/serializers/user_serializer.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class UserSerializer < BaseSerializer 4 | attributes :email 5 | end 6 | -------------------------------------------------------------------------------- /bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | require_relative '../config/boot' 5 | require 'rake' 6 | Rake.application.run 7 | -------------------------------------------------------------------------------- /app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationRecord < ActiveRecord::Base 4 | self.abstract_class = true 5 | end 6 | -------------------------------------------------------------------------------- /app/controllers/api/v1/base_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Api::V1::BaseController < ApplicationController 4 | include Renderer 5 | end 6 | -------------------------------------------------------------------------------- /app/serializers/base_serializer.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class BaseSerializer < ActiveModel::Serializer 4 | attributes :id, :created_at, :updated_at 5 | end 6 | -------------------------------------------------------------------------------- /app/mailers/application_mailer.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationMailer < ActionMailer::Base 4 | default from: 'from@example.com' 5 | layout 'mailer' 6 | end 7 | -------------------------------------------------------------------------------- /config.ru: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # This file is used by Rack-based servers to start the application. 4 | 5 | require_relative 'config/environment' 6 | 7 | run Rails.application 8 | -------------------------------------------------------------------------------- /app/controllers/swagger_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class SwaggerController < ActionController::Base 4 | def index 5 | render html: nil, layout: 'swagger' 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | APP_PATH = File.expand_path('../config/application', __dir__) 5 | require_relative '../config/boot' 6 | require 'rails/commands' 7 | -------------------------------------------------------------------------------- /config/environment.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Load the Rails application. 4 | require_relative 'application' 5 | 6 | # Initialize the Rails application. 7 | Rails.application.initialize! 8 | -------------------------------------------------------------------------------- /spec/factories/users.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | FactoryBot.define do 4 | factory :user do 5 | sequence(:email) { |n| "user_#{n}@duetcode.io" } 6 | password { 'samplepassword' } 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | # Be sure to restart your server when you modify this file. 3 | 4 | # Add new mime types for use in respond_to blocks: 5 | # Mime::Type.register "text/richtext", :rtf 6 | -------------------------------------------------------------------------------- /config/boot.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 4 | 5 | require 'bundler/setup' # Set up gems listed in the Gemfile. 6 | require 'bootsnap/setup' # Speed up boot time by caching expensive operations. 7 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Add your own tasks in files placed in lib/tasks ending in .rake, 4 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 5 | 6 | require_relative 'config/application' 7 | 8 | Rails.application.load_tasks 9 | -------------------------------------------------------------------------------- /config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # Configure sensitive parameters which will be filtered from the log file. 6 | Rails.application.config.filter_parameters += [:password] 7 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | -------------------------------------------------------------------------------- /config/initializers/application_controller_renderer.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | # Be sure to restart your server when you modify this file. 3 | 4 | # ActiveSupport::Reloader.to_prepare do 5 | # ApplicationController.renderer.defaults.merge!( 6 | # http_host: 'example.org', 7 | # https: false 8 | # ) 9 | # end 10 | -------------------------------------------------------------------------------- /config/initializers/cors.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.config.middleware.insert_before 0, Rack::Cors do 4 | allow do 5 | origins 'http://localhost:8080' 6 | resource '/api/v1/*', 7 | headers: :any, 8 | methods: %i[get post put patch delete options head] 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /app/jobs/application_job.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApplicationJob < ActiveJob::Base 4 | # Automatically retry jobs that encountered a deadlock 5 | # retry_on ActiveRecord::Deadlocked 6 | 7 | # Most jobs are safe to ignore if the underlying records are no longer available 8 | # discard_on ActiveJob::DeserializationError 9 | end 10 | -------------------------------------------------------------------------------- /app/controllers/swagger/models/meta.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Swagger::Models::Meta 4 | include Swagger::Blocks 5 | 6 | swagger_schema :Meta do 7 | key :type, :object 8 | key :required, %i[resource count] 9 | 10 | property :resource do 11 | key :type, :string 12 | end 13 | 14 | property :count do 15 | key :type, :integer 16 | end 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /db/seeds.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | # This file should contain all the record creation needed to seed the database with its default values. 3 | # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). 4 | # 5 | # Examples: 6 | # 7 | # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) 8 | # Character.create(name: 'Luke', movie: movies.first) 9 | -------------------------------------------------------------------------------- /spec/support/json_helpers.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module JsonHelpers 4 | def load_body(response) 5 | JSON.parse(response.body) 6 | end 7 | 8 | def load_body_data(response) 9 | load_body(response)['data'] 10 | end 11 | 12 | def load_body_meta(response) 13 | load_body(response)['meta'] 14 | end 15 | 16 | def load_body_errors(response) 17 | load_body(response)['errors'] 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /app/controllers/api/v1/users_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Api::V1::UsersController < Api::V1::BaseController 4 | def create 5 | @user = User.new(user_params) 6 | 7 | if @user.save 8 | return render_object(@user, status: :created) 9 | end 10 | 11 | render_errors(@user.errors) 12 | end 13 | 14 | private 15 | 16 | def user_params 17 | params.require(:user).permit(:email, :password) 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /config/credentials.yml.enc: -------------------------------------------------------------------------------- 1 | dBXqC0a/zDV7PYalqMTr52w/yAMwiw4Y8Zmi73fbD3TkSpiPPjOmJD1NrBnI8m7IiA/ky4EV4QgPp0sPov2kHPR9kVQvJ16ykqelAavzqfDA6javXoH1z9Vr4/s89Ls16uaJISSkKRsUpybk2uwVK1C9zDAKqYu5JWXMhb04XRFDS+05uUKxCJnjLUYB/bseCBaoOMz9DmGvfRLkCvzwH6khBrDE9Hy6d2Da4Qp2KH10nmyrPVYZjewqAuUhi78Hwggqdxps/rgfeUWk3gTfPorg+JPgs2CLMV7r0WHfquB5mFW/QoDK+brtEFRaenhEihPOlRrOyj8gg83ruKxU47KA4D6uKchmZJN05IW4rlQjhJRsn7lurYt0UeFr/bvxvSSxf8ALFjzqp9DEiNPoGvtTlGVgAvkj/6B8--GsoaFgSztZ8qJomw--ZKSmXXG3yFIklTT8d+DH/g== -------------------------------------------------------------------------------- /app/controllers/swagger/models/unauthorized.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Swagger::Models::Unauthorized 4 | include Swagger::Blocks 5 | 6 | swagger_schema :Unauthorized do 7 | key :type, :object 8 | 9 | property :error do 10 | key :type, :string 11 | end 12 | 13 | property :error_description do 14 | key :type, :string 15 | end 16 | 17 | property :state do 18 | key :type, :string 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | # Be sure to restart your server when you modify this file. 3 | 4 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 5 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 6 | 7 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 8 | # Rails.backtrace_cleaner.remove_silencers! 9 | -------------------------------------------------------------------------------- /spec/serializers/user_serializer_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'rails_helper' 4 | 5 | RSpec.describe UserSerializer, type: :serializer do 6 | let(:user) { FactoryBot.build(:user, email: 'user@duetcode.io') } 7 | let(:serialized_user) { described_class.new(user).as_json } 8 | 9 | subject { serialized_user[:user] } 10 | 11 | it 'has an email that matches with the user email' do 12 | expect(subject[:email]).to eq('user@duetcode.io') 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /app/controllers/swagger/models/user_input.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Swagger::Models::UserInput 4 | include Swagger::Blocks 5 | 6 | swagger_schema :UserInput do 7 | key :required, %i[user] 8 | property :user do 9 | key :type, :object 10 | key :required, %i[email password] 11 | 12 | property :email do 13 | key :type, :string 14 | end 15 | 16 | property :password do 17 | key :type, :string 18 | end 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | inherit_from: .rubocop_todo.yml 2 | 3 | Metrics/MethodLength: 4 | Max: 7 5 | Exclude: 6 | - 'bin/bundle' 7 | - 'db/migrate/*' 8 | 9 | Style/Documentation: 10 | Enabled: false 11 | 12 | Style/ClassAndModuleChildren: 13 | Enabled: false 14 | 15 | Style/IfUnlessModifier: 16 | Enabled: false 17 | 18 | Metrics/BlockLength: 19 | Exclude: 20 | - 'spec/**/*' 21 | - 'app/controllers/swagger/**/*' 22 | 23 | AllCops: 24 | Exclude: 25 | - 'db/migrate/**/*' 26 | - 'db/schema.rb' 27 | -------------------------------------------------------------------------------- /app/controllers/swagger/models/oauth_token_input.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Swagger::Models::OauthTokenInput 4 | include Swagger::Blocks 5 | 6 | swagger_schema :OauthTokenInput do 7 | key :type, :object 8 | key :required, %i[email password grant_type] 9 | 10 | property :email do 11 | key :type, :string 12 | end 13 | 14 | property :password do 15 | key :type, :string 16 | end 17 | 18 | property :grant_type do 19 | key :type, :string 20 | end 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /app/models/user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class User < ApplicationRecord 4 | # Include default devise modules. Others available are: 5 | # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable 6 | devise :database_authenticatable, :registerable, 7 | :recoverable, :rememberable, :validatable 8 | 9 | class << self 10 | def authenticate(email, password) 11 | user = User.find_for_authentication(email: email) 12 | user.try(:valid_password?, password) ? user : nil 13 | end 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.routes.draw do 4 | # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html 5 | 6 | scope 'api/v1' do 7 | use_doorkeeper do 8 | skip_controllers :authorizations, :applications, :authorized_applications 9 | end 10 | end 11 | 12 | namespace :api do 13 | namespace :v1 do 14 | resources :users, only: [:create] 15 | end 16 | end 17 | 18 | resources :apidocs, only: [:index] 19 | resources :swagger, only: [:index] 20 | end 21 | -------------------------------------------------------------------------------- /config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Be sure to restart your server when you modify this file. 4 | 5 | # This file contains settings for ActionController::ParamsWrapper which 6 | # is enabled by default. 7 | 8 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 9 | ActiveSupport.on_load(:action_controller) do 10 | wrap_parameters format: [:json] 11 | end 12 | 13 | # To enable root element in JSON for ActiveRecord objects. 14 | # ActiveSupport.on_load(:active_record) do 15 | # self.include_root_in_json = true 16 | # end 17 | -------------------------------------------------------------------------------- /app/controllers/swagger/models/error.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Swagger::Models::Error 4 | include Swagger::Blocks 5 | 6 | swagger_schema :Error do 7 | key :required, [:errors] 8 | property :errors do 9 | key :type, :object 10 | 11 | property :field_name_one do 12 | key :type, :array 13 | 14 | items do 15 | key :type, :string 16 | end 17 | end 18 | 19 | property :field_name_two do 20 | key :type, :array 21 | 22 | items do 23 | key :type, :string 24 | end 25 | end 26 | end 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /app/controllers/swagger/models/oauth_token.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Swagger::Models::OauthToken 4 | include Swagger::Blocks 5 | 6 | swagger_schema :OauthToken do 7 | key :type, :object 8 | key :required, %i[access_token token_type expires_in created_at] 9 | 10 | property :access_token do 11 | key :type, :string 12 | end 13 | 14 | property :token_type do 15 | key :type, :string 16 | end 17 | 18 | property :expires_in do 19 | key :type, :integer 20 | end 21 | 22 | property :created_at do 23 | key :type, :string 24 | key :format, 'date-time' 25 | end 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /app/controllers/swagger/models/user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Swagger::Models::User 4 | include Swagger::Blocks 5 | 6 | swagger_schema :User do 7 | key :type, :object 8 | key :required, %i[id email created_at updated_at] 9 | 10 | property :id do 11 | key :type, :integer 12 | key :format, :int64 13 | end 14 | 15 | property :email do 16 | key :type, :string 17 | end 18 | 19 | property :created_at do 20 | key :type, :string 21 | key :format, 'date-time' 22 | end 23 | 24 | property :updated_at do 25 | key :type, :string 26 | key :format, 'date-time' 27 | end 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /spec/serializers/base_serializer_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'rails_helper' 4 | 5 | RSpec.describe BaseSerializer, type: :serializer do 6 | let(:resource) { create(:user) } 7 | let(:serialized_resource) { described_class.new(resource).as_json } 8 | 9 | subject { serialized_resource[:base] } 10 | 11 | it 'has an ID that matches with resource ID' do 12 | expect(subject[:id]).to eq(resource.id) 13 | end 14 | 15 | it 'has a created date time of the resource' do 16 | expect(subject[:created_at]).to eq(resource.created_at) 17 | end 18 | 19 | it 'has an updated date time of the resource' do 20 | expect(subject[:updated_at]).to eq(resource.updated_at) 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /spec/models/user_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'rails_helper' 4 | 5 | RSpec.describe User, type: :model do 6 | describe 'validations' do 7 | it { should validate_presence_of(:email) } 8 | it { should validate_presence_of(:password) } 9 | end 10 | 11 | describe '#authenticate' do 12 | let(:user) do 13 | create(:user, email: 'user@duetcode.io', password: 'sample') 14 | end 15 | 16 | it 'returns user when the credentials are correct' do 17 | expect(User.authenticate(user.email, user.password)).to eq(user) 18 | end 19 | 20 | it 'returns nil when the credentials are not correct' do 21 | expect(User.authenticate(user.email, 'wrong')).to be_nil 22 | end 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /db/migrate/20200704195412_devise_create_users.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class DeviseCreateUsers < ActiveRecord::Migration[6.0] 4 | def change 5 | create_table :users do |t| 6 | ## Database authenticatable 7 | t.string :email, null: false, default: '' 8 | t.string :encrypted_password, null: false, default: '' 9 | 10 | ## Recoverable 11 | t.string :reset_password_token 12 | t.datetime :reset_password_sent_at 13 | 14 | ## Rememberable 15 | t.datetime :remember_created_at 16 | t.timestamps null: false 17 | end 18 | 19 | add_index :users, :email, unique: true 20 | add_index :users, :reset_password_token, unique: true 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /app/controllers/concerns/renderer.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Renderer 4 | def render_object(resource, **options) 5 | options.merge!(json: resource, root: :data) 6 | options.merge!(status: :ok) unless options.key?(:status) 7 | options.merge!(meta: assign_metadata(resource)) 8 | 9 | render options 10 | end 11 | 12 | def render_errors(errors, status = :unprocessable_entity) 13 | render json: { errors: errors.messages }, status: status 14 | end 15 | 16 | private 17 | 18 | def assign_metadata(resource) 19 | count = resource.respond_to?(:count) ? resource.count : 1 20 | resource_name = (resource.try(:first)&.class || resource.class).to_s 21 | 22 | { resource: resource_name, count: count } 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | # Be sure to restart your server when you modify this file. 3 | 4 | # Add new inflection rules using the following format. Inflections 5 | # are locale specific, and you may define rules for as many different 6 | # locales as you wish. All of these examples are active by default: 7 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 8 | # inflect.plural /^(ox)$/i, '\1en' 9 | # inflect.singular /^(ox)en/i, '\1' 10 | # inflect.irregular 'person', 'people' 11 | # inflect.uncountable %w( fish sheep ) 12 | # end 13 | 14 | # These inflection rules are supported but not enabled by default: 15 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 16 | # inflect.acronym 'RESTful' 17 | # end 18 | -------------------------------------------------------------------------------- /db/migrate/20200906143918_create_doorkeeper_tables.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class CreateDoorkeeperTables < ActiveRecord::Migration[6.0] 4 | def change 5 | create_table :oauth_access_tokens do |t| 6 | t.references :resource_owner, index: true 7 | t.references :application 8 | 9 | t.string :token, null: false 10 | t.string :refresh_token 11 | t.integer :expires_in 12 | t.datetime :revoked_at 13 | t.datetime :created_at, null: false 14 | t.string :scopes 15 | 16 | t.string :previous_refresh_token, null: false, default: '' 17 | end 18 | 19 | add_index :oauth_access_tokens, :token, unique: true 20 | add_index :oauth_access_tokens, :refresh_token, unique: true 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /app/controllers/swagger/models/oauth_token_info.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Swagger::Models::OauthTokenInfo 4 | include Swagger::Blocks 5 | 6 | swagger_schema :OauthTokenInfo do 7 | key :type, :object 8 | key :required, %i[resource_owner_id scope expires_in created_at] 9 | 10 | property :resource_owner_id do 11 | key :type, :integer 12 | key :format, :int64 13 | end 14 | 15 | property :scope do 16 | key :type, :array 17 | 18 | items do 19 | key :type, :string 20 | end 21 | end 22 | 23 | property :expires_in do 24 | key :type, :integer 25 | end 26 | 27 | property :created_at do 28 | key :type, :integer 29 | key :format, :int64 30 | end 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files for more about ignoring files. 2 | # 3 | # If you find yourself ignoring temporary files generated by your text editor 4 | # or operating system, you probably want to add a global ignore instead: 5 | # git config --global core.excludesfile '~/.gitignore_global' 6 | 7 | # Ignore bundler config. 8 | /.bundle 9 | 10 | # Ignore all logfiles and tempfiles. 11 | /log/* 12 | /tmp/* 13 | !/log/.keep 14 | !/tmp/.keep 15 | 16 | # Ignore pidfiles, but keep the directory. 17 | /tmp/pids/* 18 | !/tmp/pids/ 19 | !/tmp/pids/.keep 20 | 21 | # Ignore uploaded files in development. 22 | /storage/* 23 | !/storage/.keep 24 | .byebug_history 25 | 26 | # Ignore master key for decrypting credentials and more. 27 | /config/master.key 28 | -------------------------------------------------------------------------------- /config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Files in the config/locales directory are used for internationalization 2 | # and are automatically loaded by Rails. If you want to use locales other 3 | # than English, add the necessary files in this directory. 4 | # 5 | # To use the locales, use `I18n.t`: 6 | # 7 | # I18n.t 'hello' 8 | # 9 | # In views, this is aliased to just `t`: 10 | # 11 | # <%= t('hello') %> 12 | # 13 | # To use a different locale, set it with `I18n.locale`: 14 | # 15 | # I18n.locale = :es 16 | # 17 | # This would use the information in config/locales/es.yml. 18 | # 19 | # The following keys must be escaped otherwise they will not be retrieved by 20 | # the default I18n backend: 21 | # 22 | # true, false, on, off, yes, no 23 | # 24 | # Instead, surround them with single quotes. 25 | # 26 | # en: 27 | # 'true': 'foo' 28 | # 29 | # To learn more, please read the Rails Internationalization guide 30 | # available at https://guides.rubyonrails.org/i18n.html. 31 | 32 | en: 33 | hello: "Hello world" 34 | -------------------------------------------------------------------------------- /spec/requests/api/v1/users_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'rails_helper' 4 | 5 | RSpec.describe 'Api::V1::Users', type: :request do 6 | describe 'POST /api/v1/users' do 7 | let(:user_params) do 8 | { email: 'user@duetcode.io', password: 'samplepassword' } 9 | end 10 | 11 | it 'creates a new user' do 12 | post api_v1_users_path, params: { user: user_params } 13 | expected_data = { 'email' => 'user@duetcode.io' } 14 | 15 | expect(response).to have_http_status(:created) 16 | expect(load_body_data(response)).to include(expected_data) 17 | end 18 | 19 | it 'returns unprocessable entity with errors' do 20 | user_params[:password] = nil 21 | post api_v1_users_path, params: { user: user_params } 22 | 23 | expected_error = { 'password' => ['can\'t be blank'] } 24 | 25 | expect(response).to have_http_status(:unprocessable_entity) 26 | expect(load_body_errors(response)).to eq(expected_error) 27 | end 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Bookmarker 2 | 3 | Bookmarker repository shows the source code of the application that we build with API-only rails course from [duetcode.io](https://duetcode.io/rails-api-only-course) 4 | 5 | ## Chapters 6 | 7 | - Chapter 1 (Introduction page without any code) 8 | - [Chapter 2](https://github.com/duetcode/bookmarker/commits/chapter-2) 9 | - [Chapter 3](https://github.com/duetcode/bookmarker/commits/chapter-3) 10 | - [Chapter 4](https://github.com/duetcode/bookmarker/commits/chapter-4) 11 | - [Chapter 5](https://github.com/duetcode/bookmarker/commits/chapter-5) 12 | - [Chapter 6](https://github.com/duetcode/bookmarker/commits/chapter-6) 13 | - [Chapter 7](https://github.com/duetcode/bookmarker/commits/chapter-7) 14 | - [Chapter 8](https://github.com/duetcode/bookmarker/commits/chapter-8) 15 | - [Chapter 9](https://github.com/duetcode/bookmarker/commits/chapter-9) 16 | - [Chapter 10](https://github.com/duetcode/bookmarker/commits/chapter-10) 17 | - [Chapter 11](https://github.com/duetcode/bookmarker/commits/chapter-11) 18 | -------------------------------------------------------------------------------- /.rubocop_todo.yml: -------------------------------------------------------------------------------- 1 | # This configuration was generated by 2 | # `rubocop --auto-gen-config` 3 | # on 2020-06-24 21:54:26 +0200 using RuboCop version 0.85.1. 4 | # The point is for the user to remove these configuration records 5 | # one by one as the offenses are removed from the code base. 6 | # Note that changes in the inspected code, or installation of new 7 | # versions of RuboCop, may require this file to be generated again. 8 | 9 | # Offense count: 1 10 | # Configuration parameters: IgnoredMethods. 11 | Metrics/AbcSize: 12 | Max: 17 13 | 14 | # Offense count: 1 15 | # Configuration parameters: IgnoredMethods. 16 | Metrics/CyclomaticComplexity: 17 | Max: 8 18 | 19 | # Offense count: 1 20 | # Configuration parameters: IgnoredMethods. 21 | Metrics/PerceivedComplexity: 22 | Max: 8 23 | 24 | # Offense count: 1 25 | # Cop supports --auto-correct. 26 | # Configuration parameters: AutoCorrect, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. 27 | # URISchemes: http, https 28 | Layout/LineLength: 29 | Max: 198 30 | -------------------------------------------------------------------------------- /app/controllers/swagger/controllers/users_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Swagger::Controllers::UsersController 4 | include Swagger::Blocks 5 | 6 | swagger_path '/users' do 7 | operation :post do 8 | key :description, 'Creates a new user in the system' 9 | key :tags, [ 10 | 'user' 11 | ] 12 | 13 | parameter do 14 | key :name, :user 15 | key :in, :body 16 | key :description, 'Email and password information of the new user' 17 | key :required, true 18 | schema do 19 | key :'$ref', :UserInput 20 | end 21 | end 22 | 23 | response 201 do 24 | key :description, 'User created' 25 | schema do 26 | property :data do 27 | key :'$ref', :User 28 | end 29 | 30 | property :meta do 31 | key :'$ref', :Meta 32 | end 33 | end 34 | end 35 | 36 | response 422 do 37 | key :description, 'Unprocessable Entity' 38 | schema do 39 | key :'$ref', :Error 40 | end 41 | end 42 | end 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | require 'fileutils' 5 | 6 | # path to your application root. 7 | APP_ROOT = File.expand_path('..', __dir__) 8 | 9 | def system!(*args) 10 | system(*args) || abort("\n== Command #{args} failed ==") 11 | end 12 | 13 | FileUtils.chdir APP_ROOT do 14 | # This script is a way to setup or update your development environment automatically. 15 | # This script is idempotent, so that you can run it at anytime and get an expectable outcome. 16 | # Add necessary setup steps to this file. 17 | 18 | puts '== Installing dependencies ==' 19 | system! 'gem install bundler --conservative' 20 | system('bundle check') || system!('bundle install') 21 | 22 | # puts "\n== Copying sample files ==" 23 | # unless File.exist?('config/database.yml') 24 | # FileUtils.cp 'config/database.yml.sample', 'config/database.yml' 25 | # end 26 | 27 | puts "\n== Preparing database ==" 28 | system! 'bin/rails db:prepare' 29 | 30 | puts "\n== Removing old logs and tempfiles ==" 31 | system! 'bin/rails log:clear tmp:clear' 32 | 33 | puts "\n== Restarting application server ==" 34 | system! 'bin/rails restart' 35 | end 36 | -------------------------------------------------------------------------------- /app/controllers/apidocs_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class ApidocsController < ActionController::Base 4 | include Swagger::Blocks 5 | 6 | swagger_root do 7 | key :swagger, '2.0' 8 | 9 | info do 10 | key :version, '1.0.0' 11 | key :title, 'Bookmarker API' 12 | key :description, 'Bookmarker API documentation' 13 | 14 | contact do 15 | key :name, 'duetcode.io' 16 | end 17 | end 18 | 19 | key :host, 'localhost:3000' 20 | key :basePath, '/api/v1' 21 | key :consumes, ['application/json'] 22 | key :produces, ['application/json'] 23 | key :schemes, ['http'] 24 | end 25 | 26 | # A list of all classes that have swagger_* declarations. 27 | SWAGGERED_CLASSES = [ 28 | Swagger::Controllers::UsersController, 29 | Swagger::Controllers::OauthTokenController, 30 | Swagger::Models::Error, 31 | Swagger::Models::Meta, 32 | Swagger::Models::User, 33 | Swagger::Models::UserInput, 34 | Swagger::Models::OauthTokenInput, 35 | Swagger::Models::OauthToken, 36 | self 37 | ].freeze 38 | 39 | def index 40 | render json: Swagger::Blocks.build_root_json(SWAGGERED_CLASSES) 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /config/application.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative 'boot' 4 | 5 | require 'rails' 6 | # Pick the frameworks you want: 7 | require 'active_model/railtie' 8 | require 'active_job/railtie' 9 | require 'active_record/railtie' 10 | require 'active_storage/engine' 11 | require 'action_controller/railtie' 12 | require 'action_mailer/railtie' 13 | # require "action_mailbox/engine" 14 | require 'action_text/engine' 15 | require 'action_view/railtie' 16 | # require "action_cable/engine" 17 | # require "sprockets/railtie" 18 | # require "rails/test_unit/railtie" 19 | 20 | # Require the gems listed in Gemfile, including any gems 21 | # you've limited to :test, :development, or :production. 22 | Bundler.require(*Rails.groups) 23 | 24 | module Bookmarker 25 | class Application < Rails::Application 26 | # Initialize configuration defaults for originally generated Rails version. 27 | config.load_defaults 6.0 28 | 29 | # Settings in config/environments/* take precedence over those specified here. 30 | # Application configuration can go into files in config/initializers 31 | # -- all .rb files in that directory are automatically loaded after loading 32 | # the framework and any gems in your application. 33 | 34 | # Only loads a smaller set of middleware suitable for API only apps. 35 | # Middleware like session, flash, cookies can be added back manually. 36 | # Skip views, helpers and assets when generating a new resource. 37 | config.api_only = true 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /app/views/layouts/swagger.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Swagger UI 5 | 6 | 27 | 28 | 29 | 30 |
31 | 32 | 33 | 34 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /config/puma.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Puma can serve each request in a thread from an internal thread pool. 4 | # The `threads` method setting takes two numbers: a minimum and maximum. 5 | # Any libraries that use thread pools should be configured to match 6 | # the maximum value specified for Puma. Default is set to 5 threads for minimum 7 | # and maximum; this matches the default thread size of Active Record. 8 | # 9 | max_threads_count = ENV.fetch('RAILS_MAX_THREADS') { 5 } 10 | min_threads_count = ENV.fetch('RAILS_MIN_THREADS') { max_threads_count } 11 | threads min_threads_count, max_threads_count 12 | 13 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000. 14 | # 15 | port ENV.fetch('PORT') { 3000 } 16 | 17 | # Specifies the `environment` that Puma will run in. 18 | # 19 | environment ENV.fetch('RAILS_ENV') { 'development' } 20 | 21 | # Specifies the `pidfile` that Puma will use. 22 | pidfile ENV.fetch('PIDFILE') { 'tmp/pids/server.pid' } 23 | 24 | # Specifies the number of `workers` to boot in clustered mode. 25 | # Workers are forked web server processes. If using threads and workers together 26 | # the concurrency of the application would be max `threads` * `workers`. 27 | # Workers do not work on JRuby or Windows (both of which do not support 28 | # processes). 29 | # 30 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 } 31 | 32 | # Use the `preload_app!` method when specifying a `workers` number. 33 | # This directive tells Puma to first boot the application and load code 34 | # before forking the application. This takes advantage of Copy On Write 35 | # process behavior so workers use less memory. 36 | # 37 | # preload_app! 38 | 39 | # Allow puma to be restarted by `rails restart` command. 40 | plugin :tmp_restart 41 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | source 'https://rubygems.org' 4 | git_source(:github) { |repo| "https://github.com/#{repo}.git" } 5 | 6 | ruby '2.6.5' 7 | 8 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' 9 | gem 'rails', '~> 6.0.3', '>= 6.0.3.2' 10 | # Use postgresql as the database for Active Record 11 | gem 'pg', '>= 0.18', '< 2.0' 12 | # Use Puma as the app server 13 | gem 'puma', '~> 4.1' 14 | # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder 15 | # gem 'jbuilder', '~> 2.7' 16 | # Use Active Model has_secure_password 17 | # gem 'bcrypt', '~> 3.1.7' 18 | 19 | # Use Active Storage variant 20 | # gem 'image_processing', '~> 1.2' 21 | 22 | # Generate JSON in an object-oriented and convention-driven manner 23 | gem 'active_model_serializers', '~> 0.8.4' 24 | 25 | # Reduces boot times through caching; required in config/boot.rb 26 | gem 'bootsnap', '>= 1.4.2', require: false 27 | 28 | # Flexible authentication solution for Rails based on Warden 29 | gem 'devise', '~> 4.7' 30 | 31 | # Rails engine to introduce OAuth 2 provider functionality 32 | gem 'doorkeeper', '~> 5.4' 33 | 34 | # Define and serve live-updating Swagger JSON for Ruby apps. 35 | gem 'swagger-blocks', '~> 3.0' 36 | 37 | # Use Rack CORS for handling Cross-Origin Resource Sharing (CORS) 38 | gem 'rack-cors', '~> 1.1' 39 | 40 | group :development, :test do 41 | # Call 'byebug' anywhere in the code to stop execution and get a debugger console 42 | gem 'byebug', platforms: %i[mri mingw x64_mingw] 43 | 44 | gem 'factory_bot_rails', '~> 5.2' 45 | gem 'rspec-rails', '~> 4.0' 46 | gem 'rubocop', '~> 0.85.1', require: false 47 | end 48 | 49 | group :test do 50 | gem 'shoulda-matchers', '~> 3.1' 51 | end 52 | 53 | group :development do 54 | gem 'listen', '~> 3.2' 55 | end 56 | 57 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem 58 | gem 'tzinfo-data', platforms: %i[mingw mswin x64_mingw jruby] 59 | -------------------------------------------------------------------------------- /app/controllers/swagger/controllers/oauth_token_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Swagger::Controllers::OauthTokenController 4 | include Swagger::Blocks 5 | 6 | swagger_path '/oauth/token' do 7 | operation :post do 8 | key :description, 'Creates a new token from user credentials' 9 | key :tags, [ 10 | 'oauth' 11 | ] 12 | 13 | parameter do 14 | key :name, :user_credentials 15 | key :in, :body 16 | key :description, 'Email and password information of the new user with grant type.' 17 | key :required, true 18 | schema do 19 | key :'$ref', :OauthTokenInput 20 | end 21 | end 22 | 23 | response 201 do 24 | key :description, 'Token created' 25 | schema do 26 | key :'$ref', :OauthToken 27 | end 28 | end 29 | 30 | response 400 do 31 | key :description, 'Bad Request' 32 | schema do 33 | key :type, :object 34 | 35 | property :error do 36 | key :type, :string 37 | end 38 | 39 | property :error_description do 40 | key :type, :string 41 | end 42 | end 43 | end 44 | end 45 | end 46 | 47 | swagger_path '/oauth/token/info' do 48 | operation :get do 49 | key :description, 'Show details about the token used for authentication' 50 | key :tags, [ 51 | 'oauth' 52 | ] 53 | 54 | parameter do 55 | key :name, :Authorization 56 | key :in, :header 57 | key :required, true 58 | schema do 59 | key :type, :string 60 | end 61 | end 62 | 63 | response 200 do 64 | key :description, 'Details about the specified token' 65 | schema do 66 | key :'$ref', :OauthTokenInfo 67 | end 68 | end 69 | 70 | response 401 do 71 | key :description, 'Unauthorized' 72 | schema do 73 | key :'$ref', :Unauthorized 74 | end 75 | end 76 | end 77 | end 78 | end 79 | -------------------------------------------------------------------------------- /spec/concerns/renderer_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'rails_helper' 4 | 5 | RSpec.describe Renderer, type: :controller do 6 | before do 7 | ActiveRecord::Base.connection.create_table :dummies, force: true do |t| 8 | t.string(:name) 9 | 10 | t.timestamps null: false 11 | end 12 | end 13 | 14 | after do 15 | ActiveRecord::Base.connection.drop_table(:dummies, if_exists: true) 16 | end 17 | 18 | class Dummy < ApplicationRecord 19 | validates :name, presence: true 20 | end 21 | 22 | class DummySerializer < BaseSerializer 23 | attributes :name 24 | end 25 | 26 | FactoryBot.define do 27 | factory :dummy do 28 | name { 'sample' } 29 | end 30 | end 31 | 32 | controller(ApplicationController) do 33 | include Renderer 34 | 35 | def show 36 | dummy = Dummy.find(params[:id]) 37 | render_object(dummy) 38 | end 39 | 40 | def create 41 | dummy = Dummy.create(dummy_params) 42 | render_errors(dummy.errors) 43 | end 44 | 45 | private 46 | 47 | def dummy_params 48 | params.require(:dummy).permit(:name) 49 | end 50 | end 51 | 52 | describe 'GET show' do 53 | let(:resource) { create(:dummy, name: 'sample') } 54 | 55 | it 'renders resource with render_object method' do 56 | get :show, params: { id: resource.id } 57 | 58 | data_fields = { 'id' => resource.id, 'name' => resource.name } 59 | meta_fields = { 'resource' => 'Dummy', 'count' => 1 } 60 | 61 | expect(response.status).to eq(200) 62 | expect(load_body_data(response)).to include(data_fields) 63 | expect(load_body_meta(response)).to include(meta_fields) 64 | end 65 | end 66 | 67 | describe 'POST create' do 68 | it 'renders resource errors with render_errors method' do 69 | post :create, params: { dummy: { name: nil } } 70 | 71 | error_fields = { 72 | 'name' => ['can\'t be blank'] 73 | } 74 | 75 | expect(response.status).to eq(422) 76 | expect(load_body_errors(response)).to eq(error_fields) 77 | end 78 | end 79 | end 80 | -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # The test environment is used exclusively to run your application's 4 | # test suite. You never need to work with it otherwise. Remember that 5 | # your test database is "scratch space" for the test suite and is wiped 6 | # and recreated between test runs. Don't rely on the data there! 7 | 8 | Rails.application.configure do 9 | # Settings specified here will take precedence over those in config/application.rb. 10 | 11 | config.cache_classes = true 12 | 13 | # Do not eager load code on boot. This avoids loading your whole application 14 | # just for the purpose of running a single test. If you are using a tool that 15 | # preloads Rails for running tests, you may have to set it to true. 16 | config.eager_load = false 17 | 18 | # Configure public file server for tests with Cache-Control for performance. 19 | config.public_file_server.enabled = true 20 | config.public_file_server.headers = { 21 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}" 22 | } 23 | 24 | # Show full error reports and disable caching. 25 | config.consider_all_requests_local = true 26 | config.action_controller.perform_caching = false 27 | config.cache_store = :null_store 28 | 29 | # Raise exceptions instead of rendering exception templates. 30 | config.action_dispatch.show_exceptions = false 31 | 32 | # Disable request forgery protection in test environment. 33 | config.action_controller.allow_forgery_protection = false 34 | 35 | # Store uploaded files on the local file system in a temporary directory. 36 | config.active_storage.service = :test 37 | 38 | config.action_mailer.perform_caching = false 39 | 40 | # Tell Action Mailer not to deliver emails to the real world. 41 | # The :test delivery method accumulates sent emails in the 42 | # ActionMailer::Base.deliveries array. 43 | config.action_mailer.delivery_method = :test 44 | 45 | # Print deprecation notices to the stderr. 46 | config.active_support.deprecation = :stderr 47 | 48 | # Raises error for missing translations. 49 | # config.action_view.raise_on_missing_translations = true 50 | end 51 | -------------------------------------------------------------------------------- /config/environments/development.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # In the development environment your application's code is reloaded on 7 | # every request. This slows down response time but is perfect for development 8 | # since you don't have to restart the web server when you make code changes. 9 | config.cache_classes = false 10 | 11 | # Do not eager load code on boot. 12 | config.eager_load = false 13 | 14 | # Show full error reports. 15 | config.consider_all_requests_local = true 16 | 17 | # Enable/disable caching. By default caching is disabled. 18 | # Run rails dev:cache to toggle caching. 19 | if Rails.root.join('tmp', 'caching-dev.txt').exist? 20 | config.cache_store = :memory_store 21 | config.public_file_server.headers = { 22 | 'Cache-Control' => "public, max-age=#{2.days.to_i}" 23 | } 24 | else 25 | config.action_controller.perform_caching = false 26 | 27 | config.cache_store = :null_store 28 | end 29 | 30 | # Store uploaded files on the local file system (see config/storage.yml for options). 31 | config.active_storage.service = :local 32 | 33 | # Don't care if the mailer can't send. 34 | config.action_mailer.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 | # Raises error for missing translations. 48 | # config.action_view.raise_on_missing_translations = true 49 | 50 | # Use an evented file watcher to asynchronously detect changes in source code, 51 | # routes, locales, etc. This feature depends on the listen gem. 52 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker 53 | 54 | config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } 55 | 56 | config.hosts << 'http://localhost:8080' 57 | end 58 | -------------------------------------------------------------------------------- /db/schema.rb: -------------------------------------------------------------------------------- 1 | # This file is auto-generated from the current state of the database. Instead 2 | # of editing this file, please use the migrations feature of Active Record to 3 | # incrementally modify your database, and then regenerate this schema definition. 4 | # 5 | # This file is the source Rails uses to define your schema when running `rails 6 | # db:schema:load`. When creating a new database, `rails db:schema:load` tends to 7 | # be faster and is potentially less error prone than running all of your 8 | # migrations from scratch. Old migrations may fail to apply correctly if those 9 | # migrations use external dependencies or application code. 10 | # 11 | # It's strongly recommended that you check this file into your version control system. 12 | 13 | ActiveRecord::Schema.define(version: 2020_09_06_143918) do 14 | 15 | # These are extensions that must be enabled in order to support this database 16 | enable_extension "plpgsql" 17 | 18 | create_table "oauth_access_tokens", force: :cascade do |t| 19 | t.bigint "resource_owner_id" 20 | t.bigint "application_id" 21 | t.string "token", null: false 22 | t.string "refresh_token" 23 | t.integer "expires_in" 24 | t.datetime "revoked_at" 25 | t.datetime "created_at", null: false 26 | t.string "scopes" 27 | t.string "previous_refresh_token", default: "", null: false 28 | t.index ["application_id"], name: "index_oauth_access_tokens_on_application_id" 29 | t.index ["refresh_token"], name: "index_oauth_access_tokens_on_refresh_token", unique: true 30 | t.index ["resource_owner_id"], name: "index_oauth_access_tokens_on_resource_owner_id" 31 | t.index ["token"], name: "index_oauth_access_tokens_on_token", unique: true 32 | end 33 | 34 | create_table "users", force: :cascade do |t| 35 | t.string "email", default: "", null: false 36 | t.string "encrypted_password", default: "", null: false 37 | t.string "reset_password_token" 38 | t.datetime "reset_password_sent_at" 39 | t.datetime "remember_created_at" 40 | t.datetime "created_at", precision: 6, null: false 41 | t.datetime "updated_at", precision: 6, null: false 42 | t.index ["email"], name: "index_users_on_email", unique: true 43 | t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true 44 | end 45 | 46 | end 47 | -------------------------------------------------------------------------------- /config/database.yml: -------------------------------------------------------------------------------- 1 | # PostgreSQL. Versions 9.3 and up are supported. 2 | # 3 | # Install the pg driver: 4 | # gem install pg 5 | # On macOS with Homebrew: 6 | # gem install pg -- --with-pg-config=/usr/local/bin/pg_config 7 | # On macOS with MacPorts: 8 | # gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config 9 | # On Windows: 10 | # gem install pg 11 | # Choose the win32 build. 12 | # Install PostgreSQL and put its /bin directory on your path. 13 | # 14 | # Configure Using Gemfile 15 | # gem 'pg' 16 | # 17 | default: &default 18 | adapter: postgresql 19 | encoding: unicode 20 | # For details on connection pooling, see Rails configuration guide 21 | # https://guides.rubyonrails.org/configuring.html#database-pooling 22 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> 23 | 24 | development: 25 | <<: *default 26 | database: bookmarker_development 27 | 28 | # The specified database role being used to connect to postgres. 29 | # To create additional roles in postgres see `$ createuser --help`. 30 | # When left blank, postgres will use the default role. This is 31 | # the same name as the operating system user that initialized the database. 32 | #username: bookmarker 33 | 34 | # The password associated with the postgres role (username). 35 | #password: 36 | 37 | # Connect on a TCP socket. Omitted by default since the client uses a 38 | # domain socket that doesn't need configuration. Windows does not have 39 | # domain sockets, so uncomment these lines. 40 | #host: localhost 41 | 42 | # The TCP port the server listens on. Defaults to 5432. 43 | # If your server runs on a different port number, change accordingly. 44 | #port: 5432 45 | 46 | # Schema search path. The server defaults to $user,public 47 | #schema_search_path: myapp,sharedapp,public 48 | 49 | # Minimum log levels, in increasing order: 50 | # debug5, debug4, debug3, debug2, debug1, 51 | # log, notice, warning, error, fatal, and panic 52 | # Defaults to warning. 53 | #min_messages: notice 54 | 55 | # Warning: The database defined as "test" will be erased and 56 | # re-generated from your development database when you run "rake". 57 | # Do not set this db to the same as development or production. 58 | test: 59 | <<: *default 60 | database: bookmarker_test 61 | 62 | # As with config/credentials.yml, you never want to store sensitive information, 63 | # like your database password, in your source code. If your source code is 64 | # ever seen by anyone, they now have access to your database. 65 | # 66 | # Instead, provide the password as a unix environment variable when you boot 67 | # the app. Read https://guides.rubyonrails.org/configuring.html#configuring-a-database 68 | # for a full rundown on how to provide these environment variables in a 69 | # production deployment. 70 | # 71 | # On Heroku and other platform providers, you may have a full connection URL 72 | # available as an environment variable. For example: 73 | # 74 | # DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" 75 | # 76 | # You can use this database configuration with: 77 | # 78 | # production: 79 | # url: <%= ENV['DATABASE_URL'] %> 80 | # 81 | production: 82 | <<: *default 83 | database: bookmarker_production 84 | username: bookmarker 85 | password: <%= ENV['BOOKMARKER_DATABASE_PASSWORD'] %> 86 | -------------------------------------------------------------------------------- /spec/rails_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # This file is copied to spec/ when you run 'rails generate rspec:install' 4 | require 'spec_helper' 5 | ENV['RAILS_ENV'] ||= 'test' 6 | require File.expand_path('../config/environment', __dir__) 7 | # Prevent database truncation if the environment is production 8 | abort('The Rails environment is running in production mode!') if Rails.env.production? 9 | require 'rspec/rails' 10 | require 'factory_bot_rails' 11 | # Add additional requires below this line. Rails is not loaded until this point! 12 | 13 | # Requires supporting ruby files with custom matchers and macros, etc, in 14 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are 15 | # run as spec files by default. This means that files in spec/support that end 16 | # in _spec.rb will both be required and run as specs, causing the specs to be 17 | # run twice. It is recommended that you do not name files matching this glob to 18 | # end with _spec.rb. You can configure this pattern with the --pattern 19 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. 20 | # 21 | # The following line is provided for convenience purposes. It has the downside 22 | # of increasing the boot-up time by auto-requiring all files in the support 23 | # directory. Alternatively, in the individual `*_spec.rb` files, manually 24 | # require only the support files necessary. 25 | # 26 | # Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } 27 | 28 | # Checks for pending migrations and applies them before tests are run. 29 | # If you are not using ActiveRecord, you can remove these lines. 30 | begin 31 | ActiveRecord::Migration.maintain_test_schema! 32 | rescue ActiveRecord::PendingMigrationError => e 33 | puts e.to_s.strip 34 | exit 1 35 | end 36 | RSpec.configure do |config| 37 | config.include FactoryBot::Syntax::Methods 38 | 39 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 40 | config.fixture_path = "#{::Rails.root}/spec/fixtures" 41 | 42 | # If you're not using ActiveRecord, or you'd prefer not to run each of your 43 | # examples within a transaction, remove the following line or assign false 44 | # instead of true. 45 | config.use_transactional_fixtures = true 46 | 47 | # You can uncomment this line to turn off ActiveRecord support entirely. 48 | # config.use_active_record = false 49 | 50 | # RSpec Rails can automatically mix in different behaviours to your tests 51 | # based on their file location, for example enabling you to call `get` and 52 | # `post` in specs under `spec/controllers`. 53 | # 54 | # You can disable this behaviour by removing the line below, and instead 55 | # explicitly tag your specs with their type, e.g.: 56 | # 57 | # RSpec.describe UsersController, type: :controller do 58 | # # ... 59 | # end 60 | # 61 | # The different available types are documented in the features, such as in 62 | # https://relishapp.com/rspec/rspec-rails/docs 63 | config.infer_spec_type_from_file_location! 64 | 65 | # Filter lines from Rails gems in backtraces. 66 | config.filter_rails_from_backtrace! 67 | # arbitrary gems may also be filtered via: 68 | # config.filter_gems_from_backtrace("gem name") 69 | end 70 | 71 | Shoulda::Matchers.configure do |config| 72 | config.integrate do |with| 73 | with.test_framework :rspec 74 | with.library :rails 75 | end 76 | end 77 | -------------------------------------------------------------------------------- /bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # 5 | # This file was generated by Bundler. 6 | # 7 | # The application 'bundle' is installed as part of a gem, and 8 | # this file is here to facilitate running it. 9 | # 10 | 11 | require 'rubygems' 12 | 13 | m = Module.new do 14 | module_function 15 | 16 | def invoked_as_script? 17 | File.expand_path($PROGRAM_NAME) == File.expand_path(__FILE__) 18 | end 19 | 20 | def env_var_version 21 | ENV['BUNDLER_VERSION'] 22 | end 23 | 24 | def cli_arg_version 25 | return unless invoked_as_script? # don't want to hijack other binstubs 26 | return unless 'update'.start_with?(ARGV.first || ' ') # must be running `bundle update` 27 | 28 | bundler_version = nil 29 | update_index = nil 30 | ARGV.each_with_index do |a, i| 31 | bundler_version = a if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN 32 | next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ 33 | 34 | bundler_version = Regexp.last_match(1) 35 | update_index = i 36 | end 37 | bundler_version 38 | end 39 | 40 | def gemfile 41 | gemfile = ENV['BUNDLE_GEMFILE'] 42 | return gemfile if gemfile && !gemfile.empty? 43 | 44 | File.expand_path('../Gemfile', __dir__) 45 | end 46 | 47 | def lockfile 48 | lockfile = 49 | case File.basename(gemfile) 50 | when 'gems.rb' then gemfile.sub(/\.rb$/, gemfile) 51 | else "#{gemfile}.lock" 52 | end 53 | File.expand_path(lockfile) 54 | end 55 | 56 | def lockfile_version 57 | return unless File.file?(lockfile) 58 | 59 | lockfile_contents = File.read(lockfile) 60 | return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ 61 | 62 | Regexp.last_match(1) 63 | end 64 | 65 | def bundler_version 66 | @bundler_version ||= 67 | env_var_version || cli_arg_version || 68 | lockfile_version 69 | end 70 | 71 | def bundler_requirement 72 | return "#{Gem::Requirement.default}.a" unless bundler_version 73 | 74 | bundler_gem_version = Gem::Version.new(bundler_version) 75 | 76 | requirement = bundler_gem_version.approximate_recommendation 77 | 78 | return requirement unless Gem::Version.new(Gem::VERSION) < Gem::Version.new('2.7.0') 79 | 80 | requirement += '.a' if bundler_gem_version.prerelease? 81 | 82 | requirement 83 | end 84 | 85 | def load_bundler! 86 | ENV['BUNDLE_GEMFILE'] ||= gemfile 87 | 88 | activate_bundler 89 | end 90 | 91 | def activate_bundler 92 | gem_error = activation_error_handling do 93 | gem 'bundler', bundler_requirement 94 | end 95 | return if gem_error.nil? 96 | 97 | require_error = activation_error_handling do 98 | require 'bundler/version' 99 | end 100 | if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) 101 | return 102 | end 103 | 104 | warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" 105 | exit 42 106 | end 107 | 108 | def activation_error_handling 109 | yield 110 | nil 111 | rescue StandardError, LoadError => e 112 | e 113 | end 114 | end 115 | 116 | m.load_bundler! 117 | 118 | load Gem.bin_path('bundler', 'bundle') if m.invoked_as_script? 119 | -------------------------------------------------------------------------------- /config/locales/devise.en.yml: -------------------------------------------------------------------------------- 1 | # Additional translations at https://github.com/heartcombo/devise/wiki/I18n 2 | 3 | en: 4 | devise: 5 | confirmations: 6 | confirmed: "Your email address has been successfully confirmed." 7 | send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes." 8 | send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." 9 | failure: 10 | already_authenticated: "You are already signed in." 11 | inactive: "Your account is not activated yet." 12 | invalid: "Invalid %{authentication_keys} or password." 13 | locked: "Your account is locked." 14 | last_attempt: "You have one more attempt before your account is locked." 15 | not_found_in_database: "Invalid %{authentication_keys} or password." 16 | timeout: "Your session expired. Please sign in again to continue." 17 | unauthenticated: "You need to sign in or sign up before continuing." 18 | unconfirmed: "You have to confirm your email address before continuing." 19 | mailer: 20 | confirmation_instructions: 21 | subject: "Confirmation instructions" 22 | reset_password_instructions: 23 | subject: "Reset password instructions" 24 | unlock_instructions: 25 | subject: "Unlock instructions" 26 | email_changed: 27 | subject: "Email Changed" 28 | password_change: 29 | subject: "Password Changed" 30 | omniauth_callbacks: 31 | failure: "Could not authenticate you from %{kind} because \"%{reason}\"." 32 | success: "Successfully authenticated from %{kind} account." 33 | passwords: 34 | no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." 35 | send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes." 36 | send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." 37 | updated: "Your password has been changed successfully. You are now signed in." 38 | updated_not_active: "Your password has been changed successfully." 39 | registrations: 40 | destroyed: "Bye! Your account has been successfully cancelled. We hope to see you again soon." 41 | signed_up: "Welcome! You have signed up successfully." 42 | signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated." 43 | signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked." 44 | signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please follow the link to activate your account." 45 | update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and follow the confirmation link to confirm your new email address." 46 | updated: "Your account has been updated successfully." 47 | updated_but_not_signed_in: "Your account has been updated successfully, but since your password was changed, you need to sign in again" 48 | sessions: 49 | signed_in: "Signed in successfully." 50 | signed_out: "Signed out successfully." 51 | already_signed_out: "Signed out successfully." 52 | unlocks: 53 | send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes." 54 | send_paranoid_instructions: "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." 55 | unlocked: "Your account has been unlocked successfully. Please sign in to continue." 56 | errors: 57 | messages: 58 | already_confirmed: "was already confirmed, please try signing in" 59 | confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" 60 | expired: "has expired, please request a new one" 61 | not_found: "not found" 62 | not_locked: "was not locked" 63 | not_saved: 64 | one: "1 error prohibited this %{resource} from being saved:" 65 | other: "%{count} errors prohibited this %{resource} from being saved:" 66 | -------------------------------------------------------------------------------- /config/environments/production.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # Code is not reloaded between requests. 7 | config.cache_classes = true 8 | 9 | # Eager load code on boot. This eager loads most of Rails and 10 | # your application in memory, allowing both threaded web servers 11 | # and those relying on copy on write to perform better. 12 | # Rake tasks automatically ignore this option for performance. 13 | config.eager_load = true 14 | 15 | # Full error reports are disabled and caching is turned on. 16 | config.consider_all_requests_local = false 17 | 18 | # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] 19 | # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). 20 | # config.require_master_key = true 21 | 22 | # Disable serving static files from the `/public` folder by default since 23 | # Apache or NGINX already handles this. 24 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 25 | 26 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 27 | # config.action_controller.asset_host = 'http://assets.example.com' 28 | 29 | # Specifies the header that your server uses for sending files. 30 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 31 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 32 | 33 | # Store uploaded files on the local file system (see config/storage.yml for options). 34 | config.active_storage.service = :local 35 | 36 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 37 | # config.force_ssl = true 38 | 39 | # Use the lowest log level to ensure availability of diagnostic information 40 | # when problems arise. 41 | config.log_level = :debug 42 | 43 | # Prepend all log lines with the following tags. 44 | config.log_tags = [:request_id] 45 | 46 | # Use a different cache store in production. 47 | # config.cache_store = :mem_cache_store 48 | 49 | # Use a real queuing backend for Active Job (and separate queues per environment). 50 | # config.active_job.queue_adapter = :resque 51 | # config.active_job.queue_name_prefix = "bookmarker_production" 52 | 53 | config.action_mailer.perform_caching = false 54 | 55 | # Ignore bad email addresses and do not raise email delivery errors. 56 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 57 | # config.action_mailer.raise_delivery_errors = false 58 | 59 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 60 | # the I18n.default_locale when a translation cannot be found). 61 | config.i18n.fallbacks = true 62 | 63 | # Send deprecation notices to registered listeners. 64 | config.active_support.deprecation = :notify 65 | 66 | # Use default logging formatter so that PID and timestamp are not suppressed. 67 | config.log_formatter = ::Logger::Formatter.new 68 | 69 | # Use a different logger for distributed setups. 70 | # require 'syslog/logger' 71 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 72 | 73 | if ENV['RAILS_LOG_TO_STDOUT'].present? 74 | logger = ActiveSupport::Logger.new(STDOUT) 75 | logger.formatter = config.log_formatter 76 | config.logger = ActiveSupport::TaggedLogging.new(logger) 77 | end 78 | 79 | # Do not dump schema after migrations. 80 | config.active_record.dump_schema_after_migration = false 81 | 82 | # Inserts middleware to perform automatic connection switching. 83 | # The `database_selector` hash is used to pass options to the DatabaseSelector 84 | # middleware. The `delay` is used to determine how long to wait after a write 85 | # to send a subsequent read to the primary. 86 | # 87 | # The `database_resolver` class is used by the middleware to determine which 88 | # database is appropriate to use based on the time delay. 89 | # 90 | # The `database_resolver_context` class is used by the middleware to set 91 | # timestamps for the last write to the primary. The resolver uses the context 92 | # class timestamps to determine how long to wait before reading from the 93 | # replica. 94 | # 95 | # By default Rails will store a last write timestamp in the session. The 96 | # DatabaseSelector middleware is designed as such you can define your own 97 | # strategy for connection switching and pass that into the middleware through 98 | # these configuration options. 99 | # config.active_record.database_selector = { delay: 2.seconds } 100 | # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver 101 | # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session 102 | end 103 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative 'support/json_helpers' 4 | 5 | # This file was generated by the `rails generate rspec:install` command. Conventionally, all 6 | # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. 7 | # The generated `.rspec` file contains `--require spec_helper` which will cause 8 | # this file to always be loaded, without a need to explicitly require it in any 9 | # files. 10 | # 11 | # Given that it is always loaded, you are encouraged to keep this file as 12 | # light-weight as possible. Requiring heavyweight dependencies from this file 13 | # will add to the boot time of your test suite on EVERY test run, even for an 14 | # individual file that may not need all of that loaded. Instead, consider making 15 | # a separate helper file that requires the additional dependencies and performs 16 | # the additional setup, and require it from the spec files that actually need 17 | # it. 18 | # 19 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration 20 | RSpec.configure do |config| 21 | config.include JsonHelpers 22 | # rspec-expectations config goes here. You can use an alternate 23 | # assertion/expectation library such as wrong or the stdlib/minitest 24 | # assertions if you prefer. 25 | config.expect_with :rspec do |expectations| 26 | # This option will default to `true` in RSpec 4. It makes the `description` 27 | # and `failure_message` of custom matchers include text for helper methods 28 | # defined using `chain`, e.g.: 29 | # be_bigger_than(2).and_smaller_than(4).description 30 | # # => "be bigger than 2 and smaller than 4" 31 | # ...rather than: 32 | # # => "be bigger than 2" 33 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true 34 | end 35 | 36 | # rspec-mocks config goes here. You can use an alternate test double 37 | # library (such as bogus or mocha) by changing the `mock_with` option here. 38 | config.mock_with :rspec do |mocks| 39 | # Prevents you from mocking or stubbing a method that does not exist on 40 | # a real object. This is generally recommended, and will default to 41 | # `true` in RSpec 4. 42 | mocks.verify_partial_doubles = true 43 | end 44 | 45 | # This option will default to `:apply_to_host_groups` in RSpec 4 (and will 46 | # have no way to turn it off -- the option exists only for backwards 47 | # compatibility in RSpec 3). It causes shared context metadata to be 48 | # inherited by the metadata hash of host groups and examples, rather than 49 | # triggering implicit auto-inclusion in groups with matching metadata. 50 | config.shared_context_metadata_behavior = :apply_to_host_groups 51 | 52 | # The settings below are suggested to provide a good initial experience 53 | # with RSpec, but feel free to customize to your heart's content. 54 | # # This allows you to limit a spec run to individual examples or groups 55 | # # you care about by tagging them with `:focus` metadata. When nothing 56 | # # is tagged with `:focus`, all examples get run. RSpec also provides 57 | # # aliases for `it`, `describe`, and `context` that include `:focus` 58 | # # metadata: `fit`, `fdescribe` and `fcontext`, respectively. 59 | # config.filter_run_when_matching :focus 60 | # 61 | # # Allows RSpec to persist some state between runs in order to support 62 | # # the `--only-failures` and `--next-failure` CLI options. We recommend 63 | # # you configure your source control system to ignore this file. 64 | # config.example_status_persistence_file_path = "spec/examples.txt" 65 | # 66 | # # Limits the available syntax to the non-monkey patched syntax that is 67 | # # recommended. For more details, see: 68 | # # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ 69 | # # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ 70 | # # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode 71 | # config.disable_monkey_patching! 72 | # 73 | # # Many RSpec users commonly either run the entire suite or an individual 74 | # # file, and it's useful to allow more verbose output when running an 75 | # # individual spec file. 76 | # if config.files_to_run.one? 77 | # # Use the documentation formatter for detailed output, 78 | # # unless a formatter has already been configured 79 | # # (e.g. via a command-line flag). 80 | # config.default_formatter = "doc" 81 | # end 82 | # 83 | # # Print the 10 slowest examples and example groups at the 84 | # # end of the spec run, to help surface which specs are running 85 | # # particularly slow. 86 | # config.profile_examples = 10 87 | # 88 | # # Run specs in random order to surface order dependencies. If you find an 89 | # # order dependency and want to debug it, you can fix the order by providing 90 | # # the seed, which is printed after each run. 91 | # # --seed 1234 92 | # config.order = :random 93 | # 94 | # # Seed global randomization in this process using the `--seed` CLI option. 95 | # # Setting this allows you to use `--seed` to deterministically reproduce 96 | # # test failures related to randomization by passing the same `--seed` value 97 | # # as the one that triggered the failure. 98 | # Kernel.srand config.seed 99 | end 100 | -------------------------------------------------------------------------------- /config/locales/doorkeeper.en.yml: -------------------------------------------------------------------------------- 1 | en: 2 | activerecord: 3 | attributes: 4 | doorkeeper/application: 5 | name: 'Name' 6 | redirect_uri: 'Redirect URI' 7 | errors: 8 | models: 9 | doorkeeper/application: 10 | attributes: 11 | redirect_uri: 12 | fragment_present: 'cannot contain a fragment.' 13 | invalid_uri: 'must be a valid URI.' 14 | unspecified_scheme: 'must specify a scheme.' 15 | relative_uri: 'must be an absolute URI.' 16 | secured_uri: 'must be an HTTPS/SSL URI.' 17 | forbidden_uri: 'is forbidden by the server.' 18 | scopes: 19 | not_match_configured: "doesn't match configured on the server." 20 | 21 | doorkeeper: 22 | applications: 23 | confirmations: 24 | destroy: 'Are you sure?' 25 | buttons: 26 | edit: 'Edit' 27 | destroy: 'Destroy' 28 | submit: 'Submit' 29 | cancel: 'Cancel' 30 | authorize: 'Authorize' 31 | form: 32 | error: 'Whoops! Check your form for possible errors' 33 | help: 34 | confidential: 'Application will be used where the client secret can be kept confidential. Native mobile apps and Single Page Apps are considered non-confidential.' 35 | redirect_uri: 'Use one line per URI' 36 | blank_redirect_uri: "Leave it blank if you configured your provider to use Client Credentials, Resource Owner Password Credentials or any other grant type that doesn't require redirect URI." 37 | scopes: 'Separate scopes with spaces. Leave blank to use the default scopes.' 38 | edit: 39 | title: 'Edit application' 40 | index: 41 | title: 'Your applications' 42 | new: 'New Application' 43 | name: 'Name' 44 | callback_url: 'Callback URL' 45 | confidential: 'Confidential?' 46 | actions: 'Actions' 47 | confidentiality: 48 | 'yes': 'Yes' 49 | 'no': 'No' 50 | new: 51 | title: 'New Application' 52 | show: 53 | title: 'Application: %{name}' 54 | application_id: 'UID' 55 | secret: 'Secret' 56 | secret_hashed: 'Secret hashed' 57 | scopes: 'Scopes' 58 | confidential: 'Confidential' 59 | callback_urls: 'Callback urls' 60 | actions: 'Actions' 61 | not_defined: 'Not defined' 62 | 63 | authorizations: 64 | buttons: 65 | authorize: 'Authorize' 66 | deny: 'Deny' 67 | error: 68 | title: 'An error has occurred' 69 | new: 70 | title: 'Authorization required' 71 | prompt: 'Authorize %{client_name} to use your account?' 72 | able_to: 'This application will be able to' 73 | show: 74 | title: 'Authorization code' 75 | 76 | authorized_applications: 77 | confirmations: 78 | revoke: 'Are you sure?' 79 | buttons: 80 | revoke: 'Revoke' 81 | index: 82 | title: 'Your authorized applications' 83 | application: 'Application' 84 | created_at: 'Created At' 85 | date_format: '%Y-%m-%d %H:%M:%S' 86 | 87 | pre_authorization: 88 | status: 'Pre-authorization' 89 | 90 | errors: 91 | messages: 92 | # Common error messages 93 | invalid_request: 94 | unknown: 'The request is missing a required parameter, includes an unsupported parameter value, or is otherwise malformed.' 95 | missing_param: 'Missing required parameter: %{value}.' 96 | not_support_pkce: 'Invalid code_verifier parameter. Server does not support pkce.' 97 | request_not_authorized: 'Request need to be authorized. Required parameter for authorizing request is missing or invalid.' 98 | invalid_redirect_uri: "The requested redirect uri is malformed or doesn't match client redirect URI." 99 | unauthorized_client: 'The client is not authorized to perform this request using this method.' 100 | access_denied: 'The resource owner or authorization server denied the request.' 101 | invalid_scope: 'The requested scope is invalid, unknown, or malformed.' 102 | invalid_code_challenge_method: 'The code challenge method must be plain or S256.' 103 | server_error: 'The authorization server encountered an unexpected condition which prevented it from fulfilling the request.' 104 | temporarily_unavailable: 'The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server.' 105 | 106 | # Configuration error messages 107 | credential_flow_not_configured: 'Resource Owner Password Credentials flow failed due to Doorkeeper.configure.resource_owner_from_credentials being unconfigured.' 108 | resource_owner_authenticator_not_configured: 'Resource Owner find failed due to Doorkeeper.configure.resource_owner_authenticator being unconfigured.' 109 | admin_authenticator_not_configured: 'Access to admin panel is forbidden due to Doorkeeper.configure.admin_authenticator being unconfigured.' 110 | 111 | # Access grant errors 112 | unsupported_response_type: 'The authorization server does not support this response type.' 113 | 114 | # Access token errors 115 | invalid_client: 'Client authentication failed due to unknown client, no client authentication included, or unsupported authentication method.' 116 | invalid_grant: 'The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.' 117 | unsupported_grant_type: 'The authorization grant type is not supported by the authorization server.' 118 | 119 | invalid_token: 120 | revoked: "The access token was revoked" 121 | expired: "The access token expired" 122 | unknown: "The access token is invalid" 123 | revoke: 124 | unauthorized: "You are not authorized to revoke this token" 125 | 126 | flash: 127 | applications: 128 | create: 129 | notice: 'Application created.' 130 | destroy: 131 | notice: 'Application deleted.' 132 | update: 133 | notice: 'Application updated.' 134 | authorized_applications: 135 | destroy: 136 | notice: 'Application revoked.' 137 | 138 | layouts: 139 | admin: 140 | title: 'Doorkeeper' 141 | nav: 142 | oauth2_provider: 'OAuth2 Provider' 143 | applications: 'Applications' 144 | home: 'Home' 145 | application: 146 | title: 'OAuth authorization required' 147 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | actioncable (6.0.3.2) 5 | actionpack (= 6.0.3.2) 6 | nio4r (~> 2.0) 7 | websocket-driver (>= 0.6.1) 8 | actionmailbox (6.0.3.2) 9 | actionpack (= 6.0.3.2) 10 | activejob (= 6.0.3.2) 11 | activerecord (= 6.0.3.2) 12 | activestorage (= 6.0.3.2) 13 | activesupport (= 6.0.3.2) 14 | mail (>= 2.7.1) 15 | actionmailer (6.0.3.2) 16 | actionpack (= 6.0.3.2) 17 | actionview (= 6.0.3.2) 18 | activejob (= 6.0.3.2) 19 | mail (~> 2.5, >= 2.5.4) 20 | rails-dom-testing (~> 2.0) 21 | actionpack (6.0.3.2) 22 | actionview (= 6.0.3.2) 23 | activesupport (= 6.0.3.2) 24 | rack (~> 2.0, >= 2.0.8) 25 | rack-test (>= 0.6.3) 26 | rails-dom-testing (~> 2.0) 27 | rails-html-sanitizer (~> 1.0, >= 1.2.0) 28 | actiontext (6.0.3.2) 29 | actionpack (= 6.0.3.2) 30 | activerecord (= 6.0.3.2) 31 | activestorage (= 6.0.3.2) 32 | activesupport (= 6.0.3.2) 33 | nokogiri (>= 1.8.5) 34 | actionview (6.0.3.2) 35 | activesupport (= 6.0.3.2) 36 | builder (~> 3.1) 37 | erubi (~> 1.4) 38 | rails-dom-testing (~> 2.0) 39 | rails-html-sanitizer (~> 1.1, >= 1.2.0) 40 | active_model_serializers (0.8.4) 41 | activemodel (>= 3.0) 42 | activejob (6.0.3.2) 43 | activesupport (= 6.0.3.2) 44 | globalid (>= 0.3.6) 45 | activemodel (6.0.3.2) 46 | activesupport (= 6.0.3.2) 47 | activerecord (6.0.3.2) 48 | activemodel (= 6.0.3.2) 49 | activesupport (= 6.0.3.2) 50 | activestorage (6.0.3.2) 51 | actionpack (= 6.0.3.2) 52 | activejob (= 6.0.3.2) 53 | activerecord (= 6.0.3.2) 54 | marcel (~> 0.3.1) 55 | activesupport (6.0.3.2) 56 | concurrent-ruby (~> 1.0, >= 1.0.2) 57 | i18n (>= 0.7, < 2) 58 | minitest (~> 5.1) 59 | tzinfo (~> 1.1) 60 | zeitwerk (~> 2.2, >= 2.2.2) 61 | ast (2.4.1) 62 | bcrypt (3.1.13) 63 | bootsnap (1.4.6) 64 | msgpack (~> 1.0) 65 | builder (3.2.4) 66 | byebug (11.1.3) 67 | concurrent-ruby (1.1.6) 68 | crass (1.0.6) 69 | devise (4.7.2) 70 | bcrypt (~> 3.0) 71 | orm_adapter (~> 0.1) 72 | railties (>= 4.1.0) 73 | responders 74 | warden (~> 1.2.3) 75 | diff-lcs (1.4.2) 76 | doorkeeper (5.4.0) 77 | railties (>= 5) 78 | erubi (1.9.0) 79 | factory_bot (5.2.0) 80 | activesupport (>= 4.2.0) 81 | factory_bot_rails (5.2.0) 82 | factory_bot (~> 5.2.0) 83 | railties (>= 4.2.0) 84 | ffi (1.13.1) 85 | globalid (0.4.2) 86 | activesupport (>= 4.2.0) 87 | i18n (1.8.3) 88 | concurrent-ruby (~> 1.0) 89 | listen (3.2.1) 90 | rb-fsevent (~> 0.10, >= 0.10.3) 91 | rb-inotify (~> 0.9, >= 0.9.10) 92 | loofah (2.6.0) 93 | crass (~> 1.0.2) 94 | nokogiri (>= 1.5.9) 95 | mail (2.7.1) 96 | mini_mime (>= 0.1.1) 97 | marcel (0.3.3) 98 | mimemagic (~> 0.3.2) 99 | method_source (1.0.0) 100 | mimemagic (0.3.5) 101 | mini_mime (1.0.2) 102 | mini_portile2 (2.4.0) 103 | minitest (5.14.1) 104 | msgpack (1.3.3) 105 | nio4r (2.5.2) 106 | nokogiri (1.10.9) 107 | mini_portile2 (~> 2.4.0) 108 | orm_adapter (0.5.0) 109 | parallel (1.19.2) 110 | parser (2.7.1.4) 111 | ast (~> 2.4.1) 112 | pg (1.2.3) 113 | puma (4.3.5) 114 | nio4r (~> 2.0) 115 | rack (2.2.3) 116 | rack-cors (1.1.1) 117 | rack (>= 2.0.0) 118 | rack-test (1.1.0) 119 | rack (>= 1.0, < 3) 120 | rails (6.0.3.2) 121 | actioncable (= 6.0.3.2) 122 | actionmailbox (= 6.0.3.2) 123 | actionmailer (= 6.0.3.2) 124 | actionpack (= 6.0.3.2) 125 | actiontext (= 6.0.3.2) 126 | actionview (= 6.0.3.2) 127 | activejob (= 6.0.3.2) 128 | activemodel (= 6.0.3.2) 129 | activerecord (= 6.0.3.2) 130 | activestorage (= 6.0.3.2) 131 | activesupport (= 6.0.3.2) 132 | bundler (>= 1.3.0) 133 | railties (= 6.0.3.2) 134 | sprockets-rails (>= 2.0.0) 135 | rails-dom-testing (2.0.3) 136 | activesupport (>= 4.2.0) 137 | nokogiri (>= 1.6) 138 | rails-html-sanitizer (1.3.0) 139 | loofah (~> 2.3) 140 | railties (6.0.3.2) 141 | actionpack (= 6.0.3.2) 142 | activesupport (= 6.0.3.2) 143 | method_source 144 | rake (>= 0.8.7) 145 | thor (>= 0.20.3, < 2.0) 146 | rainbow (3.0.0) 147 | rake (13.0.1) 148 | rb-fsevent (0.10.4) 149 | rb-inotify (0.10.1) 150 | ffi (~> 1.0) 151 | regexp_parser (1.7.1) 152 | responders (3.0.1) 153 | actionpack (>= 5.0) 154 | railties (>= 5.0) 155 | rexml (3.2.4) 156 | rspec-core (3.9.2) 157 | rspec-support (~> 3.9.3) 158 | rspec-expectations (3.9.2) 159 | diff-lcs (>= 1.2.0, < 2.0) 160 | rspec-support (~> 3.9.0) 161 | rspec-mocks (3.9.1) 162 | diff-lcs (>= 1.2.0, < 2.0) 163 | rspec-support (~> 3.9.0) 164 | rspec-rails (4.0.1) 165 | actionpack (>= 4.2) 166 | activesupport (>= 4.2) 167 | railties (>= 4.2) 168 | rspec-core (~> 3.9) 169 | rspec-expectations (~> 3.9) 170 | rspec-mocks (~> 3.9) 171 | rspec-support (~> 3.9) 172 | rspec-support (3.9.3) 173 | rubocop (0.85.1) 174 | parallel (~> 1.10) 175 | parser (>= 2.7.0.1) 176 | rainbow (>= 2.2.2, < 4.0) 177 | regexp_parser (>= 1.7) 178 | rexml 179 | rubocop-ast (>= 0.0.3) 180 | ruby-progressbar (~> 1.7) 181 | unicode-display_width (>= 1.4.0, < 2.0) 182 | rubocop-ast (0.0.3) 183 | parser (>= 2.7.0.1) 184 | ruby-progressbar (1.10.1) 185 | shoulda-matchers (3.1.3) 186 | activesupport (>= 4.0.0) 187 | sprockets (4.0.2) 188 | concurrent-ruby (~> 1.0) 189 | rack (> 1, < 3) 190 | sprockets-rails (3.2.1) 191 | actionpack (>= 4.0) 192 | activesupport (>= 4.0) 193 | sprockets (>= 3.0.0) 194 | swagger-blocks (3.0.0) 195 | thor (1.0.1) 196 | thread_safe (0.3.6) 197 | tzinfo (1.2.7) 198 | thread_safe (~> 0.1) 199 | unicode-display_width (1.7.0) 200 | warden (1.2.8) 201 | rack (>= 2.0.6) 202 | websocket-driver (0.7.2) 203 | websocket-extensions (>= 0.1.0) 204 | websocket-extensions (0.1.5) 205 | zeitwerk (2.3.0) 206 | 207 | PLATFORMS 208 | ruby 209 | 210 | DEPENDENCIES 211 | active_model_serializers (~> 0.8.4) 212 | bootsnap (>= 1.4.2) 213 | byebug 214 | devise (~> 4.7) 215 | doorkeeper (~> 5.4) 216 | factory_bot_rails (~> 5.2) 217 | listen (~> 3.2) 218 | pg (>= 0.18, < 2.0) 219 | puma (~> 4.1) 220 | rack-cors (~> 1.1) 221 | rails (~> 6.0.3, >= 6.0.3.2) 222 | rspec-rails (~> 4.0) 223 | rubocop (~> 0.85.1) 224 | shoulda-matchers (~> 3.1) 225 | swagger-blocks (~> 3.0) 226 | tzinfo-data 227 | 228 | RUBY VERSION 229 | ruby 2.6.5p114 230 | 231 | BUNDLED WITH 232 | 2.1.4 233 | -------------------------------------------------------------------------------- /config/initializers/devise.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Assuming you have not yet modified this file, each configuration option below 4 | # is set to its default value. Note that some are commented out while others 5 | # are not: uncommented lines are intended to protect your configuration from 6 | # breaking changes in upgrades (i.e., in the event that future versions of 7 | # Devise change the default values for those options). 8 | # 9 | # Use this hook to configure devise mailer, warden hooks and so forth. 10 | # Many of these configuration options can be set straight in your model. 11 | Devise.setup do |config| 12 | # The secret key used by Devise. Devise uses this key to generate 13 | # random tokens. Changing this key will render invalid all existing 14 | # confirmation, reset password and unlock tokens in the database. 15 | # Devise will use the `secret_key_base` as its `secret_key` 16 | # by default. You can change it below and use your own secret key. 17 | # config.secret_key = 'bd856ec05e2e5956acfa242ab3154706b1a305fb5f8ea45f6d949111cd31e5b99f5f34896d565da0a52836579e3ae7ebb79af0851ee4466e6987bc3af3521205' 18 | 19 | # ==> Controller configuration 20 | # Configure the parent class to the devise controllers. 21 | # config.parent_controller = 'DeviseController' 22 | 23 | # ==> Mailer Configuration 24 | # Configure the e-mail address which will be shown in Devise::Mailer, 25 | # note that it will be overwritten if you use your own mailer class 26 | # with default "from" parameter. 27 | config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' 28 | 29 | # Configure the class responsible to send e-mails. 30 | # config.mailer = 'Devise::Mailer' 31 | 32 | # Configure the parent class responsible to send e-mails. 33 | # config.parent_mailer = 'ActionMailer::Base' 34 | 35 | # ==> ORM configuration 36 | # Load and configure the ORM. Supports :active_record (default) and 37 | # :mongoid (bson_ext recommended) by default. Other ORMs may be 38 | # available as additional gems. 39 | require 'devise/orm/active_record' 40 | 41 | # ==> Configuration for any authentication mechanism 42 | # Configure which keys are used when authenticating a user. The default is 43 | # just :email. You can configure it to use [:username, :subdomain], so for 44 | # authenticating a user, both parameters are required. Remember that those 45 | # parameters are used only when authenticating and not when retrieving from 46 | # session. If you need permissions, you should implement that in a before filter. 47 | # You can also supply a hash where the value is a boolean determining whether 48 | # or not authentication should be aborted when the value is not present. 49 | # config.authentication_keys = [:email] 50 | 51 | # Configure parameters from the request object used for authentication. Each entry 52 | # given should be a request method and it will automatically be passed to the 53 | # find_for_authentication method and considered in your model lookup. For instance, 54 | # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. 55 | # The same considerations mentioned for authentication_keys also apply to request_keys. 56 | # config.request_keys = [] 57 | 58 | # Configure which authentication keys should be case-insensitive. 59 | # These keys will be downcased upon creating or modifying a user and when used 60 | # to authenticate or find a user. Default is :email. 61 | config.case_insensitive_keys = [:email] 62 | 63 | # Configure which authentication keys should have whitespace stripped. 64 | # These keys will have whitespace before and after removed upon creating or 65 | # modifying a user and when used to authenticate or find a user. Default is :email. 66 | config.strip_whitespace_keys = [:email] 67 | 68 | # Tell if authentication through request.params is enabled. True by default. 69 | # It can be set to an array that will enable params authentication only for the 70 | # given strategies, for example, `config.params_authenticatable = [:database]` will 71 | # enable it only for database (email + password) authentication. 72 | # config.params_authenticatable = true 73 | 74 | # Tell if authentication through HTTP Auth is enabled. False by default. 75 | # It can be set to an array that will enable http authentication only for the 76 | # given strategies, for example, `config.http_authenticatable = [:database]` will 77 | # enable it only for database authentication. 78 | # For API-only applications to support authentication "out-of-the-box", you will likely want to 79 | # enable this with :database unless you are using a custom strategy. 80 | # The supported strategies are: 81 | # :database = Support basic authentication with authentication key + password 82 | # config.http_authenticatable = false 83 | 84 | # If 401 status code should be returned for AJAX requests. True by default. 85 | # config.http_authenticatable_on_xhr = true 86 | 87 | # The realm used in Http Basic Authentication. 'Application' by default. 88 | # config.http_authentication_realm = 'Application' 89 | 90 | # It will change confirmation, password recovery and other workflows 91 | # to behave the same regardless if the e-mail provided was right or wrong. 92 | # Does not affect registerable. 93 | # config.paranoid = true 94 | 95 | # By default Devise will store the user in session. You can skip storage for 96 | # particular strategies by setting this option. 97 | # Notice that if you are skipping storage for all authentication paths, you 98 | # may want to disable generating routes to Devise's sessions controller by 99 | # passing skip: :sessions to `devise_for` in your config/routes.rb 100 | config.skip_session_storage = [:http_auth] 101 | 102 | # By default, Devise cleans up the CSRF token on authentication to 103 | # avoid CSRF token fixation attacks. This means that, when using AJAX 104 | # requests for sign in and sign up, you need to get a new CSRF token 105 | # from the server. You can disable this option at your own risk. 106 | # config.clean_up_csrf_token_on_authentication = true 107 | 108 | # When false, Devise will not attempt to reload routes on eager load. 109 | # This can reduce the time taken to boot the app but if your application 110 | # requires the Devise mappings to be loaded during boot time the application 111 | # won't boot properly. 112 | # config.reload_routes = true 113 | 114 | # ==> Configuration for :database_authenticatable 115 | # For bcrypt, this is the cost for hashing the password and defaults to 12. If 116 | # using other algorithms, it sets how many times you want the password to be hashed. 117 | # The number of stretches used for generating the hashed password are stored 118 | # with the hashed password. This allows you to change the stretches without 119 | # invalidating existing passwords. 120 | # 121 | # Limiting the stretches to just one in testing will increase the performance of 122 | # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use 123 | # a value less than 10 in other environments. Note that, for bcrypt (the default 124 | # algorithm), the cost increases exponentially with the number of stretches (e.g. 125 | # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). 126 | config.stretches = Rails.env.test? ? 1 : 12 127 | 128 | # Set up a pepper to generate the hashed password. 129 | # config.pepper = 'f7d1bc0f315c75b002fd724c098c4ce4ecad2d87cd21e38515ac3adf8961ea434147968f2058cbe49525b6d6a6e69eaca1afed7e117dcc7dab4c608633bc1025' 130 | 131 | # Send a notification to the original email when the user's email is changed. 132 | # config.send_email_changed_notification = false 133 | 134 | # Send a notification email when the user's password is changed. 135 | # config.send_password_change_notification = false 136 | 137 | # ==> Configuration for :confirmable 138 | # A period that the user is allowed to access the website even without 139 | # confirming their account. For instance, if set to 2.days, the user will be 140 | # able to access the website for two days without confirming their account, 141 | # access will be blocked just in the third day. 142 | # You can also set it to nil, which will allow the user to access the website 143 | # without confirming their account. 144 | # Default is 0.days, meaning the user cannot access the website without 145 | # confirming their account. 146 | # config.allow_unconfirmed_access_for = 2.days 147 | 148 | # A period that the user is allowed to confirm their account before their 149 | # token becomes invalid. For example, if set to 3.days, the user can confirm 150 | # their account within 3 days after the mail was sent, but on the fourth day 151 | # their account can't be confirmed with the token any more. 152 | # Default is nil, meaning there is no restriction on how long a user can take 153 | # before confirming their account. 154 | # config.confirm_within = 3.days 155 | 156 | # If true, requires any email changes to be confirmed (exactly the same way as 157 | # initial account confirmation) to be applied. Requires additional unconfirmed_email 158 | # db field (see migrations). Until confirmed, new email is stored in 159 | # unconfirmed_email column, and copied to email column on successful confirmation. 160 | config.reconfirmable = true 161 | 162 | # Defines which key will be used when confirming an account 163 | # config.confirmation_keys = [:email] 164 | 165 | # ==> Configuration for :rememberable 166 | # The time the user will be remembered without asking for credentials again. 167 | # config.remember_for = 2.weeks 168 | 169 | # Invalidates all the remember me tokens when the user signs out. 170 | config.expire_all_remember_me_on_sign_out = true 171 | 172 | # If true, extends the user's remember period when remembered via cookie. 173 | # config.extend_remember_period = false 174 | 175 | # Options to be passed to the created cookie. For instance, you can set 176 | # secure: true in order to force SSL only cookies. 177 | # config.rememberable_options = {} 178 | 179 | # ==> Configuration for :validatable 180 | # Range for password length. 181 | config.password_length = 6..128 182 | 183 | # Email regex used to validate email formats. It simply asserts that 184 | # one (and only one) @ exists in the given string. This is mainly 185 | # to give user feedback and not to assert the e-mail validity. 186 | config.email_regexp = /\A[^@\s]+@[^@\s]+\z/ 187 | 188 | # ==> Configuration for :timeoutable 189 | # The time you want to timeout the user session without activity. After this 190 | # time the user will be asked for credentials again. Default is 30 minutes. 191 | # config.timeout_in = 30.minutes 192 | 193 | # ==> Configuration for :lockable 194 | # Defines which strategy will be used to lock an account. 195 | # :failed_attempts = Locks an account after a number of failed attempts to sign in. 196 | # :none = No lock strategy. You should handle locking by yourself. 197 | # config.lock_strategy = :failed_attempts 198 | 199 | # Defines which key will be used when locking and unlocking an account 200 | # config.unlock_keys = [:email] 201 | 202 | # Defines which strategy will be used to unlock an account. 203 | # :email = Sends an unlock link to the user email 204 | # :time = Re-enables login after a certain amount of time (see :unlock_in below) 205 | # :both = Enables both strategies 206 | # :none = No unlock strategy. You should handle unlocking by yourself. 207 | # config.unlock_strategy = :both 208 | 209 | # Number of authentication tries before locking an account if lock_strategy 210 | # is failed attempts. 211 | # config.maximum_attempts = 20 212 | 213 | # Time interval to unlock the account if :time is enabled as unlock_strategy. 214 | # config.unlock_in = 1.hour 215 | 216 | # Warn on the last attempt before the account is locked. 217 | # config.last_attempt_warning = true 218 | 219 | # ==> Configuration for :recoverable 220 | # 221 | # Defines which key will be used when recovering the password for an account 222 | # config.reset_password_keys = [:email] 223 | 224 | # Time interval you can reset your password with a reset password key. 225 | # Don't put a too small interval or your users won't have the time to 226 | # change their passwords. 227 | config.reset_password_within = 6.hours 228 | 229 | # When set to false, does not sign a user in automatically after their password is 230 | # reset. Defaults to true, so a user is signed in automatically after a reset. 231 | # config.sign_in_after_reset_password = true 232 | 233 | # ==> Configuration for :encryptable 234 | # Allow you to use another hashing or encryption algorithm besides bcrypt (default). 235 | # You can use :sha1, :sha512 or algorithms from others authentication tools as 236 | # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20 237 | # for default behavior) and :restful_authentication_sha1 (then you should set 238 | # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper). 239 | # 240 | # Require the `devise-encryptable` gem when using anything other than bcrypt 241 | # config.encryptor = :sha512 242 | 243 | # ==> Scopes configuration 244 | # Turn scoped views on. Before rendering "sessions/new", it will first check for 245 | # "users/sessions/new". It's turned off by default because it's slower if you 246 | # are using only default views. 247 | # config.scoped_views = false 248 | 249 | # Configure the default scope given to Warden. By default it's the first 250 | # devise role declared in your routes (usually :user). 251 | # config.default_scope = :user 252 | 253 | # Set this configuration to false if you want /users/sign_out to sign out 254 | # only the current scope. By default, Devise signs out all scopes. 255 | # config.sign_out_all_scopes = true 256 | 257 | # ==> Navigation configuration 258 | # Lists the formats that should be treated as navigational. Formats like 259 | # :html, should redirect to the sign in page when the user does not have 260 | # access, but formats like :xml or :json, should return 401. 261 | # 262 | # If you have any extra navigational formats, like :iphone or :mobile, you 263 | # should add them to the navigational formats lists. 264 | # 265 | # The "*/*" below is required to match Internet Explorer requests. 266 | # config.navigational_formats = ['*/*', :html] 267 | 268 | # The default HTTP method used to sign out a resource. Default is :delete. 269 | config.sign_out_via = :delete 270 | 271 | # ==> OmniAuth 272 | # Add a new OmniAuth provider. Check the wiki for more information on setting 273 | # up on your models and hooks. 274 | # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' 275 | 276 | # ==> Warden configuration 277 | # If you want to use other strategies, that are not supported by Devise, or 278 | # change the failure app, you can configure them inside the config.warden block. 279 | # 280 | # config.warden do |manager| 281 | # manager.intercept_401 = false 282 | # manager.default_strategies(scope: :user).unshift :some_external_strategy 283 | # end 284 | 285 | # ==> Mountable engine configurations 286 | # When using Devise inside an engine, let's call it `MyEngine`, and this engine 287 | # is mountable, there are some extra configurations to be taken into account. 288 | # The following options are available, assuming the engine is mounted as: 289 | # 290 | # mount MyEngine, at: '/my_engine' 291 | # 292 | # The router that invoked `devise_for`, in the example above, would be: 293 | # config.router_name = :my_engine 294 | # 295 | # When using OmniAuth, Devise cannot automatically set OmniAuth path, 296 | # so you need to do it manually. For the users scope, it would be: 297 | # config.omniauth_path_prefix = '/my_engine/users/auth' 298 | 299 | # ==> Turbolinks configuration 300 | # If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly: 301 | # 302 | # ActiveSupport.on_load(:devise_failure_app) do 303 | # include Turbolinks::Controller 304 | # end 305 | 306 | # ==> Configuration for :registerable 307 | 308 | # When set to false, does not sign a user in automatically after their password is 309 | # changed. Defaults to true, so a user is signed in automatically after changing a password. 310 | # config.sign_in_after_change_password = true 311 | end 312 | -------------------------------------------------------------------------------- /config/initializers/doorkeeper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Doorkeeper.configure do 4 | # Change the ORM that doorkeeper will use (requires ORM extensions installed). 5 | # Check the list of supported ORMs here: https://github.com/doorkeeper-gem/doorkeeper#orms 6 | orm :active_record 7 | 8 | resource_owner_from_credentials do |_routes| 9 | User.authenticate(params[:email], params[:password]) 10 | end 11 | 12 | api_only 13 | 14 | grant_flows %w[password] 15 | 16 | # This block will be called to check whether the resource owner is authenticated or not. 17 | # resource_owner_authenticator do 18 | # raise "Please configure doorkeeper resource_owner_authenticator block located in #{__FILE__}" 19 | # # Put your resource owner authentication logic here. 20 | # # Example implementation: 21 | # # User.find_by(id: session[:user_id]) || redirect_to(new_user_session_url) 22 | # end 23 | 24 | # If you didn't skip applications controller from Doorkeeper routes in your application routes.rb 25 | # file then you need to declare this block in order to restrict access to the web interface for 26 | # adding oauth authorized applications. In other case it will return 403 Forbidden response 27 | # every time somebody will try to access the admin web interface. 28 | # 29 | # admin_authenticator do 30 | # # Put your admin authentication logic here. 31 | # # Example implementation: 32 | # 33 | # if current_user 34 | # head :forbidden unless current_user.admin? 35 | # else 36 | # redirect_to sign_in_url 37 | # end 38 | # end 39 | 40 | # You can use your own model classes if you need to extend (or even override) default 41 | # Doorkeeper models such as `Application`, `AccessToken` and `AccessGrant. 42 | # 43 | # Be default Doorkeeper ActiveRecord ORM uses it's own classes: 44 | # 45 | # access_token_class "Doorkeeper::AccessToken" 46 | # access_grant_class "Doorkeeper::AccessGrant" 47 | # application_class "Doorkeeper::Application" 48 | # 49 | # Don't forget to include Doorkeeper ORM mixins into your custom models: 50 | # 51 | # * ::Doorkeeper::Orm::ActiveRecord::Mixins::AccessToken - for access token 52 | # * ::Doorkeeper::Orm::ActiveRecord::Mixins::AccessGrant - for access grant 53 | # * ::Doorkeeper::Orm::ActiveRecord::Mixins::Application - for application (OAuth2 clients) 54 | # 55 | # For example: 56 | # 57 | # access_token_class "MyAccessToken" 58 | # 59 | # class MyAccessToken < ApplicationRecord 60 | # include ::Doorkeeper::Orm::ActiveRecord::Mixins::AccessToken 61 | # 62 | # self.table_name = "hey_i_wanna_my_name" 63 | # 64 | # def destroy_me! 65 | # destroy 66 | # end 67 | # end 68 | 69 | # Enables polymorphic Resource Owner association for Access Tokens and Access Grants. 70 | # By default this option is disabled. 71 | # 72 | # Make sure you properly setup you database and have all the required columns (run 73 | # `bundle exec rails generate doorkeeper:enable_polymorphic_resource_owner` and execute Rails 74 | # migrations). 75 | # 76 | # If this option enabled, Doorkeeper will store not only Resource Owner primary key 77 | # value, but also it's type (class name). See "Polymorphic Associations" section of 78 | # Rails guides: https://guides.rubyonrails.org/association_basics.html#polymorphic-associations 79 | # 80 | # [NOTE] If you apply this option on already existing project don't forget to manually 81 | # update `resource_owner_type` column in the database and fix migration template as it will 82 | # set NOT NULL constraint for Access Grants table. 83 | # 84 | # use_polymorphic_resource_owner 85 | 86 | # If you are planning to use Doorkeeper in Rails 5 API-only application, then you might 87 | # want to use API mode that will skip all the views management and change the way how 88 | # Doorkeeper responds to a requests. 89 | # 90 | # api_only 91 | 92 | # Enforce token request content type to application/x-www-form-urlencoded. 93 | # It is not enabled by default to not break prior versions of the gem. 94 | # 95 | # enforce_content_type 96 | 97 | # Authorization Code expiration time (default: 10 minutes). 98 | # 99 | # authorization_code_expires_in 10.minutes 100 | 101 | # Access token expiration time (default: 2 hours). 102 | # If you want to disable expiration, set this to `nil`. 103 | # 104 | # access_token_expires_in 2.hours 105 | 106 | # Assign custom TTL for access tokens. Will be used instead of access_token_expires_in 107 | # option if defined. In case the block returns `nil` value Doorkeeper fallbacks to 108 | # +access_token_expires_in+ configuration option value. If you really need to issue a 109 | # non-expiring access token (which is not recommended) then you need to return 110 | # Float::INFINITY from this block. 111 | # 112 | # `context` has the following properties available: 113 | # 114 | # `client` - the OAuth client application (see Doorkeeper::OAuth::Client) 115 | # `grant_type` - the grant type of the request (see Doorkeeper::OAuth) 116 | # `scopes` - the requested scopes (see Doorkeeper::OAuth::Scopes) 117 | # 118 | # custom_access_token_expires_in do |context| 119 | # context.client.application.additional_settings.implicit_oauth_expiration 120 | # end 121 | 122 | # Use a custom class for generating the access token. 123 | # See https://doorkeeper.gitbook.io/guides/configuration/other-configurations#custom-access-token-generator 124 | # 125 | # access_token_generator '::Doorkeeper::JWT' 126 | 127 | # The controller +Doorkeeper::ApplicationController+ inherits from. 128 | # Defaults to +ActionController::Base+ unless +api_only+ is set, which changes the default to 129 | # +ActionController::API+. The return value of this option must be a stringified class name. 130 | # See https://doorkeeper.gitbook.io/guides/configuration/other-configurations#custom-base-controller 131 | # 132 | # base_controller 'ApplicationController' 133 | 134 | # Reuse access token for the same resource owner within an application (disabled by default). 135 | # 136 | # This option protects your application from creating new tokens before old valid one becomes 137 | # expired so your database doesn't bloat. Keep in mind that when this option is `on` Doorkeeper 138 | # doesn't updates existing token expiration time, it will create a new token instead. 139 | # Rationale: https://github.com/doorkeeper-gem/doorkeeper/issues/383 140 | # 141 | # You can not enable this option together with +hash_token_secrets+. 142 | # 143 | # reuse_access_token 144 | 145 | # In case you enabled `reuse_access_token` option Doorkeeper will try to find matching 146 | # token using `matching_token_for` Access Token API that searches for valid records 147 | # in batches in order not to pollute the memory with all the database records. By default 148 | # Doorkeeper uses batch size of 10 000 records. You can increase or decrease this value 149 | # depending on your needs and server capabilities. 150 | # 151 | # token_lookup_batch_size 10_000 152 | 153 | # Set a limit for token_reuse if using reuse_access_token option 154 | # 155 | # This option limits token_reusability to some extent. 156 | # If not set then access_token will be reused unless it expires. 157 | # Rationale: https://github.com/doorkeeper-gem/doorkeeper/issues/1189 158 | # 159 | # This option should be a percentage(i.e. (0,100]) 160 | # 161 | # token_reuse_limit 100 162 | 163 | # Only allow one valid access token obtained via client credentials 164 | # per client. If a new access token is obtained before the old one 165 | # expired, the old one gets revoked (disabled by default) 166 | # 167 | # When enabling this option, make sure that you do not expect multiple processes 168 | # using the same credentials at the same time (e.g. web servers spanning 169 | # multiple machines and/or processes). 170 | # 171 | # revoke_previous_client_credentials_token 172 | 173 | # Hash access and refresh tokens before persisting them. 174 | # This will disable the possibility to use +reuse_access_token+ 175 | # since plain values can no longer be retrieved. 176 | # 177 | # Note: If you are already a user of doorkeeper and have existing tokens 178 | # in your installation, they will be invalid without enabling the additional 179 | # setting `fallback_to_plain_secrets` below. 180 | # 181 | # hash_token_secrets 182 | # By default, token secrets will be hashed using the 183 | # +Doorkeeper::Hashing::SHA256+ strategy. 184 | # 185 | # If you wish to use another hashing implementation, you can override 186 | # this strategy as follows: 187 | # 188 | # hash_token_secrets using: '::Doorkeeper::Hashing::MyCustomHashImpl' 189 | # 190 | # Keep in mind that changing the hashing function will invalidate all existing 191 | # secrets, if there are any. 192 | 193 | # Hash application secrets before persisting them. 194 | # 195 | # hash_application_secrets 196 | # 197 | # By default, applications will be hashed 198 | # with the +Doorkeeper::SecretStoring::SHA256+ strategy. 199 | # 200 | # If you wish to use bcrypt for application secret hashing, uncomment 201 | # this line instead: 202 | # 203 | # hash_application_secrets using: '::Doorkeeper::SecretStoring::BCrypt' 204 | 205 | # When the above option is enabled, and a hashed token or secret is not found, 206 | # you can allow to fall back to another strategy. For users upgrading 207 | # doorkeeper and wishing to enable hashing, you will probably want to enable 208 | # the fallback to plain tokens. 209 | # 210 | # This will ensure that old access tokens and secrets 211 | # will remain valid even if the hashing above is enabled. 212 | # 213 | # fallback_to_plain_secrets 214 | 215 | # Issue access tokens with refresh token (disabled by default), you may also 216 | # pass a block which accepts `context` to customize when to give a refresh 217 | # token or not. Similar to +custom_access_token_expires_in+, `context` has 218 | # the following properties: 219 | # 220 | # `client` - the OAuth client application (see Doorkeeper::OAuth::Client) 221 | # `grant_type` - the grant type of the request (see Doorkeeper::OAuth) 222 | # `scopes` - the requested scopes (see Doorkeeper::OAuth::Scopes) 223 | # 224 | # use_refresh_token 225 | 226 | # Provide support for an owner to be assigned to each registered application (disabled by default) 227 | # Optional parameter confirmation: true (default: false) if you want to enforce ownership of 228 | # a registered application 229 | # NOTE: you must also run the rails g doorkeeper:application_owner generator 230 | # to provide the necessary support 231 | # 232 | # enable_application_owner confirmation: false 233 | 234 | # Define access token scopes for your provider 235 | # For more information go to 236 | # https://doorkeeper.gitbook.io/guides/ruby-on-rails/scopes 237 | # 238 | # default_scopes :public 239 | # optional_scopes :write, :update 240 | 241 | # Allows to restrict only certain scopes for grant_type. 242 | # By default, all the scopes will be available for all the grant types. 243 | # 244 | # Keys to this hash should be the name of grant_type and 245 | # values should be the array of scopes for that grant type. 246 | # Note: scopes should be from configured_scopes (i.e. default or optional) 247 | # 248 | # scopes_by_grant_type password: [:write], client_credentials: [:update] 249 | 250 | # Forbids creating/updating applications with arbitrary scopes that are 251 | # not in configuration, i.e. +default_scopes+ or +optional_scopes+. 252 | # (disabled by default) 253 | # 254 | # enforce_configured_scopes 255 | 256 | # Change the way client credentials are retrieved from the request object. 257 | # By default it retrieves first from the `HTTP_AUTHORIZATION` header, then 258 | # falls back to the `:client_id` and `:client_secret` params from the `params` object. 259 | # Check out https://github.com/doorkeeper-gem/doorkeeper/wiki/Changing-how-clients-are-authenticated 260 | # for more information on customization 261 | # 262 | # client_credentials :from_basic, :from_params 263 | 264 | # Change the way access token is authenticated from the request object. 265 | # By default it retrieves first from the `HTTP_AUTHORIZATION` header, then 266 | # falls back to the `:access_token` or `:bearer_token` params from the `params` object. 267 | # Check out https://github.com/doorkeeper-gem/doorkeeper/wiki/Changing-how-clients-are-authenticated 268 | # for more information on customization 269 | # 270 | # access_token_methods :from_bearer_authorization, :from_access_token_param, :from_bearer_param 271 | 272 | # Forces the usage of the HTTPS protocol in non-native redirect uris (enabled 273 | # by default in non-development environments). OAuth2 delegates security in 274 | # communication to the HTTPS protocol so it is wise to keep this enabled. 275 | # 276 | # Callable objects such as proc, lambda, block or any object that responds to 277 | # #call can be used in order to allow conditional checks (to allow non-SSL 278 | # redirects to localhost for example). 279 | # 280 | # force_ssl_in_redirect_uri !Rails.env.development? 281 | # 282 | # force_ssl_in_redirect_uri { |uri| uri.host != 'localhost' } 283 | 284 | # Specify what redirect URI's you want to block during Application creation. 285 | # Any redirect URI is whitelisted by default. 286 | # 287 | # You can use this option in order to forbid URI's with 'javascript' scheme 288 | # for example. 289 | # 290 | # forbid_redirect_uri { |uri| uri.scheme.to_s.downcase == 'javascript' } 291 | 292 | # Allows to set blank redirect URIs for Applications in case Doorkeeper configured 293 | # to use URI-less OAuth grant flows like Client Credentials or Resource Owner 294 | # Password Credentials. The option is on by default and checks configured grant 295 | # types, but you **need** to manually drop `NOT NULL` constraint from `redirect_uri` 296 | # column for `oauth_applications` database table. 297 | # 298 | # You can completely disable this feature with: 299 | # 300 | # allow_blank_redirect_uri false 301 | # 302 | # Or you can define your custom check: 303 | # 304 | # allow_blank_redirect_uri do |grant_flows, client| 305 | # client.superapp? 306 | # end 307 | 308 | # Specify how authorization errors should be handled. 309 | # By default, doorkeeper renders json errors when access token 310 | # is invalid, expired, revoked or has invalid scopes. 311 | # 312 | # If you want to render error response yourself (i.e. rescue exceptions), 313 | # set +handle_auth_errors+ to `:raise` and rescue Doorkeeper::Errors::InvalidToken 314 | # or following specific errors: 315 | # 316 | # Doorkeeper::Errors::TokenForbidden, Doorkeeper::Errors::TokenExpired, 317 | # Doorkeeper::Errors::TokenRevoked, Doorkeeper::Errors::TokenUnknown 318 | # 319 | # handle_auth_errors :raise 320 | 321 | # Customize token introspection response. 322 | # Allows to add your own fields to default one that are required by the OAuth spec 323 | # for the introspection response. It could be `sub`, `aud` and so on. 324 | # This configuration option can be a proc, lambda or any Ruby object responds 325 | # to `.call` method and result of it's invocation must be a Hash. 326 | # 327 | # custom_introspection_response do |token, context| 328 | # { 329 | # "sub": "Z5O3upPC88QrAjx00dis", 330 | # "aud": "https://protected.example.net/resource", 331 | # "username": User.find(token.resource_owner_id).username 332 | # } 333 | # end 334 | # 335 | # or 336 | # 337 | # custom_introspection_response CustomIntrospectionResponder 338 | 339 | # Specify what grant flows are enabled in array of Strings. The valid 340 | # strings and the flows they enable are: 341 | # 342 | # "authorization_code" => Authorization Code Grant Flow 343 | # "implicit" => Implicit Grant Flow 344 | # "password" => Resource Owner Password Credentials Grant Flow 345 | # "client_credentials" => Client Credentials Grant Flow 346 | # 347 | # If not specified, Doorkeeper enables authorization_code and 348 | # client_credentials. 349 | # 350 | # implicit and password grant flows have risks that you should understand 351 | # before enabling: 352 | # http://tools.ietf.org/html/rfc6819#section-4.4.2 353 | # http://tools.ietf.org/html/rfc6819#section-4.4.3 354 | # 355 | # grant_flows %w[authorization_code client_credentials] 356 | 357 | # Allows to customize OAuth grant flows that +each+ application support. 358 | # You can configure a custom block (or use a class respond to `#call`) that must 359 | # return `true` in case Application instance supports requested OAuth grant flow 360 | # during the authorization request to the server. This configuration +doesn't+ 361 | # set flows per application, it only allows to check if application supports 362 | # specific grant flow. 363 | # 364 | # For example you can add an additional database column to `oauth_applications` table, 365 | # say `t.array :grant_flows, default: []`, and store allowed grant flows that can 366 | # be used with this application there. Then when authorization requested Doorkeeper 367 | # will call this block to check if specific Application (passed with client_id and/or 368 | # client_secret) is allowed to perform the request for the specific grant type 369 | # (authorization, password, client_credentials, etc). 370 | # 371 | # Example of the block: 372 | # 373 | # ->(flow, client) { client.grant_flows.include?(flow) } 374 | # 375 | # In case this option invocation result is `false`, Doorkeeper server returns 376 | # :unauthorized_client error and stops the request. 377 | # 378 | # @param allow_grant_flow_for_client [Proc] Block or any object respond to #call 379 | # @return [Boolean] `true` if allow or `false` if forbid the request 380 | # 381 | # allow_grant_flow_for_client do |grant_flow, client| 382 | # # `grant_flows` is an Array column with grant 383 | # # flows that application supports 384 | # 385 | # client.grant_flows.include?(grant_flow) 386 | # end 387 | 388 | # If you need arbitrary Resource Owner-Client authorization you can enable this option 389 | # and implement the check your need. Config option must respond to #call and return 390 | # true in case resource owner authorized for the specific application or false in other 391 | # cases. 392 | # 393 | # Be default all Resource Owners are authorized to any Client (application). 394 | # 395 | # authorize_resource_owner_for_client do |client, resource_owner| 396 | # resource_owner.admin? || client.owners_whitelist.include?(resource_owner) 397 | # end 398 | 399 | # Hook into the strategies' request & response life-cycle in case your 400 | # application needs advanced customization or logging: 401 | # 402 | # before_successful_strategy_response do |request| 403 | # puts "BEFORE HOOK FIRED! #{request}" 404 | # end 405 | # 406 | # after_successful_strategy_response do |request, response| 407 | # puts "AFTER HOOK FIRED! #{request}, #{response}" 408 | # end 409 | 410 | # Hook into Authorization flow in order to implement Single Sign Out 411 | # or add any other functionality. Inside the block you have an access 412 | # to `controller` (authorizations controller instance) and `context` 413 | # (Doorkeeper::OAuth::Hooks::Context instance) which provides pre auth 414 | # or auth objects with issued token based on hook type (before or after). 415 | # 416 | # before_successful_authorization do |controller, context| 417 | # Rails.logger.info(controller.request.params.inspect) 418 | # 419 | # Rails.logger.info(context.pre_auth.inspect) 420 | # end 421 | # 422 | # after_successful_authorization do |controller, context| 423 | # controller.session[:logout_urls] << 424 | # Doorkeeper::Application 425 | # .find_by(controller.request.params.slice(:redirect_uri)) 426 | # .logout_uri 427 | # 428 | # Rails.logger.info(context.auth.inspect) 429 | # Rails.logger.info(context.issued_token) 430 | # end 431 | 432 | # Under some circumstances you might want to have applications auto-approved, 433 | # so that the user skips the authorization step. 434 | # For example if dealing with a trusted application. 435 | # 436 | # skip_authorization do |resource_owner, client| 437 | # client.superapp? or resource_owner.admin? 438 | # end 439 | 440 | # Configure custom constraints for the Token Introspection request. 441 | # By default this configuration option allows to introspect a token by another 442 | # token of the same application, OR to introspect the token that belongs to 443 | # authorized client (from authenticated client) OR when token doesn't 444 | # belong to any client (public token). Otherwise requester has no access to the 445 | # introspection and it will return response as stated in the RFC. 446 | # 447 | # Block arguments: 448 | # 449 | # @param token [Doorkeeper::AccessToken] 450 | # token to be introspected 451 | # 452 | # @param authorized_client [Doorkeeper::Application] 453 | # authorized client (if request is authorized using Basic auth with 454 | # Client Credentials for example) 455 | # 456 | # @param authorized_token [Doorkeeper::AccessToken] 457 | # Bearer token used to authorize the request 458 | # 459 | # In case the block returns `nil` or `false` introspection responses with 401 status code 460 | # when using authorized token to introspect, or you'll get 200 with { "active": false } body 461 | # when using authorized client to introspect as stated in the 462 | # RFC 7662 section 2.2. Introspection Response. 463 | # 464 | # Using with caution: 465 | # Keep in mind that these three parameters pass to block can be nil as following case: 466 | # `authorized_client` is nil if and only if `authorized_token` is present, and vice versa. 467 | # `token` will be nil if and only if `authorized_token` is present. 468 | # So remember to use `&` or check if it is present before calling method on 469 | # them to make sure you doesn't get NoMethodError exception. 470 | # 471 | # You can define your custom check: 472 | # 473 | # allow_token_introspection do |token, authorized_client, authorized_token| 474 | # if authorized_token 475 | # # customize: require `introspection` scope 476 | # authorized_token.application == token&.application || 477 | # authorized_token.scopes.include?("introspection") 478 | # elsif token.application 479 | # # `protected_resource` is a new database boolean column, for example 480 | # authorized_client == token.application || authorized_client.protected_resource? 481 | # else 482 | # # public token (when token.application is nil, token doesn't belong to any application) 483 | # true 484 | # end 485 | # end 486 | # 487 | # Or you can completely disable any token introspection: 488 | # 489 | # allow_token_introspection false 490 | # 491 | # If you need to block the request at all, then configure your routes.rb or web-server 492 | # like nginx to forbid the request. 493 | 494 | # WWW-Authenticate Realm (default: "Doorkeeper"). 495 | # 496 | # realm "Doorkeeper" 497 | end 498 | --------------------------------------------------------------------------------