Commit 72bf4a7

mo <mo.khan@gmail.com>
2019-06-15 20:32:08
install rubocop rails
1 parent 8945154
app/controllers/oauth/clients_controller.rb
@@ -42,7 +42,7 @@ module Oauth
 
         Token.find(claims[:jti])
       end
-      return request_http_token_authentication unless token.present?
+      return request_http_token_authentication if token.blank?
 
       unless Client.where(id: params[:id]).exists?
         token.revoke!
app/controllers/oauth/mes_controller.rb
@@ -16,7 +16,7 @@ module Oauth
         claims = Token.claims_for(token)
         Token.revoked?(claims[:jti]) ? nil : claims
       end
-      request_http_token_authentication if @claims.nil? || @claims.empty?
+      request_http_token_authentication if @claims.blank?
     end
   end
 end
app/controllers/mfas_controller.rb
@@ -9,7 +9,7 @@ class MfasController < ApplicationController
     if current_user.mfa.authenticate(secure_params[:code])
       reset_session
       session[:user_session_key] = Current.user_session.key
-      session[:mfa] = { issued_at: Time.now.utc.to_i }
+      session[:mfa] = { issued_at: Time.current.utc.to_i }
       redirect_to response_path
     else
       redirect_to new_mfa_path, error: "Invalid code"
app/models/scim/visitor.rb
@@ -108,7 +108,7 @@ module Scim
     def cast_value_from(node)
       case @clazz.columns_hash[attr_for(node).to_s].type
       when :datetime
-        DateTime.parse(node.value)
+        DateTime.parse(node.value).utc
       else
         node.value.to_s
       end
app/models/authorization.rb
@@ -5,19 +5,19 @@ class Authorization < ApplicationRecord
   has_secure_token :code
   belongs_to :user
   belongs_to :client
-  has_many :tokens
+  has_many :tokens, dependent: :delete_all
   enum challenge_method: { plain: 0, sha256: 1 }
 
   scope :active, -> { where.not(id: revoked.or(where(id: expired))) }
-  scope :revoked, -> { where('revoked_at < ?', Time.now) }
-  scope :expired, -> { where('expired_at < ?', Time.now) }
+  scope :revoked, -> { where('revoked_at < ?', Time.current) }
+  scope :expired, -> { where('expired_at < ?', Time.current) }
 
   after_initialize do
-    self.expired_at = 10.minutes.from_now unless expired_at.present?
+    self.expired_at = 10.minutes.from_now if expired_at.blank?
   end
 
   def valid_verifier?(code_verifier)
-    return true unless challenge.present?
+    return true if challenge.blank?
 
     challenge ==
       if sha256?
@@ -39,7 +39,7 @@ class Authorization < ApplicationRecord
   def revoke!
     raise 'already revoked' if revoked?
 
-    now = Time.now
+    now = Time.current
     update!(revoked_at: now)
     tokens.update_all(revoked_at: now)
   end
app/models/client.rb
@@ -4,7 +4,7 @@ class Client < ApplicationRecord
   RESPONSE_TYPES = %w[code token].freeze
   audited
   has_secure_password
