Merge branch '1922-cache-discovery-python'
[arvados.git] / services / api / app / controllers / arvados / v1 / api_client_authorizations_controller.rb
1 class Arvados::V1::ApiClientAuthorizationsController < ApplicationController
2   accept_attribute_as_json :scopes, Array
3   before_filter :current_api_client_is_trusted
4   before_filter :admin_required, :only => :create_system_auth
5
6   def self._create_system_auth_requires_parameters
7     {
8       api_client_id: {type: 'integer', required: false},
9       scopes: {type: 'array', required: false}
10     }
11   end
12   def create_system_auth
13     @object = ApiClientAuthorization.
14       new(user_id: system_user.id,
15           api_client_id: params[:api_client_id] || current_api_client.andand.id,
16           created_by_ip_address: remote_ip,
17           scopes: Oj.load(params[:scopes] || '["all"]'))
18     @object.save!
19     show
20   end
21
22   def create
23     if resource_attrs[:owner_uuid]
24       # The model has an owner_id attribute instead of owner_uuid, but
25       # we can't expect the client to know the local numeric ID. We
26       # translate UUID to numeric ID here.
27       resource_attrs[:user_id] =
28         User.where(uuid: resource_attrs.delete(:owner_uuid)).first.andand.id
29     end
30     super
31   end
32
33   protected
34
35   def find_objects_for_index
36     # Here we are deliberately less helpful about searching for client
37     # authorizations. Rather than use the generic index/where/order
38     # features, we look up tokens belonging to the current user and
39     # filter by exact match on api_token (which we expect in the form
40     # of a where[uuid] parameter to make things easier for API client
41     # libraries).
42     @objects = model_class.
43       includes(:user, :api_client).
44       where('user_id=? and (? or api_token=?)', current_user.id, !@where['uuid'], @where['uuid']).
45       order('created_at desc')
46   end
47
48   def find_object_by_uuid
49     # Again, to make things easier for the client and our own routing,
50     # here we look for the api_token key in a "uuid" (POST) or "id"
51     # (GET) parameter.
52     @object = model_class.where('api_token=?', params[:uuid] || params[:id]).first
53   end
54
55   def current_api_client_is_trusted
56     unless Thread.current[:api_client].andand.is_trusted
57       render :json => { errors: ['Forbidden: this API client cannot manipulate other clients\' access tokens.'] }.to_json, status: 403
58     end
59   end
60 end