1 class ApplicationController < ActionController::Base
2 include CurrentApiClient
5 around_filter :thread_with_auth_info, :except => [:render_error, :render_not_found]
7 before_filter :remote_ip
8 before_filter :require_auth_scope_all, :except => :render_not_found
9 before_filter :catch_redirect_hint
11 before_filter :load_where_param, :only => :index
12 before_filter :find_objects_for_index, :only => :index
13 before_filter :find_object_by_uuid, :except => [:index, :create]
15 attr_accessor :resource_attrs
19 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
20 @objects.each(&:eager_load_associations)
27 render json: @object.as_api_response
29 render_not_found("object not found")
34 @object = model_class.new resource_attrs
40 attrs_to_update = resource_attrs.reject { |k,v|
41 [:kind, :etag, :href].index k
43 if @object.update_attributes attrs_to_update
46 render json: { errors: @object.errors.full_messages }, status: 422
55 def catch_redirect_hint
57 if params.has_key?('redirect_to') then
58 session[:redirect_to] = params[:redirect_to]
64 rescue_from Exception,
65 :with => :render_error
66 rescue_from ActiveRecord::RecordNotFound,
67 :with => :render_not_found
68 rescue_from ActionController::RoutingError,
69 :with => :render_not_found
70 rescue_from ActionController::UnknownController,
71 :with => :render_not_found
72 rescue_from AbstractController::ActionNotFound,
73 :with => :render_not_found
74 rescue_from ArvadosModel::PermissionDeniedError,
75 :with => :render_error
79 logger.error e.inspect
80 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
81 if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
82 errors = @object.errors.full_messages
86 render json: { errors: errors }, status: 422
89 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
90 logger.error e.inspect
91 render json: { errors: ["Path not found"] }, status: 404
97 if params[:where].nil? or params[:where] == ""
99 elsif params[:where].is_a? Hash
100 @where = params[:where]
101 elsif params[:where].is_a? String
103 @where = Oj.load(params[:where])
105 raise ArgumentError.new("Could not parse \"where\" param as an object")
110 def find_objects_for_index
111 uuid_list = [current_user.uuid, *current_user.groups_i_can(:read)]
112 sanitized_uuid_list = uuid_list.
113 collect { |uuid| model_class.sanitize(uuid) }.join(', ')
114 or_references_me = ''
115 if model_class == Link and current_user
116 or_references_me = "OR (#{table_name}.link_class in (#{model_class.sanitize 'permission'}, #{model_class.sanitize 'resources'}) AND #{model_class.sanitize current_user.uuid} IN (#{table_name}.head_uuid, #{table_name}.tail_uuid))"
118 @objects ||= model_class.
119 joins("LEFT JOIN links permissions ON permissions.head_uuid in (#{table_name}.owner_uuid, #{table_name}.uuid) AND permissions.tail_uuid in (#{sanitized_uuid_list}) AND permissions.link_class='permission'").
120 where("?=? OR #{table_name}.owner_uuid in (?) OR #{table_name}.uuid=? OR permissions.head_uuid IS NOT NULL #{or_references_me}",
121 true, current_user.is_admin,
126 @where.each do |attr,value|
127 if attr == 'any' or attr == :any
128 if value.is_a?(Array) and
129 value[0] == 'contains' and
130 model_class.columns.collect(&:name).index('name') then
131 conditions[0] << " and #{table_name}.name ilike ?"
132 conditions << "%#{value[1]}%"
134 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
135 model_class.columns.collect(&:name).index(attr.to_s)
137 conditions[0] << " and #{table_name}.#{attr} is ?"
139 elsif value.is_a? Array
140 conditions[0] << " and #{table_name}.#{attr} in (?)"
142 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
143 conditions[0] << " and #{table_name}.#{attr}=?"
145 elsif value.is_a? Hash
146 # Not quite the same thing as "equal?" but better than nothing?
149 conditions[0] << " and #{table_name}.#{attr} ilike ?"
150 conditions << "%#{k}%#{v}%"
156 if conditions.length > 1
157 conditions[0].sub!(/^1=1 and /, '')
164 @objects = @objects.limit(params[:limit].to_i)
166 raise ArgumentError.new("Invalid value for limit parameter")
169 @objects = @objects.limit(100)
173 params[:order].split(',').each do |order|
174 attr, direction = order.strip.split " "
176 if attr.match /^[a-z][_a-z0-9]+$/ and
177 model_class.columns.collect(&:name).index(attr) and
178 ['asc','desc'].index direction.downcase
179 orders << "#{table_name}.#{attr} #{direction.downcase}"
184 orders << "#{table_name}.modified_at desc"
186 @objects = @objects.order(orders.join ", ")
190 return @attrs if @attrs
191 @attrs = params[resource_name]
192 if @attrs.is_a? String
193 @attrs = Oj.load @attrs
195 unless @attrs.is_a? Hash
196 message = "No #{resource_name}"
197 if resource_name.index('_')
198 message << " (or #{resource_name.camelcase(:lower)})"
200 message << " hash provided with request"
201 raise ArgumentError.new(message)
203 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
214 respond_to do |format|
216 render :json => { errors: ['Not logged in'] }.to_json, status: 401
219 redirect_to '/auth/joshid'
227 unless current_user and current_user.is_admin
228 render :json => { errors: ['Forbidden'] }.to_json, status: 403
232 def require_auth_scope_all
233 require_login and require_auth_scope(['all'])
236 def require_auth_scope(ok_scopes)
237 unless current_api_client_auth_has_scope(ok_scopes)
238 render :json => { errors: ['Forbidden'] }.to_json, status: 403
242 def thread_with_auth_info
243 Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
247 api_client_auth = nil
249 params[:api_token] ||
250 params[:oauth_token] ||
251 request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
253 api_client_auth = ApiClientAuthorization.
254 includes(:api_client, :user).
255 where('api_token=? and (expires_at is null or expires_at > now())', supplied_token).
257 if api_client_auth.andand.user
258 session[:user_id] = api_client_auth.user.id
259 session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
260 session[:api_client_authorization_id] = api_client_auth.id
261 user = api_client_auth.user
262 api_client = api_client_auth.api_client
264 elsif session[:user_id]
265 user = User.find(session[:user_id]) rescue nil
266 api_client = ApiClient.
267 where('uuid=?',session[:api_client_uuid]).
269 if session[:api_client_authorization_id] then
270 api_client_auth = ApiClientAuthorization.
271 find session[:api_client_authorization_id]
274 Thread.current[:api_client_ip_address] = remote_ip
275 Thread.current[:api_client_authorization] = api_client_auth
276 Thread.current[:api_client_uuid] = api_client.andand.uuid
277 Thread.current[:api_client] = api_client
278 Thread.current[:user] = user
280 api_client_auth.last_used_at = Time.now
281 api_client_auth.last_used_by_ip_address = remote_ip
282 api_client_auth.save validate: false
286 Thread.current[:api_client_ip_address] = nil
287 Thread.current[:api_client_authorization] = nil
288 Thread.current[:api_client_uuid] = nil
289 Thread.current[:api_client] = nil
290 Thread.current[:user] = nil
296 controller_name.classify.constantize
299 def resource_name # params[] key used by client
300 controller_name.singularize
307 def find_object_by_uuid
308 if params[:id] and params[:id].match /\D/
309 params[:uuid] = params.delete :id
311 @object = model_class.where('uuid=?', params[:uuid]).first
314 def self.accept_attribute_as_json(attr, force_class=nil)
315 before_filter lambda { accept_attribute_as_json attr, force_class }
317 def accept_attribute_as_json(attr, force_class)
318 if params[resource_name].is_a? Hash
319 if params[resource_name][attr].is_a? String
320 params[resource_name][attr] = Oj.load params[resource_name][attr]
321 if force_class and !params[resource_name][attr].is_a? force_class
322 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
330 :kind => "arvados##{resource_name}List",
333 :next_page_token => "",
335 :items => @objects.as_api_response(nil)
337 render json: @object_list
341 # Caveat: this is highly dependent on the proxy setup. YMMV.
342 if request.headers.has_key?('HTTP_X_REAL_IP') then
343 # We're behind a reverse proxy
344 @remote_ip = request.headers['HTTP_X_REAL_IP']
346 # Hopefully, we are not!
347 @remote_ip = request.env['REMOTE_ADDR']
351 def self._index_requires_parameters
353 where: { type: 'object', required: false },
354 order: { type: 'string', required: false }
358 def client_accepts_plain_text_stream
359 (request.headers['Accept'].split(' ') &
360 ['text/plain', '*/*']).count > 0