-  has_many :authorizations
+  has_many :authorizations, dependent: :delete_all
   attribute :redirect_uris, :string, array: true
   enum token_endpoint_auth_method: {
     client_secret_basic: 0,
@@ -39,7 +39,7 @@ class Client < ApplicationRecord
     transaction do
       Token
         .active.where(subject: self, audience: self)
-        .update_all(revoked_at: Time.now)
+        .update_all(revoked_at: Time.current)
       Token.create!(subject: self, audience: self, token_type: :access)
     end
   end
app/models/token.rb
@@ -8,8 +8,8 @@ class Token < ApplicationRecord
   belongs_to :audience, polymorphic: true
 
   scope :active, -> { where.not(id: revoked.or(where(id: expired))) }
-  scope :expired, -> { where('expired_at < ?', Time.now) }
-  scope :revoked, -> { where('revoked_at < ?', Time.now) }
+  scope :expired, -> { where('expired_at < ?', Time.current) }
+  scope :revoked, -> { where('revoked_at < ?', Time.current) }
 
   after_initialize do |x|
     if x.expired_at.nil?
@@ -22,7 +22,7 @@ class Token < ApplicationRecord
   end
 
   def revoke!
-    update!(revoked_at: Time.now)
+    update!(revoked_at: Time.current)
     authorization&.revoke!
   end
 
app/models/user.rb
@@ -5,7 +5,11 @@ class User < ApplicationRecord
   VALID_LOCALES = I18n.available_locales.map(&:to_s)
   audited except: [:password_digest, :mfa_secret]
   has_secure_password
-  has_many :sessions, foreign_key: "user_id", class_name: UserSession.name
+  has_many :sessions,
+    foreign_key: "user_id",
+    class_name: 'UserSession',
+    inverse_of: :user,
+    dependent: :delete_all
 
   validates :email, presence: true, email: true, uniqueness: {
     case_sensitive: false
app/models/user_session.rb
@@ -23,7 +23,7 @@ class UserSession < ApplicationRecord
   end
 
   def revoke!
-    update!(revoked_at: Time.now)
+    update!(revoked_at: Time.current)
   end
 
   def sudo?
@@ -31,12 +31,12 @@ class UserSession < ApplicationRecord
   end
 
   def sudo!
-    update!(sudo_enabled_at: Time.now)
+    update!(sudo_enabled_at: Time.current)
   end
 
   def access(request)
     update(
-      accessed_at: Time.now,
+      accessed_at: Time.current,
       ip: request.ip,
       user_agent: request.user_agent,
     )
db/migrate/20180922211216_add_timezone_locale_to_users.rb
@@ -2,7 +2,7 @@
 
 class AddTimezoneLocaleToUsers < ActiveRecord::Migration[5.2]
   def change
-    change_table :users do |t|
+    change_table :users, bulk: true do |t|
       t.column :locale, :string, default: 'en', null: false
       t.column :timezone, :string, default: 'Etc/UTC', null: false
     end
db/migrate/20181020161349_change_clients.rb
@@ -2,10 +2,12 @@
 
 class ChangeClients < ActiveRecord::Migration[5.2]
   def change
-    add_column :clients, :redirect_uris, :text, array: true, default: [], null: false
-    add_column :clients, :token_endpoint_auth_method, :integer, default: 0, null: false
-    add_column :clients, :logo_uri, :string
-    add_column :clients, :jwks_uri, :string
-    remove_column :clients, :redirect_uri
+    change_table :clients, bulk: true do |t|
+      t.column :redirect_uris, :text, array: true, default: [], null: false
+      t.column :token_endpoint_auth_method, :integer, default: 0, null: false
+      t.column :logo_uri, :string
+      t.column :jwks_uri, :string
+    end
+    remove_column :clients, :redirect_uri, :string
   end
 end
lib/tasks/doc.rake
@@ -7,13 +7,13 @@ namespace :doc do
     {
       config: Rails.root.join("config", "jekyll.yml").to_s,
       source: Rails.root.join('doc').to_s,
-      destination: Rails.root.join('public/doc').to_s
+      destination: Rails.root.join('public', 'doc').to_s
     }
   end
 
   desc 'Clean the API documentation'
   task :clean do
-    rm_rf Rails.root.join('public/doc')
+    rm_rf Rails.root.join('public', 'doc')
   end
 
   desc "Build static pages"
spec/factories/token.rb
@@ -15,7 +15,7 @@ FactoryBot.define do
     end
 
     trait :revoked do
-      revoked_at { Time.now }
+      revoked_at { Time.current }
     end
 
     trait :expired do
spec/models/scim/search_spec.rb
@@ -98,7 +98,7 @@ RSpec.describe ::Scim::Search do
       freeze_time
       random_user.update!(updated_at: 10.minutes.from_now)
 
-      results = subject.for("meta.lastModified gt \"#{Time.now.iso8601}\"")
+      results = subject.for("meta.lastModified gt \"#{Time.current.iso8601}\"")
       expect(results).to match_array([random_user])
     end
 
@@ -114,7 +114,7 @@ RSpec.describe ::Scim::Search do
       freeze_time
       random_user.update!(updated_at: 10.minutes.from_now)
 
-      results = subject.for("meta.lastModified lt \"#{Time.now.iso8601}\"")
+      results = subject.for("meta.lastModified lt \"#{Time.current.iso8601}\"")
       expect(results).to match_array(users - [random_user])
     end
 
spec/models/token_spec.rb
@@ -12,7 +12,7 @@ RSpec.describe Token, type: :model do
         subject.revoke!
       end
 
-      specify { expect(subject.reload.revoked_at.to_i).to eql(DateTime.now.to_i) }
+      specify { expect(subject.reload.revoked_at.to_i).to eql(Time.current.to_i) }
     end
 
     context "when a token associated with an authorization grant is revoked" do
spec/models/user_session_spec.rb
@@ -22,7 +22,7 @@ RSpec.describe UserSession do
       result
     end
 
-    specify { expect(subject.accessed_at).to eql(Time.now) }
+    specify { expect(subject.accessed_at).to eql(Time.current) }
     specify { expect(subject.ip).to eql(request.ip) }
     specify { expect(subject.user_agent).to eql(request.user_agent) }
     specify { expect(subject).to be_persisted }
spec/models/user_spec.rb
@@ -57,7 +57,7 @@ RSpec.describe User do
       freeze_time
       random_user.update!(updated_at: 10.minutes.from_now)
 
-      results = subject.scim_search("meta.lastModified gt \"#{Time.now.iso8601}\"")
+      results = subject.scim_search("meta.lastModified gt \"#{Time.current.iso8601}\"")
       expect(results).to match_array([random_user])
     end
 
@@ -73,7 +73,7 @@ RSpec.describe User do
       freeze_time
       random_user.update!(updated_at: 10.minutes.from_now)
 
-      results = subject.scim_search("meta.lastModified lt \"#{Time.now.iso8601}\"")
+      results = subject.scim_search("meta.lastModified lt \"#{Time.current.iso8601}\"")
       expect(results).to match_array(users - [random_user])
     end
 
spec/documentation.rb
@@ -25,7 +25,7 @@ RSpec.configure do |config|
     puts "Booting"
     $server.boot
     print "." until $server.responsive?
-    FileUtils.rm_rf(Rails.root.join('tmp/_cassettes/'))
+    FileUtils.rm_rf(Rails.root.join('tmp', '_cassettes'))
     Net::Hippie.logger = Logger.new('/dev/null')
     VCR.configure do |x|
       x.cassette_library_dir = "tmp/_cassettes"
spec/i18n_spec.rb
@@ -9,19 +9,19 @@ RSpec.describe 'I18n' do
 
   it 'does not have missing keys' do
     expect(missing_keys).to be_empty,
-                            "Missing #{missing_keys.leaves.count} i18n keys, run `i18n-tasks missing' to show them"
+      "Missing #{missing_keys.leaves.count} i18n keys, run `i18n-tasks missing' to show them"
   end
 
   it 'does not have unused keys' do
     expect(unused_keys).to be_empty,
-                           "#{unused_keys.leaves.count} unused i18n keys, run `i18n-tasks unused' to show them"
+      "#{unused_keys.leaves.count} unused i18n keys, run `i18n-tasks unused' to show them"
   end
 
   it 'files are normalized' do
     non_normalized = i18n.non_normalized_paths
     error_message = "The following files need to be normalized:\n" \
-                    "#{non_normalized.map { |path| "  #{path}" }.join("\n")}\n" \
-                    'Please run `i18n-tasks normalize` to fix'
+      "#{non_normalized.map { |path| "  #{path}" }.join("\n")}\n" \
+      'Please run `i18n-tasks normalize` to fix'
     expect(non_normalized).to be_empty, error_message
   end
 end
spec/rails_helper.rb
@@ -22,7 +22,7 @@ require 'rspec/rails'
 # directory. Alternatively, in the individual `*_spec.rb` files, manually
 # require only the support files necessary.
 #
-Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
+Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }
 # Checks for pending migrations and applies them before tests are run.
 # If you are not using ActiveRecord, you can remove this line.
 ActiveRecord::Migration.maintain_test_schema!
.rubocop.yml
@@ -1,4 +1,6 @@
-require: rubocop-rspec
+require:
+  - rubocop-rails
+  - rubocop-rspec
 # For a list of available cops see:
 # https://github.com/bbatsov/rubocop/blob/master/config/default.yml
 AllCops:
@@ -15,6 +17,9 @@ AllCops:
     - 'tmp/**/*'
     - 'vendor/**/*'
 
+Layout/AlignArguments:
+  EnforcedStyle: with_fixed_indentation
+
 Layout/IndentFirstArrayElement:
   EnforcedStyle: consistent
 
@@ -43,6 +48,13 @@ Metrics/PerceivedComplexity:
 Naming/RescuedExceptionsVariableName:
   PreferredName: error
 
+Rails/CreateTableWithTimestamps:
+  Exclude:
+    - 'db/migrate/20180923222720_install_audited.rb'
+
+Rails/SkipsModelValidations:
+  Enabled: false
+
 RSpec/DescribeClass:
   Enabled: false
 
Gemfile
@@ -37,6 +37,7 @@ group :development do
   gem 'erb_lint', require: false
   gem 'listen', '>= 3.0.5', '< 3.2'
   gem 'rubocop', '~> 0.59', require: false
+  gem 'rubocop-rails', '~> 2.0', require: false
   gem 'web-console', '>= 3.3.0'
 end
 group :development, :test do
Gemfile.lock
@@ -284,6 +284,9 @@ GEM
       rainbow (>= 2.2.2, < 4.0)
       ruby-progressbar (~> 1.7)
       unicode-display_width (>= 1.4.0, < 1.7)
+    rubocop-rails (2.0.1)
+      rack (>= 1.1)
+      rubocop (>= 0.70.0)
     rubocop-rspec (1.33.0)
       rubocop (>= 0.60.0)
     ruby-progressbar (1.10.1)
@@ -390,6 +393,7 @@ DEPENDENCIES
   rotp (~> 3.3)
   rspec-rails (~> 3.8)
   rubocop (~> 0.59)
+  rubocop-rails (~> 2.0)
   rubocop-rspec (~> 1.30)
   saml-kit (~> 1.0)
   scim-kit!