##// END OF EJS Templates
Merged r13041 (#16511)....
Jean-Philippe Lang -
r12773:cf36ba1572bc
parent child
Show More
@@ -1,620 +1,621
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2014 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 include Redmine::Pagination
26 26 include RoutesHelper
27 27 helper :routes
28 28
29 29 class_attribute :accept_api_auth_actions
30 30 class_attribute :accept_rss_auth_actions
31 31 class_attribute :model_object
32 32
33 33 layout 'base'
34 34
35 35 protect_from_forgery
36 36
37 37 def verify_authenticity_token
38 38 unless api_request?
39 39 super
40 40 end
41 41 end
42 42
43 43 def handle_unverified_request
44 44 unless api_request?
45 45 super
46 46 cookies.delete(autologin_cookie_name)
47 self.logged_user = nil
47 48 render_error :status => 422, :message => "Invalid form authenticity token."
48 49 end
49 50 end
50 51
51 52 before_filter :session_expiration, :user_setup, :check_if_login_required, :check_password_change, :set_localization
52 53
53 54 rescue_from ::Unauthorized, :with => :deny_access
54 55 rescue_from ::ActionView::MissingTemplate, :with => :missing_template
55 56
56 57 include Redmine::Search::Controller
57 58 include Redmine::MenuManager::MenuController
58 59 helper Redmine::MenuManager::MenuHelper
59 60
60 61 def session_expiration
61 62 if session[:user_id]
62 63 if session_expired? && !try_to_autologin
63 64 reset_session
64 65 flash[:error] = l(:error_session_expired)
65 66 redirect_to signin_url
66 67 else
67 68 session[:atime] = Time.now.utc.to_i
68 69 end
69 70 end
70 71 end
71 72
72 73 def session_expired?
73 74 if Setting.session_lifetime?
74 75 unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
75 76 return true
76 77 end
77 78 end
78 79 if Setting.session_timeout?
79 80 unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
80 81 return true
81 82 end
82 83 end
83 84 false
84 85 end
85 86
86 87 def start_user_session(user)
87 88 session[:user_id] = user.id
88 89 session[:ctime] = Time.now.utc.to_i
89 90 session[:atime] = Time.now.utc.to_i
90 91 if user.must_change_password?
91 92 session[:pwd] = '1'
92 93 end
93 94 end
94 95
95 96 def user_setup
96 97 # Check the settings cache for each request
97 98 Setting.check_cache
98 99 # Find the current user
99 100 User.current = find_current_user
100 101 logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
101 102 end
102 103
103 104 # Returns the current user or nil if no user is logged in
104 105 # and starts a session if needed
105 106 def find_current_user
106 107 user = nil
107 108 unless api_request?
108 109 if session[:user_id]
109 110 # existing session
110 111 user = (User.active.find(session[:user_id]) rescue nil)
111 112 elsif autologin_user = try_to_autologin
112 113 user = autologin_user
113 114 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
114 115 # RSS key authentication does not start a session
115 116 user = User.find_by_rss_key(params[:key])
116 117 end
117 118 end
118 119 if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
119 120 if (key = api_key_from_request)
120 121 # Use API key
121 122 user = User.find_by_api_key(key)
122 123 elsif request.authorization.to_s =~ /\ABasic /i
123 124 # HTTP Basic, either username/password or API key/random
124 125 authenticate_with_http_basic do |username, password|
125 126 user = User.try_to_login(username, password) || User.find_by_api_key(username)
126 127 end
127 128 if user && user.must_change_password?
128 129 render_error :message => 'You must change your password', :status => 403
129 130 return
130 131 end
131 132 end
132 133 # Switch user if requested by an admin user
133 134 if user && user.admin? && (username = api_switch_user_from_request)
134 135 su = User.find_by_login(username)
135 136 if su && su.active?
136 137 logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
137 138 user = su
138 139 else
139 140 render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
140 141 end
141 142 end
142 143 end
143 144 user
144 145 end
145 146
146 147 def autologin_cookie_name
147 148 Redmine::Configuration['autologin_cookie_name'].presence || 'autologin'
148 149 end
149 150
150 151 def try_to_autologin
151 152 if cookies[autologin_cookie_name] && Setting.autologin?
152 153 # auto-login feature starts a new session
153 154 user = User.try_to_autologin(cookies[autologin_cookie_name])
154 155 if user
155 156 reset_session
156 157 start_user_session(user)
157 158 end
158 159 user
159 160 end
160 161 end
161 162
162 163 # Sets the logged in user
163 164 def logged_user=(user)
164 165 reset_session
165 166 if user && user.is_a?(User)
166 167 User.current = user
167 168 start_user_session(user)
168 169 else
169 170 User.current = User.anonymous
170 171 end
171 172 end
172 173
173 174 # Logs out current user
174 175 def logout_user
175 176 if User.current.logged?
176 177 cookies.delete(autologin_cookie_name)
177 178 Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
178 179 self.logged_user = nil
179 180 end
180 181 end
181 182
182 183 # check if login is globally required to access the application
183 184 def check_if_login_required
184 185 # no check needed if user is already logged in
185 186 return true if User.current.logged?
186 187 require_login if Setting.login_required?
187 188 end
188 189
189 190 def check_password_change
190 191 if session[:pwd]
191 192 if User.current.must_change_password?
192 193 redirect_to my_password_path
193 194 else
194 195 session.delete(:pwd)
195 196 end
196 197 end
197 198 end
198 199
199 200 def set_localization
200 201 lang = nil
201 202 if User.current.logged?
202 203 lang = find_language(User.current.language)
203 204 end
204 205 if lang.nil? && !Setting.force_default_language_for_anonymous? && request.env['HTTP_ACCEPT_LANGUAGE']
205 206 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
206 207 if !accept_lang.blank?
207 208 accept_lang = accept_lang.downcase
208 209 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
209 210 end
210 211 end
211 212 lang ||= Setting.default_language
212 213 set_language_if_valid(lang)
213 214 end
214 215
215 216 def require_login
216 217 if !User.current.logged?
217 218 # Extract only the basic url parameters on non-GET requests
218 219 if request.get?
219 220 url = url_for(params)
220 221 else
221 222 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
222 223 end
223 224 respond_to do |format|
224 225 format.html {
225 226 if request.xhr?
226 227 head :unauthorized
227 228 else
228 229 redirect_to :controller => "account", :action => "login", :back_url => url
229 230 end
230 231 }
231 232 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
232 233 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
233 234 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
234 235 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
235 236 end
236 237 return false
237 238 end
238 239 true
239 240 end
240 241
241 242 def require_admin
242 243 return unless require_login
243 244 if !User.current.admin?
244 245 render_403
245 246 return false
246 247 end
247 248 true
248 249 end
249 250
250 251 def deny_access
251 252 User.current.logged? ? render_403 : require_login
252 253 end
253 254
254 255 # Authorize the user for the requested action
255 256 def authorize(ctrl = params[:controller], action = params[:action], global = false)
256 257 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
257 258 if allowed
258 259 true
259 260 else
260 261 if @project && @project.archived?
261 262 render_403 :message => :notice_not_authorized_archived_project
262 263 else
263 264 deny_access
264 265 end
265 266 end
266 267 end
267 268
268 269 # Authorize the user for the requested action outside a project
269 270 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
270 271 authorize(ctrl, action, global)
271 272 end
272 273
273 274 # Find project of id params[:id]
274 275 def find_project
275 276 @project = Project.find(params[:id])
276 277 rescue ActiveRecord::RecordNotFound
277 278 render_404
278 279 end
279 280
280 281 # Find project of id params[:project_id]
281 282 def find_project_by_project_id
282 283 @project = Project.find(params[:project_id])
283 284 rescue ActiveRecord::RecordNotFound
284 285 render_404
285 286 end
286 287
287 288 # Find a project based on params[:project_id]
288 289 # TODO: some subclasses override this, see about merging their logic
289 290 def find_optional_project
290 291 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
291 292 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
292 293 allowed ? true : deny_access
293 294 rescue ActiveRecord::RecordNotFound
294 295 render_404
295 296 end
296 297
297 298 # Finds and sets @project based on @object.project
298 299 def find_project_from_association
299 300 render_404 unless @object.present?
300 301
301 302 @project = @object.project
302 303 end
303 304
304 305 def find_model_object
305 306 model = self.class.model_object
306 307 if model
307 308 @object = model.find(params[:id])
308 309 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
309 310 end
310 311 rescue ActiveRecord::RecordNotFound
311 312 render_404
312 313 end
313 314
314 315 def self.model_object(model)
315 316 self.model_object = model
316 317 end
317 318
318 319 # Find the issue whose id is the :id parameter
319 320 # Raises a Unauthorized exception if the issue is not visible
320 321 def find_issue
321 322 # Issue.visible.find(...) can not be used to redirect user to the login form
322 323 # if the issue actually exists but requires authentication
323 324 @issue = Issue.find(params[:id])
324 325 raise Unauthorized unless @issue.visible?
325 326 @project = @issue.project
326 327 rescue ActiveRecord::RecordNotFound
327 328 render_404
328 329 end
329 330
330 331 # Find issues with a single :id param or :ids array param
331 332 # Raises a Unauthorized exception if one of the issues is not visible
332 333 def find_issues
333 334 @issues = Issue.where(:id => (params[:id] || params[:ids])).preload(:project, :status, :tracker, :priority, :author, :assigned_to, :relations_to).to_a
334 335 raise ActiveRecord::RecordNotFound if @issues.empty?
335 336 raise Unauthorized unless @issues.all?(&:visible?)
336 337 @projects = @issues.collect(&:project).compact.uniq
337 338 @project = @projects.first if @projects.size == 1
338 339 rescue ActiveRecord::RecordNotFound
339 340 render_404
340 341 end
341 342
342 343 def find_attachments
343 344 if (attachments = params[:attachments]).present?
344 345 att = attachments.values.collect do |attachment|
345 346 Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
346 347 end
347 348 att.compact!
348 349 end
349 350 @attachments = att || []
350 351 end
351 352
352 353 # make sure that the user is a member of the project (or admin) if project is private
353 354 # used as a before_filter for actions that do not require any particular permission on the project
354 355 def check_project_privacy
355 356 if @project && !@project.archived?
356 357 if @project.visible?
357 358 true
358 359 else
359 360 deny_access
360 361 end
361 362 else
362 363 @project = nil
363 364 render_404
364 365 false
365 366 end
366 367 end
367 368
368 369 def back_url
369 370 url = params[:back_url]
370 371 if url.nil? && referer = request.env['HTTP_REFERER']
371 372 url = CGI.unescape(referer.to_s)
372 373 end
373 374 url
374 375 end
375 376
376 377 def redirect_back_or_default(default, options={})
377 378 back_url = params[:back_url].to_s
378 379 if back_url.present?
379 380 begin
380 381 uri = URI.parse(back_url)
381 382 # do not redirect user to another host or to the login or register page
382 383 if ((uri.relative? && back_url.match(%r{\A/(\w.*)?\z})) || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
383 384 redirect_to(back_url)
384 385 return
385 386 end
386 387 rescue URI::InvalidURIError
387 388 logger.warn("Could not redirect to invalid URL #{back_url}")
388 389 # redirect to default
389 390 end
390 391 elsif options[:referer]
391 392 redirect_to_referer_or default
392 393 return
393 394 end
394 395 redirect_to default
395 396 false
396 397 end
397 398
398 399 # Redirects to the request referer if present, redirects to args or call block otherwise.
399 400 def redirect_to_referer_or(*args, &block)
400 401 redirect_to :back
401 402 rescue ::ActionController::RedirectBackError
402 403 if args.any?
403 404 redirect_to *args
404 405 elsif block_given?
405 406 block.call
406 407 else
407 408 raise "#redirect_to_referer_or takes arguments or a block"
408 409 end
409 410 end
410 411
411 412 def render_403(options={})
412 413 @project = nil
413 414 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
414 415 return false
415 416 end
416 417
417 418 def render_404(options={})
418 419 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
419 420 return false
420 421 end
421 422
422 423 # Renders an error response
423 424 def render_error(arg)
424 425 arg = {:message => arg} unless arg.is_a?(Hash)
425 426
426 427 @message = arg[:message]
427 428 @message = l(@message) if @message.is_a?(Symbol)
428 429 @status = arg[:status] || 500
429 430
430 431 respond_to do |format|
431 432 format.html {
432 433 render :template => 'common/error', :layout => use_layout, :status => @status
433 434 }
434 435 format.any { head @status }
435 436 end
436 437 end
437 438
438 439 # Handler for ActionView::MissingTemplate exception
439 440 def missing_template
440 441 logger.warn "Missing template, responding with 404"
441 442 @project = nil
442 443 render_404
443 444 end
444 445
445 446 # Filter for actions that provide an API response
446 447 # but have no HTML representation for non admin users
447 448 def require_admin_or_api_request
448 449 return true if api_request?
449 450 if User.current.admin?
450 451 true
451 452 elsif User.current.logged?
452 453 render_error(:status => 406)
453 454 else
454 455 deny_access
455 456 end
456 457 end
457 458
458 459 # Picks which layout to use based on the request
459 460 #
460 461 # @return [boolean, string] name of the layout to use or false for no layout
461 462 def use_layout
462 463 request.xhr? ? false : 'base'
463 464 end
464 465
465 466 def render_feed(items, options={})
466 467 @items = items || []
467 468 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
468 469 @items = @items.slice(0, Setting.feeds_limit.to_i)
469 470 @title = options[:title] || Setting.app_title
470 471 render :template => "common/feed", :formats => [:atom], :layout => false,
471 472 :content_type => 'application/atom+xml'
472 473 end
473 474
474 475 def self.accept_rss_auth(*actions)
475 476 if actions.any?
476 477 self.accept_rss_auth_actions = actions
477 478 else
478 479 self.accept_rss_auth_actions || []
479 480 end
480 481 end
481 482
482 483 def accept_rss_auth?(action=action_name)
483 484 self.class.accept_rss_auth.include?(action.to_sym)
484 485 end
485 486
486 487 def self.accept_api_auth(*actions)
487 488 if actions.any?
488 489 self.accept_api_auth_actions = actions
489 490 else
490 491 self.accept_api_auth_actions || []
491 492 end
492 493 end
493 494
494 495 def accept_api_auth?(action=action_name)
495 496 self.class.accept_api_auth.include?(action.to_sym)
496 497 end
497 498
498 499 # Returns the number of objects that should be displayed
499 500 # on the paginated list
500 501 def per_page_option
501 502 per_page = nil
502 503 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
503 504 per_page = params[:per_page].to_s.to_i
504 505 session[:per_page] = per_page
505 506 elsif session[:per_page]
506 507 per_page = session[:per_page]
507 508 else
508 509 per_page = Setting.per_page_options_array.first || 25
509 510 end
510 511 per_page
511 512 end
512 513
513 514 # Returns offset and limit used to retrieve objects
514 515 # for an API response based on offset, limit and page parameters
515 516 def api_offset_and_limit(options=params)
516 517 if options[:offset].present?
517 518 offset = options[:offset].to_i
518 519 if offset < 0
519 520 offset = 0
520 521 end
521 522 end
522 523 limit = options[:limit].to_i
523 524 if limit < 1
524 525 limit = 25
525 526 elsif limit > 100
526 527 limit = 100
527 528 end
528 529 if offset.nil? && options[:page].present?
529 530 offset = (options[:page].to_i - 1) * limit
530 531 offset = 0 if offset < 0
531 532 end
532 533 offset ||= 0
533 534
534 535 [offset, limit]
535 536 end
536 537
537 538 # qvalues http header parser
538 539 # code taken from webrick
539 540 def parse_qvalues(value)
540 541 tmp = []
541 542 if value
542 543 parts = value.split(/,\s*/)
543 544 parts.each {|part|
544 545 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
545 546 val = m[1]
546 547 q = (m[2] or 1).to_f
547 548 tmp.push([val, q])
548 549 end
549 550 }
550 551 tmp = tmp.sort_by{|val, q| -q}
551 552 tmp.collect!{|val, q| val}
552 553 end
553 554 return tmp
554 555 rescue
555 556 nil
556 557 end
557 558
558 559 # Returns a string that can be used as filename value in Content-Disposition header
559 560 def filename_for_content_disposition(name)
560 561 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
561 562 end
562 563
563 564 def api_request?
564 565 %w(xml json).include? params[:format]
565 566 end
566 567
567 568 # Returns the API key present in the request
568 569 def api_key_from_request
569 570 if params[:key].present?
570 571 params[:key].to_s
571 572 elsif request.headers["X-Redmine-API-Key"].present?
572 573 request.headers["X-Redmine-API-Key"].to_s
573 574 end
574 575 end
575 576
576 577 # Returns the API 'switch user' value if present
577 578 def api_switch_user_from_request
578 579 request.headers["X-Redmine-Switch-User"].to_s.presence
579 580 end
580 581
581 582 # Renders a warning flash if obj has unsaved attachments
582 583 def render_attachment_warning_if_needed(obj)
583 584 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
584 585 end
585 586
586 587 # Rescues an invalid query statement. Just in case...
587 588 def query_statement_invalid(exception)
588 589 logger.error "Query::StatementInvalid: #{exception.message}" if logger
589 590 session.delete(:query)
590 591 sort_clear if respond_to?(:sort_clear)
591 592 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
592 593 end
593 594
594 595 # Renders a 200 response for successfull updates or deletions via the API
595 596 def render_api_ok
596 597 render_api_head :ok
597 598 end
598 599
599 600 # Renders a head API response
600 601 def render_api_head(status)
601 602 # #head would return a response body with one space
602 603 render :text => '', :status => status, :layout => nil
603 604 end
604 605
605 606 # Renders API response on validation failure
606 607 def render_validation_errors(objects)
607 608 if objects.is_a?(Array)
608 609 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
609 610 else
610 611 @error_messages = objects.errors.full_messages
611 612 end
612 613 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
613 614 end
614 615
615 616 # Overrides #_include_layout? so that #render with no arguments
616 617 # doesn't use the layout for api requests
617 618 def _include_layout?(*args)
618 619 api_request? ? false : super
619 620 end
620 621 end
General Comments 0
You need to be logged in to leave comments. Login now