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