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