Check the oauth token and then use the capabilities directly
authorAndy Allan <git@gravitystorm.co.uk>
Wed, 24 Oct 2018 14:48:54 +0000 (16:48 +0200)
committerAndy Allan <git@gravitystorm.co.uk>
Wed, 24 Oct 2018 14:48:54 +0000 (16:48 +0200)
app/controllers/application_controller.rb
app/models/capability.rb
test/models/capability_test.rb

index 690bdf5ca5140dad6448e86af7e6d02732ce7c35..20fcc5f4739ff1bbb42054feec5c7042fa5fa28d 100644 (file)
@@ -469,11 +469,12 @@ class ApplicationController < ActionController::Base
   end
 
   def current_ability
-    Ability.new(current_user).merge(granted_capability)
-  end
-
-  def granted_capability
-    Capability.new(current_user, current_token)
+    # Add in capabilities from the oauth token if it exists and is a valid access token
+    if Authenticator.new(self, [:token]).allow?
+      Ability.new(current_user).merge(Capability.new(current_token))
+    else
+      Ability.new(current_user)
+    end
   end
 
   def deny_access(_exception)
index 72c5545cb4ec5a9b04d5e0c4b5d453765fa754cc..2a5c927748bbdb969b6d37e376a099374085bed4 100644 (file)
@@ -3,11 +3,9 @@
 class Capability
   include CanCan::Ability
 
-  def initialize(user, token)
-    if user
-      can [:read, :read_one], UserPreference if capability?(token, :allow_read_prefs)
-      can [:update, :update_one, :delete_one], UserPreference if capability?(token, :allow_write_prefs)
-    end
+  def initialize(token)
+    can [:read, :read_one], UserPreference if capability?(token, :allow_read_prefs)
+    can [:update, :update_one, :delete_one], UserPreference if capability?(token, :allow_write_prefs)
   end
 
   private
index d08d182c2bd90353e225dbf37a19fd2044cd4028..a25c670434677ffe098da203fd9b7a534fa8ba15 100644 (file)
@@ -14,22 +14,20 @@ end
 
 class UserCapabilityTest < CapabilityTest
   test "user preferences" do
-    user = create(:user)
-
     # a user with no tokens
-    capability = Capability.new create(:user), nil
+    capability = Capability.new nil
     [:read, :read_one, :update, :update_one, :delete_one].each do |act|
       assert capability.cannot? act, UserPreference
     end
 
     # A user with empty tokens
-    capability = Capability.new create(:user), tokens
+    capability = Capability.new tokens
 
     [:read, :read_one, :update, :update_one, :delete_one].each do |act|
       assert capability.cannot? act, UserPreference
     end
 
-    capability = Capability.new user, tokens(:allow_read_prefs)
+    capability = Capability.new tokens(:allow_read_prefs)
 
     [:update, :update_one, :delete_one].each do |act|
       assert capability.cannot? act, UserPreference
@@ -39,7 +37,7 @@ class UserCapabilityTest < CapabilityTest
       assert capability.can? act, UserPreference
     end
 
-    capability = Capability.new user, tokens(:allow_write_prefs)
+    capability = Capability.new tokens(:allow_write_prefs)
     [:read, :read_one].each do |act|
       assert capability.cannot? act, UserPreference
     end