Browse Source

Enable api_token in Group API

Maarten van den Berg 6 years ago
parent
commit
6b0000f298
1 changed files with 30 additions and 9 deletions
  1. 30 9
      app/controllers/api/groups_controller.rb

+ 30 - 9
app/controllers/api/groups_controller.rb

1
+# Provides API views to read information related to Groups.
2
+# This controller provides two methods to authenticate and authorize a request:
3
+#   - By the Session used to authenticate logged-in users, and
4
+#   - By passing a custom Authorization:-header of the form 'Group :api_key'.
5
+#
6
+# If the API key method is used, the :id parameter is ignored, but still required in the URL.
1
 class Api::GroupsController < ApiController
7
 class Api::GroupsController < ApiController
2
   has_no_group = [:index]
8
   has_no_group = [:index]
3
 
9
 
4
-  before_action :set_group, except: has_no_group
5
-  before_action :require_membership!, except: has_no_group
6
-  before_action :api_require_admin!, only: has_no_group
10
+  # Session-based authentication / authorization filters
11
+  before_action :set_group,           except: has_no_group, unless: 'request.authorization'
12
+  before_action :require_membership!, except: has_no_group, unless: 'request.authorization'
13
+  before_action :api_require_admin!,  only: has_no_group,   unless: 'request.authorization'
14
+
15
+  # API key based filter (both authenticates and authorizes)
16
+  before_action :api_auth_token, if: 'request.authorization'
7
 
17
 
8
   # GET /api/groups
18
   # GET /api/groups
9
   def index
19
   def index
11
   end
21
   end
12
 
22
 
13
   # GET /api/groups/1
23
   # GET /api/groups/1
14
-  def show
15
-  end
24
+  def show; end
16
 
25
 
17
   # GET /api/groups/1/current_activities
26
   # GET /api/groups/1/current_activities
18
   def current_activities
27
   def current_activities
33
   end
42
   end
34
 
43
 
35
   private
44
   private
36
-    # Use callbacks to share common setup or constraints between actions.
37
-    def set_group
38
-      @group = Group.find(params[:id])
39
-    end
45
+
46
+  # Set group from the :id parameter.
47
+  def set_group
48
+    @group = Group.find(params[:id])
49
+  end
50
+
51
+  # Authenticate a request by a 'Authorization: Group xxx'-header.
52
+  # Asserts that the client meant to pass a Group API key, and then sets the
53
+  # @group variable from the key's associated group.
54
+  def api_auth_token
55
+    words = request.authorization.split(' ')
56
+    head :unauthorized unless words[0].casecmp('Group').zero?
57
+
58
+    @group = Group.find_by api_token: words[1]
59
+    head :unauthorized unless @group
60
+  end
40
 end
61
 end