##// END OF EJS Templates
Merged r13041 (#16511)....
Jean-Philippe Lang -
r12772:3b91ec2246ed
parent child
Show More
@@ -1,617 +1,618
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 else
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? && 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)
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 end
391 392 redirect_to default
392 393 false
393 394 end
394 395
395 396 # Redirects to the request referer if present, redirects to args or call block otherwise.
396 397 def redirect_to_referer_or(*args, &block)
397 398 redirect_to :back
398 399 rescue ::ActionController::RedirectBackError
399 400 if args.any?
400 401 redirect_to *args
401 402 elsif block_given?
402 403 block.call
403 404 else
404 405 raise "#redirect_to_referer_or takes arguments or a block"
405 406 end
406 407 end
407 408
408 409 def render_403(options={})
409 410 @project = nil
410 411 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
411 412 return false
412 413 end
413 414
414 415 def render_404(options={})
415 416 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
416 417 return false
417 418 end
418 419
419 420 # Renders an error response
420 421 def render_error(arg)
421 422 arg = {:message => arg} unless arg.is_a?(Hash)
422 423
423 424 @message = arg[:message]
424 425 @message = l(@message) if @message.is_a?(Symbol)
425 426 @status = arg[:status] || 500
426 427
427 428 respond_to do |format|
428 429 format.html {
429 430 render :template => 'common/error', :layout => use_layout, :status => @status
430 431 }
431 432 format.any { head @status }
432 433 end
433 434 end
434 435
435 436 # Handler for ActionView::MissingTemplate exception
436 437 def missing_template
437 438 logger.warn "Missing template, responding with 404"
438 439 @project = nil
439 440 render_404
440 441 end
441 442
442 443 # Filter for actions that provide an API response
443 444 # but have no HTML representation for non admin users
444 445 def require_admin_or_api_request
445 446 return true if api_request?
446 447 if User.current.admin?
447 448 true
448 449 elsif User.current.logged?
449 450 render_error(:status => 406)
450 451 else
451 452 deny_access
452 453 end
453 454 end
454 455
455 456 # Picks which layout to use based on the request
456 457 #
457 458 # @return [boolean, string] name of the layout to use or false for no layout
458 459 def use_layout
459 460 request.xhr? ? false : 'base'
460 461 end
461 462
462 463 def render_feed(items, options={})
463 464 @items = items || []
464 465 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
465 466 @items = @items.slice(0, Setting.feeds_limit.to_i)
466 467 @title = options[:title] || Setting.app_title
467 468 render :template => "common/feed", :formats => [:atom], :layout => false,
468 469 :content_type => 'application/atom+xml'
469 470 end
470 471
471 472 def self.accept_rss_auth(*actions)
472 473 if actions.any?
473 474 self.accept_rss_auth_actions = actions
474 475 else
475 476 self.accept_rss_auth_actions || []
476 477 end
477 478 end
478 479
479 480 def accept_rss_auth?(action=action_name)
480 481 self.class.accept_rss_auth.include?(action.to_sym)
481 482 end
482 483
483 484 def self.accept_api_auth(*actions)
484 485 if actions.any?
485 486 self.accept_api_auth_actions = actions
486 487 else
487 488 self.accept_api_auth_actions || []
488 489 end
489 490 end
490 491
491 492 def accept_api_auth?(action=action_name)
492 493 self.class.accept_api_auth.include?(action.to_sym)
493 494 end
494 495
495 496 # Returns the number of objects that should be displayed
496 497 # on the paginated list
497 498 def per_page_option
498 499 per_page = nil
499 500 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
500 501 per_page = params[:per_page].to_s.to_i
501 502 session[:per_page] = per_page
502 503 elsif session[:per_page]
503 504 per_page = session[:per_page]
504 505 else
505 506 per_page = Setting.per_page_options_array.first || 25
506 507 end
507 508 per_page
508 509 end
509 510
510 511 # Returns offset and limit used to retrieve objects
511 512 # for an API response based on offset, limit and page parameters
512 513 def api_offset_and_limit(options=params)
513 514 if options[:offset].present?
514 515 offset = options[:offset].to_i
515 516 if offset < 0
516 517 offset = 0
517 518 end
518 519 end
519 520 limit = options[:limit].to_i
520 521 if limit < 1
521 522 limit = 25
522 523 elsif limit > 100
523 524 limit = 100
524 525 end
525 526 if offset.nil? && options[:page].present?
526 527 offset = (options[:page].to_i - 1) * limit
527 528 offset = 0 if offset < 0
528 529 end
529 530 offset ||= 0
530 531
531 532 [offset, limit]
532 533 end
533 534
534 535 # qvalues http header parser
535 536 # code taken from webrick
536 537 def parse_qvalues(value)
537 538 tmp = []
538 539 if value
539 540 parts = value.split(/,\s*/)
540 541 parts.each {|part|
541 542 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
542 543 val = m[1]
543 544 q = (m[2] or 1).to_f
544 545 tmp.push([val, q])
545 546 end
546 547 }
547 548 tmp = tmp.sort_by{|val, q| -q}
548 549 tmp.collect!{|val, q| val}
549 550 end
550 551 return tmp
551 552 rescue
552 553 nil
553 554 end
554 555
555 556 # Returns a string that can be used as filename value in Content-Disposition header
556 557 def filename_for_content_disposition(name)
557 558 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
558 559 end
559 560
560 561 def api_request?
561 562 %w(xml json).include? params[:format]
562 563 end
563 564
564 565 # Returns the API key present in the request
565 566 def api_key_from_request
566 567 if params[:key].present?
567 568 params[:key].to_s
568 569 elsif request.headers["X-Redmine-API-Key"].present?
569 570 request.headers["X-Redmine-API-Key"].to_s
570 571 end
571 572 end
572 573
573 574 # Returns the API 'switch user' value if present
574 575 def api_switch_user_from_request
575 576 request.headers["X-Redmine-Switch-User"].to_s.presence
576 577 end
577 578
578 579 # Renders a warning flash if obj has unsaved attachments
579 580 def render_attachment_warning_if_needed(obj)
580 581 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
581 582 end
582 583
583 584 # Rescues an invalid query statement. Just in case...
584 585 def query_statement_invalid(exception)
585 586 logger.error "Query::StatementInvalid: #{exception.message}" if logger
586 587 session.delete(:query)
587 588 sort_clear if respond_to?(:sort_clear)
588 589 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
589 590 end
590 591
591 592 # Renders a 200 response for successfull updates or deletions via the API
592 593 def render_api_ok
593 594 render_api_head :ok
594 595 end
595 596
596 597 # Renders a head API response
597 598 def render_api_head(status)
598 599 # #head would return a response body with one space
599 600 render :text => '', :status => status, :layout => nil
600 601 end
601 602
602 603 # Renders API response on validation failure
603 604 def render_validation_errors(objects)
604 605 if objects.is_a?(Array)
605 606 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
606 607 else
607 608 @error_messages = objects.errors.full_messages
608 609 end
609 610 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
610 611 end
611 612
612 613 # Overrides #_include_layout? so that #render with no arguments
613 614 # doesn't use the layout for api requests
614 615 def _include_layout?(*args)
615 616 api_request? ? false : super
616 617 end
617 618 end
General Comments 0
You need to be logged in to leave comments. Login now