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