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