##// END OF EJS Templates
Make sure that #api_key_from_request returns a String....
Jean-Philippe Lang -
r9615:be4ad600589c
parent child
Show More
@@ -1,538 +1,538
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2012 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 require 'uri'
19 19 require 'cgi'
20 20
21 21 class Unauthorized < Exception; end
22 22
23 23 class ApplicationController < ActionController::Base
24 24 include Redmine::I18n
25 25
26 26 class_attribute :accept_api_auth_actions
27 27 class_attribute :accept_rss_auth_actions
28 28 class_attribute :model_object
29 29
30 30 layout 'base'
31 31
32 32 protect_from_forgery
33 33 def handle_unverified_request
34 34 super
35 35 cookies.delete(:autologin)
36 36 end
37 37
38 38 before_filter :session_expiration, :user_setup, :check_if_login_required, :set_localization
39 39
40 40 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
41 41 rescue_from ::Unauthorized, :with => :deny_access
42 42
43 43 include Redmine::Search::Controller
44 44 include Redmine::MenuManager::MenuController
45 45 helper Redmine::MenuManager::MenuHelper
46 46
47 47 def session_expiration
48 48 if session[:user_id]
49 49 if session_expired? && !try_to_autologin
50 50 reset_session
51 51 flash[:error] = l(:error_session_expired)
52 52 redirect_to signin_url
53 53 else
54 54 session[:atime] = Time.now.utc.to_i
55 55 end
56 56 end
57 57 end
58 58
59 59 def session_expired?
60 60 if Setting.session_lifetime?
61 61 unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
62 62 return true
63 63 end
64 64 end
65 65 if Setting.session_timeout?
66 66 unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
67 67 return true
68 68 end
69 69 end
70 70 false
71 71 end
72 72
73 73 def start_user_session(user)
74 74 session[:user_id] = user.id
75 75 session[:ctime] = Time.now.utc.to_i
76 76 session[:atime] = Time.now.utc.to_i
77 77 end
78 78
79 79 def user_setup
80 80 # Check the settings cache for each request
81 81 Setting.check_cache
82 82 # Find the current user
83 83 User.current = find_current_user
84 84 end
85 85
86 86 # Returns the current user or nil if no user is logged in
87 87 # and starts a session if needed
88 88 def find_current_user
89 89 if session[:user_id]
90 90 # existing session
91 91 (User.active.find(session[:user_id]) rescue nil)
92 92 elsif user = try_to_autologin
93 93 user
94 94 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
95 95 # RSS key authentication does not start a session
96 96 User.find_by_rss_key(params[:key])
97 97 elsif Setting.rest_api_enabled? && accept_api_auth?
98 98 if (key = api_key_from_request)
99 99 # Use API key
100 100 User.find_by_api_key(key)
101 101 else
102 102 # HTTP Basic, either username/password or API key/random
103 103 authenticate_with_http_basic do |username, password|
104 104 User.try_to_login(username, password) || User.find_by_api_key(username)
105 105 end
106 106 end
107 107 end
108 108 end
109 109
110 110 def try_to_autologin
111 111 if cookies[:autologin] && Setting.autologin?
112 112 # auto-login feature starts a new session
113 113 user = User.try_to_autologin(cookies[:autologin])
114 114 if user
115 115 reset_session
116 116 start_user_session(user)
117 117 end
118 118 user
119 119 end
120 120 end
121 121
122 122 # Sets the logged in user
123 123 def logged_user=(user)
124 124 reset_session
125 125 if user && user.is_a?(User)
126 126 User.current = user
127 127 start_user_session(user)
128 128 else
129 129 User.current = User.anonymous
130 130 end
131 131 end
132 132
133 133 # Logs out current user
134 134 def logout_user
135 135 if User.current.logged?
136 136 cookies.delete :autologin
137 137 Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
138 138 self.logged_user = nil
139 139 end
140 140 end
141 141
142 142 # check if login is globally required to access the application
143 143 def check_if_login_required
144 144 # no check needed if user is already logged in
145 145 return true if User.current.logged?
146 146 require_login if Setting.login_required?
147 147 end
148 148
149 149 def set_localization
150 150 lang = nil
151 151 if User.current.logged?
152 152 lang = find_language(User.current.language)
153 153 end
154 154 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
155 155 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
156 156 if !accept_lang.blank?
157 157 accept_lang = accept_lang.downcase
158 158 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
159 159 end
160 160 end
161 161 lang ||= Setting.default_language
162 162 set_language_if_valid(lang)
163 163 end
164 164
165 165 def require_login
166 166 if !User.current.logged?
167 167 # Extract only the basic url parameters on non-GET requests
168 168 if request.get?
169 169 url = url_for(params)
170 170 else
171 171 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
172 172 end
173 173 respond_to do |format|
174 174 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
175 175 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
176 176 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
177 177 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
178 178 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
179 179 end
180 180 return false
181 181 end
182 182 true
183 183 end
184 184
185 185 def require_admin
186 186 return unless require_login
187 187 if !User.current.admin?
188 188 render_403
189 189 return false
190 190 end
191 191 true
192 192 end
193 193
194 194 def deny_access
195 195 User.current.logged? ? render_403 : require_login
196 196 end
197 197
198 198 # Authorize the user for the requested action
199 199 def authorize(ctrl = params[:controller], action = params[:action], global = false)
200 200 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
201 201 if allowed
202 202 true
203 203 else
204 204 if @project && @project.archived?
205 205 render_403 :message => :notice_not_authorized_archived_project
206 206 else
207 207 deny_access
208 208 end
209 209 end
210 210 end
211 211
212 212 # Authorize the user for the requested action outside a project
213 213 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
214 214 authorize(ctrl, action, global)
215 215 end
216 216
217 217 # Find project of id params[:id]
218 218 def find_project
219 219 @project = Project.find(params[:id])
220 220 rescue ActiveRecord::RecordNotFound
221 221 render_404
222 222 end
223 223
224 224 # Find project of id params[:project_id]
225 225 def find_project_by_project_id
226 226 @project = Project.find(params[:project_id])
227 227 rescue ActiveRecord::RecordNotFound
228 228 render_404
229 229 end
230 230
231 231 # Find a project based on params[:project_id]
232 232 # TODO: some subclasses override this, see about merging their logic
233 233 def find_optional_project
234 234 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
235 235 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
236 236 allowed ? true : deny_access
237 237 rescue ActiveRecord::RecordNotFound
238 238 render_404
239 239 end
240 240
241 241 # Finds and sets @project based on @object.project
242 242 def find_project_from_association
243 243 render_404 unless @object.present?
244 244
245 245 @project = @object.project
246 246 end
247 247
248 248 def find_model_object
249 249 model = self.class.model_object
250 250 if model
251 251 @object = model.find(params[:id])
252 252 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
253 253 end
254 254 rescue ActiveRecord::RecordNotFound
255 255 render_404
256 256 end
257 257
258 258 def self.model_object(model)
259 259 self.model_object = model
260 260 end
261 261
262 262 # Filter for bulk issue operations
263 263 def find_issues
264 264 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
265 265 raise ActiveRecord::RecordNotFound if @issues.empty?
266 266 if @issues.detect {|issue| !issue.visible?}
267 267 deny_access
268 268 return
269 269 end
270 270 @projects = @issues.collect(&:project).compact.uniq
271 271 @project = @projects.first if @projects.size == 1
272 272 rescue ActiveRecord::RecordNotFound
273 273 render_404
274 274 end
275 275
276 276 # make sure that the user is a member of the project (or admin) if project is private
277 277 # used as a before_filter for actions that do not require any particular permission on the project
278 278 def check_project_privacy
279 279 if @project && @project.active?
280 280 if @project.visible?
281 281 true
282 282 else
283 283 deny_access
284 284 end
285 285 else
286 286 @project = nil
287 287 render_404
288 288 false
289 289 end
290 290 end
291 291
292 292 def back_url
293 293 params[:back_url] || request.env['HTTP_REFERER']
294 294 end
295 295
296 296 def redirect_back_or_default(default)
297 297 back_url = CGI.unescape(params[:back_url].to_s)
298 298 if !back_url.blank?
299 299 begin
300 300 uri = URI.parse(back_url)
301 301 # do not redirect user to another host or to the login or register page
302 302 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
303 303 redirect_to(back_url)
304 304 return
305 305 end
306 306 rescue URI::InvalidURIError
307 307 # redirect to default
308 308 end
309 309 end
310 310 redirect_to default
311 311 false
312 312 end
313 313
314 314 # Redirects to the request referer if present, redirects to args or call block otherwise.
315 315 def redirect_to_referer_or(*args, &block)
316 316 redirect_to :back
317 317 rescue ::ActionController::RedirectBackError
318 318 if args.any?
319 319 redirect_to *args
320 320 elsif block_given?
321 321 block.call
322 322 else
323 323 raise "#redirect_to_referer_or takes arguments or a block"
324 324 end
325 325 end
326 326
327 327 def render_403(options={})
328 328 @project = nil
329 329 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
330 330 return false
331 331 end
332 332
333 333 def render_404(options={})
334 334 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
335 335 return false
336 336 end
337 337
338 338 # Renders an error response
339 339 def render_error(arg)
340 340 arg = {:message => arg} unless arg.is_a?(Hash)
341 341
342 342 @message = arg[:message]
343 343 @message = l(@message) if @message.is_a?(Symbol)
344 344 @status = arg[:status] || 500
345 345
346 346 respond_to do |format|
347 347 format.html {
348 348 render :template => 'common/error', :layout => use_layout, :status => @status
349 349 }
350 350 format.atom { head @status }
351 351 format.xml { head @status }
352 352 format.js { head @status }
353 353 format.json { head @status }
354 354 end
355 355 end
356 356
357 357 # Filter for actions that provide an API response
358 358 # but have no HTML representation for non admin users
359 359 def require_admin_or_api_request
360 360 return true if api_request?
361 361 if User.current.admin?
362 362 true
363 363 elsif User.current.logged?
364 364 render_error(:status => 406)
365 365 else
366 366 deny_access
367 367 end
368 368 end
369 369
370 370 # Picks which layout to use based on the request
371 371 #
372 372 # @return [boolean, string] name of the layout to use or false for no layout
373 373 def use_layout
374 374 request.xhr? ? false : 'base'
375 375 end
376 376
377 377 def invalid_authenticity_token
378 378 if api_request?
379 379 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
380 380 end
381 381 render_error "Invalid form authenticity token."
382 382 end
383 383
384 384 def render_feed(items, options={})
385 385 @items = items || []
386 386 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
387 387 @items = @items.slice(0, Setting.feeds_limit.to_i)
388 388 @title = options[:title] || Setting.app_title
389 389 render :template => "common/feed.atom", :layout => false,
390 390 :content_type => 'application/atom+xml'
391 391 end
392 392
393 393 def self.accept_rss_auth(*actions)
394 394 if actions.any?
395 395 self.accept_rss_auth_actions = actions
396 396 else
397 397 self.accept_rss_auth_actions || []
398 398 end
399 399 end
400 400
401 401 def accept_rss_auth?(action=action_name)
402 402 self.class.accept_rss_auth.include?(action.to_sym)
403 403 end
404 404
405 405 def self.accept_api_auth(*actions)
406 406 if actions.any?
407 407 self.accept_api_auth_actions = actions
408 408 else
409 409 self.accept_api_auth_actions || []
410 410 end
411 411 end
412 412
413 413 def accept_api_auth?(action=action_name)
414 414 self.class.accept_api_auth.include?(action.to_sym)
415 415 end
416 416
417 417 # Returns the number of objects that should be displayed
418 418 # on the paginated list
419 419 def per_page_option
420 420 per_page = nil
421 421 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
422 422 per_page = params[:per_page].to_s.to_i
423 423 session[:per_page] = per_page
424 424 elsif session[:per_page]
425 425 per_page = session[:per_page]
426 426 else
427 427 per_page = Setting.per_page_options_array.first || 25
428 428 end
429 429 per_page
430 430 end
431 431
432 432 # Returns offset and limit used to retrieve objects
433 433 # for an API response based on offset, limit and page parameters
434 434 def api_offset_and_limit(options=params)
435 435 if options[:offset].present?
436 436 offset = options[:offset].to_i
437 437 if offset < 0
438 438 offset = 0
439 439 end
440 440 end
441 441 limit = options[:limit].to_i
442 442 if limit < 1
443 443 limit = 25
444 444 elsif limit > 100
445 445 limit = 100
446 446 end
447 447 if offset.nil? && options[:page].present?
448 448 offset = (options[:page].to_i - 1) * limit
449 449 offset = 0 if offset < 0
450 450 end
451 451 offset ||= 0
452 452
453 453 [offset, limit]
454 454 end
455 455
456 456 # qvalues http header parser
457 457 # code taken from webrick
458 458 def parse_qvalues(value)
459 459 tmp = []
460 460 if value
461 461 parts = value.split(/,\s*/)
462 462 parts.each {|part|
463 463 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
464 464 val = m[1]
465 465 q = (m[2] or 1).to_f
466 466 tmp.push([val, q])
467 467 end
468 468 }
469 469 tmp = tmp.sort_by{|val, q| -q}
470 470 tmp.collect!{|val, q| val}
471 471 end
472 472 return tmp
473 473 rescue
474 474 nil
475 475 end
476 476
477 477 # Returns a string that can be used as filename value in Content-Disposition header
478 478 def filename_for_content_disposition(name)
479 479 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
480 480 end
481 481
482 482 def api_request?
483 483 %w(xml json).include? params[:format]
484 484 end
485 485
486 486 # Returns the API key present in the request
487 487 def api_key_from_request
488 488 if params[:key].present?
489 params[:key]
489 params[:key].to_s
490 490 elsif request.headers["X-Redmine-API-Key"].present?
491 request.headers["X-Redmine-API-Key"]
491 request.headers["X-Redmine-API-Key"].to_s
492 492 end
493 493 end
494 494
495 495 # Renders a warning flash if obj has unsaved attachments
496 496 def render_attachment_warning_if_needed(obj)
497 497 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
498 498 end
499 499
500 500 # Sets the `flash` notice or error based the number of issues that did not save
501 501 #
502 502 # @param [Array, Issue] issues all of the saved and unsaved Issues
503 503 # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
504 504 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
505 505 if unsaved_issue_ids.empty?
506 506 flash[:notice] = l(:notice_successful_update) unless issues.empty?
507 507 else
508 508 flash[:error] = l(:notice_failed_to_save_issues,
509 509 :count => unsaved_issue_ids.size,
510 510 :total => issues.size,
511 511 :ids => '#' + unsaved_issue_ids.join(', #'))
512 512 end
513 513 end
514 514
515 515 # Rescues an invalid query statement. Just in case...
516 516 def query_statement_invalid(exception)
517 517 logger.error "Query::StatementInvalid: #{exception.message}" if logger
518 518 session.delete(:query)
519 519 sort_clear if respond_to?(:sort_clear)
520 520 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
521 521 end
522 522
523 523 # Renders API response on validation failure
524 524 def render_validation_errors(objects)
525 525 if objects.is_a?(Array)
526 526 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
527 527 else
528 528 @error_messages = objects.errors.full_messages
529 529 end
530 530 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
531 531 end
532 532
533 533 # Overrides #_include_layout? so that #render with no arguments
534 534 # doesn't use the layout for api requests
535 535 def _include_layout?(*args)
536 536 api_request? ? false : super
537 537 end
538 538 end
General Comments 0
You need to be logged in to leave comments. Login now