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