##// END OF EJS Templates
Don't use render :text => ""....
Jean-Philippe Lang -
r15349:8b107b605825
parent child
Show More
@@ -1,678 +1,677
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2016 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 include Redmine::Pagination
26 26 include Redmine::Hook::Helper
27 27 include RoutesHelper
28 28 helper :routes
29 29
30 30 class_attribute :accept_api_auth_actions
31 31 class_attribute :accept_rss_auth_actions
32 32 class_attribute :model_object
33 33
34 34 layout 'base'
35 35
36 36 protect_from_forgery
37 37
38 38 def verify_authenticity_token
39 39 unless api_request?
40 40 super
41 41 end
42 42 end
43 43
44 44 def handle_unverified_request
45 45 unless api_request?
46 46 super
47 47 cookies.delete(autologin_cookie_name)
48 48 self.logged_user = nil
49 49 set_localization
50 50 render_error :status => 422, :message => "Invalid form authenticity token."
51 51 end
52 52 end
53 53
54 54 before_action :session_expiration, :user_setup, :check_if_login_required, :check_password_change, :set_localization
55 55
56 56 rescue_from ::Unauthorized, :with => :deny_access
57 57 rescue_from ::ActionView::MissingTemplate, :with => :missing_template
58 58
59 59 include Redmine::Search::Controller
60 60 include Redmine::MenuManager::MenuController
61 61 helper Redmine::MenuManager::MenuHelper
62 62
63 63 include Redmine::SudoMode::Controller
64 64
65 65 def session_expiration
66 66 if session[:user_id] && Rails.application.config.redmine_verify_sessions != false
67 67 if session_expired? && !try_to_autologin
68 68 set_localization(User.active.find_by_id(session[:user_id]))
69 69 self.logged_user = nil
70 70 flash[:error] = l(:error_session_expired)
71 71 require_login
72 72 end
73 73 end
74 74 end
75 75
76 76 def session_expired?
77 77 ! User.verify_session_token(session[:user_id], session[:tk])
78 78 end
79 79
80 80 def start_user_session(user)
81 81 session[:user_id] = user.id
82 82 session[:tk] = user.generate_session_token
83 83 if user.must_change_password?
84 84 session[:pwd] = '1'
85 85 end
86 86 end
87 87
88 88 def user_setup
89 89 # Check the settings cache for each request
90 90 Setting.check_cache
91 91 # Find the current user
92 92 User.current = find_current_user
93 93 logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
94 94 end
95 95
96 96 # Returns the current user or nil if no user is logged in
97 97 # and starts a session if needed
98 98 def find_current_user
99 99 user = nil
100 100 unless api_request?
101 101 if session[:user_id]
102 102 # existing session
103 103 user = (User.active.find(session[:user_id]) rescue nil)
104 104 elsif autologin_user = try_to_autologin
105 105 user = autologin_user
106 106 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
107 107 # RSS key authentication does not start a session
108 108 user = User.find_by_rss_key(params[:key])
109 109 end
110 110 end
111 111 if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
112 112 if (key = api_key_from_request)
113 113 # Use API key
114 114 user = User.find_by_api_key(key)
115 115 elsif request.authorization.to_s =~ /\ABasic /i
116 116 # HTTP Basic, either username/password or API key/random
117 117 authenticate_with_http_basic do |username, password|
118 118 user = User.try_to_login(username, password) || User.find_by_api_key(username)
119 119 end
120 120 if user && user.must_change_password?
121 121 render_error :message => 'You must change your password', :status => 403
122 122 return
123 123 end
124 124 end
125 125 # Switch user if requested by an admin user
126 126 if user && user.admin? && (username = api_switch_user_from_request)
127 127 su = User.find_by_login(username)
128 128 if su && su.active?
129 129 logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
130 130 user = su
131 131 else
132 132 render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
133 133 end
134 134 end
135 135 end
136 136 # store current ip address in user object ephemerally
137 137 user.remote_ip = request.remote_ip if user
138 138 user
139 139 end
140 140
141 141 def autologin_cookie_name
142 142 Redmine::Configuration['autologin_cookie_name'].presence || 'autologin'
143 143 end
144 144
145 145 def try_to_autologin
146 146 if cookies[autologin_cookie_name] && Setting.autologin?
147 147 # auto-login feature starts a new session
148 148 user = User.try_to_autologin(cookies[autologin_cookie_name])
149 149 if user
150 150 reset_session
151 151 start_user_session(user)
152 152 end
153 153 user
154 154 end
155 155 end
156 156
157 157 # Sets the logged in user
158 158 def logged_user=(user)
159 159 reset_session
160 160 if user && user.is_a?(User)
161 161 User.current = user
162 162 start_user_session(user)
163 163 else
164 164 User.current = User.anonymous
165 165 end
166 166 end
167 167
168 168 # Logs out current user
169 169 def logout_user
170 170 if User.current.logged?
171 171 cookies.delete(autologin_cookie_name)
172 172 Token.where(["user_id = ? AND action = ?", User.current.id, 'autologin']).delete_all
173 173 Token.where(["user_id = ? AND action = ? AND value = ?", User.current.id, 'session', session[:tk]]).delete_all
174 174 self.logged_user = nil
175 175 end
176 176 end
177 177
178 178 # check if login is globally required to access the application
179 179 def check_if_login_required
180 180 # no check needed if user is already logged in
181 181 return true if User.current.logged?
182 182 require_login if Setting.login_required?
183 183 end
184 184
185 185 def check_password_change
186 186 if session[:pwd]
187 187 if User.current.must_change_password?
188 188 flash[:error] = l(:error_password_expired)
189 189 redirect_to my_password_path
190 190 else
191 191 session.delete(:pwd)
192 192 end
193 193 end
194 194 end
195 195
196 196 def set_localization(user=User.current)
197 197 lang = nil
198 198 if user && user.logged?
199 199 lang = find_language(user.language)
200 200 end
201 201 if lang.nil? && !Setting.force_default_language_for_anonymous? && request.env['HTTP_ACCEPT_LANGUAGE']
202 202 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
203 203 if !accept_lang.blank?
204 204 accept_lang = accept_lang.downcase
205 205 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
206 206 end
207 207 end
208 208 lang ||= Setting.default_language
209 209 set_language_if_valid(lang)
210 210 end
211 211
212 212 def require_login
213 213 if !User.current.logged?
214 214 # Extract only the basic url parameters on non-GET requests
215 215 if request.get?
216 216 url = request.original_url
217 217 else
218 218 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
219 219 end
220 220 respond_to do |format|
221 221 format.html {
222 222 if request.xhr?
223 223 head :unauthorized
224 224 else
225 225 redirect_to signin_path(:back_url => url)
226 226 end
227 227 }
228 228 format.any(:atom, :pdf, :csv) {
229 229 redirect_to signin_path(:back_url => url)
230 230 }
231 231 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
232 232 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
233 233 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
234 234 format.any { head :unauthorized }
235 235 end
236 236 return false
237 237 end
238 238 true
239 239 end
240 240
241 241 def require_admin
242 242 return unless require_login
243 243 if !User.current.admin?
244 244 render_403
245 245 return false
246 246 end
247 247 true
248 248 end
249 249
250 250 def deny_access
251 251 User.current.logged? ? render_403 : require_login
252 252 end
253 253
254 254 # Authorize the user for the requested action
255 255 def authorize(ctrl = params[:controller], action = params[:action], global = false)
256 256 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
257 257 if allowed
258 258 true
259 259 else
260 260 if @project && @project.archived?
261 261 render_403 :message => :notice_not_authorized_archived_project
262 262 else
263 263 deny_access
264 264 end
265 265 end
266 266 end
267 267
268 268 # Authorize the user for the requested action outside a project
269 269 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
270 270 authorize(ctrl, action, global)
271 271 end
272 272
273 273 # Find project of id params[:id]
274 274 def find_project
275 275 @project = Project.find(params[:id])
276 276 rescue ActiveRecord::RecordNotFound
277 277 render_404
278 278 end
279 279
280 280 # Find project of id params[:project_id]
281 281 def find_project_by_project_id
282 282 @project = Project.find(params[:project_id])
283 283 rescue ActiveRecord::RecordNotFound
284 284 render_404
285 285 end
286 286
287 287 # Find a project based on params[:project_id]
288 288 # TODO: some subclasses override this, see about merging their logic
289 289 def find_optional_project
290 290 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
291 291 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
292 292 allowed ? true : deny_access
293 293 rescue ActiveRecord::RecordNotFound
294 294 render_404
295 295 end
296 296
297 297 # Finds and sets @project based on @object.project
298 298 def find_project_from_association
299 299 render_404 unless @object.present?
300 300
301 301 @project = @object.project
302 302 end
303 303
304 304 def find_model_object
305 305 model = self.class.model_object
306 306 if model
307 307 @object = model.find(params[:id])
308 308 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
309 309 end
310 310 rescue ActiveRecord::RecordNotFound
311 311 render_404
312 312 end
313 313
314 314 def self.model_object(model)
315 315 self.model_object = model
316 316 end
317 317
318 318 # Find the issue whose id is the :id parameter
319 319 # Raises a Unauthorized exception if the issue is not visible
320 320 def find_issue
321 321 # Issue.visible.find(...) can not be used to redirect user to the login form
322 322 # if the issue actually exists but requires authentication
323 323 @issue = Issue.find(params[:id])
324 324 raise Unauthorized unless @issue.visible?
325 325 @project = @issue.project
326 326 rescue ActiveRecord::RecordNotFound
327 327 render_404
328 328 end
329 329
330 330 # Find issues with a single :id param or :ids array param
331 331 # Raises a Unauthorized exception if one of the issues is not visible
332 332 def find_issues
333 333 @issues = Issue.
334 334 where(:id => (params[:id] || params[:ids])).
335 335 preload(:project, :status, :tracker, :priority, :author, :assigned_to, :relations_to, {:custom_values => :custom_field}).
336 336 to_a
337 337 raise ActiveRecord::RecordNotFound if @issues.empty?
338 338 raise Unauthorized unless @issues.all?(&:visible?)
339 339 @projects = @issues.collect(&:project).compact.uniq
340 340 @project = @projects.first if @projects.size == 1
341 341 rescue ActiveRecord::RecordNotFound
342 342 render_404
343 343 end
344 344
345 345 def find_attachments
346 346 if (attachments = params[:attachments]).present?
347 347 att = attachments.values.collect do |attachment|
348 348 Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
349 349 end
350 350 att.compact!
351 351 end
352 352 @attachments = att || []
353 353 end
354 354
355 355 def parse_params_for_bulk_update(params)
356 356 attributes = (params || {}).reject {|k,v| v.blank?}
357 357 attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
358 358 if custom = attributes[:custom_field_values]
359 359 custom.reject! {|k,v| v.blank?}
360 360 custom.keys.each do |k|
361 361 if custom[k].is_a?(Array)
362 362 custom[k] << '' if custom[k].delete('__none__')
363 363 else
364 364 custom[k] = '' if custom[k] == '__none__'
365 365 end
366 366 end
367 367 end
368 368 attributes
369 369 end
370 370
371 371 # make sure that the user is a member of the project (or admin) if project is private
372 372 # used as a before_action for actions that do not require any particular permission on the project
373 373 def check_project_privacy
374 374 if @project && !@project.archived?
375 375 if @project.visible?
376 376 true
377 377 else
378 378 deny_access
379 379 end
380 380 else
381 381 @project = nil
382 382 render_404
383 383 false
384 384 end
385 385 end
386 386
387 387 def back_url
388 388 url = params[:back_url]
389 389 if url.nil? && referer = request.env['HTTP_REFERER']
390 390 url = CGI.unescape(referer.to_s)
391 391 end
392 392 url
393 393 end
394 394
395 395 def redirect_back_or_default(default, options={})
396 396 back_url = params[:back_url].to_s
397 397 if back_url.present? && valid_url = validate_back_url(back_url)
398 398 redirect_to(valid_url)
399 399 return
400 400 elsif options[:referer]
401 401 redirect_to_referer_or default
402 402 return
403 403 end
404 404 redirect_to default
405 405 false
406 406 end
407 407
408 408 # Returns a validated URL string if back_url is a valid url for redirection,
409 409 # otherwise false
410 410 def validate_back_url(back_url)
411 411 if CGI.unescape(back_url).include?('..')
412 412 return false
413 413 end
414 414
415 415 begin
416 416 uri = URI.parse(back_url)
417 417 rescue URI::InvalidURIError
418 418 return false
419 419 end
420 420
421 421 [:scheme, :host, :port].each do |component|
422 422 if uri.send(component).present? && uri.send(component) != request.send(component)
423 423 return false
424 424 end
425 425 uri.send(:"#{component}=", nil)
426 426 end
427 427 # Always ignore basic user:password in the URL
428 428 uri.userinfo = nil
429 429
430 430 path = uri.to_s
431 431 # Ensure that the remaining URL starts with a slash, followed by a
432 432 # non-slash character or the end
433 433 if path !~ %r{\A/([^/]|\z)}
434 434 return false
435 435 end
436 436
437 437 if path.match(%r{/(login|account/register)})
438 438 return false
439 439 end
440 440
441 441 if relative_url_root.present? && !path.starts_with?(relative_url_root)
442 442 return false
443 443 end
444 444
445 445 return path
446 446 end
447 447 private :validate_back_url
448 448
449 449 def valid_back_url?(back_url)
450 450 !!validate_back_url(back_url)
451 451 end
452 452 private :valid_back_url?
453 453
454 454 # Redirects to the request referer if present, redirects to args or call block otherwise.
455 455 def redirect_to_referer_or(*args, &block)
456 456 redirect_to :back
457 457 rescue ::ActionController::RedirectBackError
458 458 if args.any?
459 459 redirect_to *args
460 460 elsif block_given?
461 461 block.call
462 462 else
463 463 raise "#redirect_to_referer_or takes arguments or a block"
464 464 end
465 465 end
466 466
467 467 def render_403(options={})
468 468 @project = nil
469 469 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
470 470 return false
471 471 end
472 472
473 473 def render_404(options={})
474 474 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
475 475 return false
476 476 end
477 477
478 478 # Renders an error response
479 479 def render_error(arg)
480 480 arg = {:message => arg} unless arg.is_a?(Hash)
481 481
482 482 @message = arg[:message]
483 483 @message = l(@message) if @message.is_a?(Symbol)
484 484 @status = arg[:status] || 500
485 485
486 486 respond_to do |format|
487 487 format.html {
488 488 render :template => 'common/error', :layout => use_layout, :status => @status
489 489 }
490 490 format.any { head @status }
491 491 end
492 492 end
493 493
494 494 # Handler for ActionView::MissingTemplate exception
495 495 def missing_template
496 496 logger.warn "Missing template, responding with 404"
497 497 @project = nil
498 498 render_404
499 499 end
500 500
501 501 # Filter for actions that provide an API response
502 502 # but have no HTML representation for non admin users
503 503 def require_admin_or_api_request
504 504 return true if api_request?
505 505 if User.current.admin?
506 506 true
507 507 elsif User.current.logged?
508 508 render_error(:status => 406)
509 509 else
510 510 deny_access
511 511 end
512 512 end
513 513
514 514 # Picks which layout to use based on the request
515 515 #
516 516 # @return [boolean, string] name of the layout to use or false for no layout
517 517 def use_layout
518 518 request.xhr? ? false : 'base'
519 519 end
520 520
521 521 def render_feed(items, options={})
522 522 @items = (items || []).to_a
523 523 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
524 524 @items = @items.slice(0, Setting.feeds_limit.to_i)
525 525 @title = options[:title] || Setting.app_title
526 526 render :template => "common/feed", :formats => [:atom], :layout => false,
527 527 :content_type => 'application/atom+xml'
528 528 end
529 529
530 530 def self.accept_rss_auth(*actions)
531 531 if actions.any?
532 532 self.accept_rss_auth_actions = actions
533 533 else
534 534 self.accept_rss_auth_actions || []
535 535 end
536 536 end
537 537
538 538 def accept_rss_auth?(action=action_name)
539 539 self.class.accept_rss_auth.include?(action.to_sym)
540 540 end
541 541
542 542 def self.accept_api_auth(*actions)
543 543 if actions.any?
544 544 self.accept_api_auth_actions = actions
545 545 else
546 546 self.accept_api_auth_actions || []
547 547 end
548 548 end
549 549
550 550 def accept_api_auth?(action=action_name)
551 551 self.class.accept_api_auth.include?(action.to_sym)
552 552 end
553 553
554 554 # Returns the number of objects that should be displayed
555 555 # on the paginated list
556 556 def per_page_option
557 557 per_page = nil
558 558 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
559 559 per_page = params[:per_page].to_s.to_i
560 560 session[:per_page] = per_page
561 561 elsif session[:per_page]
562 562 per_page = session[:per_page]
563 563 else
564 564 per_page = Setting.per_page_options_array.first || 25
565 565 end
566 566 per_page
567 567 end
568 568
569 569 # Returns offset and limit used to retrieve objects
570 570 # for an API response based on offset, limit and page parameters
571 571 def api_offset_and_limit(options=params)
572 572 if options[:offset].present?
573 573 offset = options[:offset].to_i
574 574 if offset < 0
575 575 offset = 0
576 576 end
577 577 end
578 578 limit = options[:limit].to_i
579 579 if limit < 1
580 580 limit = 25
581 581 elsif limit > 100
582 582 limit = 100
583 583 end
584 584 if offset.nil? && options[:page].present?
585 585 offset = (options[:page].to_i - 1) * limit
586 586 offset = 0 if offset < 0
587 587 end
588 588 offset ||= 0
589 589
590 590 [offset, limit]
591 591 end
592 592
593 593 # qvalues http header parser
594 594 # code taken from webrick
595 595 def parse_qvalues(value)
596 596 tmp = []
597 597 if value
598 598 parts = value.split(/,\s*/)
599 599 parts.each {|part|
600 600 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
601 601 val = m[1]
602 602 q = (m[2] or 1).to_f
603 603 tmp.push([val, q])
604 604 end
605 605 }
606 606 tmp = tmp.sort_by{|val, q| -q}
607 607 tmp.collect!{|val, q| val}
608 608 end
609 609 return tmp
610 610 rescue
611 611 nil
612 612 end
613 613
614 614 # Returns a string that can be used as filename value in Content-Disposition header
615 615 def filename_for_content_disposition(name)
616 616 request.env['HTTP_USER_AGENT'] =~ %r{(MSIE|Trident|Edge)} ? ERB::Util.url_encode(name) : name
617 617 end
618 618
619 619 def api_request?
620 620 %w(xml json).include? params[:format]
621 621 end
622 622
623 623 # Returns the API key present in the request
624 624 def api_key_from_request
625 625 if params[:key].present?
626 626 params[:key].to_s
627 627 elsif request.headers["X-Redmine-API-Key"].present?
628 628 request.headers["X-Redmine-API-Key"].to_s
629 629 end
630 630 end
631 631
632 632 # Returns the API 'switch user' value if present
633 633 def api_switch_user_from_request
634 634 request.headers["X-Redmine-Switch-User"].to_s.presence
635 635 end
636 636
637 637 # Renders a warning flash if obj has unsaved attachments
638 638 def render_attachment_warning_if_needed(obj)
639 639 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
640 640 end
641 641
642 642 # Rescues an invalid query statement. Just in case...
643 643 def query_statement_invalid(exception)
644 644 logger.error "Query::StatementInvalid: #{exception.message}" if logger
645 645 session.delete(:query)
646 646 sort_clear if respond_to?(:sort_clear)
647 647 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
648 648 end
649 649
650 650 # Renders a 200 response for successfull updates or deletions via the API
651 651 def render_api_ok
652 652 render_api_head :ok
653 653 end
654 654
655 655 # Renders a head API response
656 656 def render_api_head(status)
657 # #head would return a response body with one space
658 render :text => '', :status => status, :layout => nil
657 head :status => status
659 658 end
660 659
661 660 # Renders API response on validation failure
662 661 # for an object or an array of objects
663 662 def render_validation_errors(objects)
664 663 messages = Array.wrap(objects).map {|object| object.errors.full_messages}.flatten
665 664 render_api_errors(messages)
666 665 end
667 666
668 667 def render_api_errors(*messages)
669 668 @error_messages = messages.flatten
670 669 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
671 670 end
672 671
673 672 # Overrides #_include_layout? so that #render with no arguments
674 673 # doesn't use the layout for api requests
675 674 def _include_layout?(*args)
676 675 api_request? ? false : super
677 676 end
678 677 end
@@ -1,44 +1,44
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2016 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 class MailHandlerController < ActionController::Base
19 19 before_action :check_credential
20 20
21 21 # Displays the email submission form
22 22 def new
23 23 end
24 24
25 25 # Submits an incoming email to MailHandler
26 26 def index
27 27 options = params.dup
28 28 email = options.delete(:email)
29 29 if MailHandler.receive(email, options)
30 30 head :created
31 31 else
32 32 head :unprocessable_entity
33 33 end
34 34 end
35 35
36 36 private
37 37
38 38 def check_credential
39 39 User.current = nil
40 40 unless Setting.mail_handler_api_enabled? && params[:key].to_s == Setting.mail_handler_api_key
41 render :text => 'Access denied. Incoming emails WS is disabled or key is invalid.', :status => 403
41 render :plain => 'Access denied. Incoming emails WS is disabled or key is invalid.', :status => 403
42 42 end
43 43 end
44 44 end
@@ -1,81 +1,81
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2016 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 class SysController < ActionController::Base
19 19 before_action :check_enabled
20 20
21 21 def projects
22 22 p = Project.active.has_module(:repository).
23 23 order("#{Project.table_name}.identifier").preload(:repository).to_a
24 24 # extra_info attribute from repository breaks activeresource client
25 25 render :xml => p.to_xml(
26 26 :only => [:id, :identifier, :name, :is_public, :status],
27 27 :include => {:repository => {:only => [:id, :url]}}
28 28 )
29 29 end
30 30
31 31 def create_project_repository
32 32 project = Project.find(params[:id])
33 33 if project.repository
34 34 head 409
35 35 else
36 36 logger.info "Repository for #{project.name} was reported to be created by #{request.remote_ip}."
37 37 repository = Repository.factory(params[:vendor], params[:repository])
38 38 repository.project = project
39 39 if repository.save
40 40 render :xml => {repository.class.name.underscore.gsub('/', '-') => {:id => repository.id, :url => repository.url}}, :status => 201
41 41 else
42 42 head 422
43 43 end
44 44 end
45 45 end
46 46
47 47 def fetch_changesets
48 48 projects = []
49 49 scope = Project.active.has_module(:repository)
50 50 if params[:id]
51 51 project = nil
52 52 if params[:id].to_s =~ /^\d*$/
53 53 project = scope.find(params[:id])
54 54 else
55 55 project = scope.find_by_identifier(params[:id])
56 56 end
57 57 raise ActiveRecord::RecordNotFound unless project
58 58 projects << project
59 59 else
60 60 projects = scope.to_a
61 61 end
62 62 projects.each do |project|
63 63 project.repositories.each do |repository|
64 64 repository.fetch_changesets
65 65 end
66 66 end
67 67 head 200
68 68 rescue ActiveRecord::RecordNotFound
69 69 head 404
70 70 end
71 71
72 72 protected
73 73
74 74 def check_enabled
75 75 User.current = nil
76 76 unless Setting.sys_api_enabled? && params[:key].to_s == Setting.sys_api_key
77 render :text => 'Access denied. Repository management WS is disabled or key is invalid.', :status => 403
77 render :plain => 'Access denied. Repository management WS is disabled or key is invalid.', :status => 403
78 78 return false
79 79 end
80 80 end
81 81 end
@@ -1,149 +1,152
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2016 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 class WatchersController < ApplicationController
19 19 before_action :require_login, :find_watchables, :only => [:watch, :unwatch]
20 20
21 21 def watch
22 22 set_watcher(@watchables, User.current, true)
23 23 end
24 24
25 25 def unwatch
26 26 set_watcher(@watchables, User.current, false)
27 27 end
28 28
29 29 before_action :find_project, :authorize, :only => [:new, :create, :append, :destroy, :autocomplete_for_user]
30 30 accept_api_auth :create, :destroy
31 31
32 32 def new
33 33 @users = users_for_new_watcher
34 34 end
35 35
36 36 def create
37 37 user_ids = []
38 38 if params[:watcher]
39 39 user_ids << (params[:watcher][:user_ids] || params[:watcher][:user_id])
40 40 else
41 41 user_ids << params[:user_id]
42 42 end
43 43 users = User.active.visible.where(:id => user_ids.flatten.compact.uniq)
44 44 users.each do |user|
45 45 @watchables.each do |watchable|
46 46 Watcher.create(:watchable => watchable, :user => user)
47 47 end
48 48 end
49 49 respond_to do |format|
50 format.html { redirect_to_referer_or {render :text => 'Watcher added.', :layout => true}}
50 format.html { redirect_to_referer_or {render :html => 'Watcher added.', :status => 200, :layout => true}}
51 51 format.js { @users = users_for_new_watcher }
52 52 format.api { render_api_ok }
53 53 end
54 54 end
55 55
56 56 def append
57 57 if params[:watcher]
58 58 user_ids = params[:watcher][:user_ids] || [params[:watcher][:user_id]]
59 59 @users = User.active.visible.where(:id => user_ids).to_a
60 60 end
61 61 if @users.blank?
62 62 head 200
63 63 end
64 64 end
65 65
66 66 def destroy
67 67 user = User.find(params[:user_id])
68 68 @watchables.each do |watchable|
69 69 watchable.set_watcher(user, false)
70 70 end
71 71 respond_to do |format|
72 format.html { redirect_to :back }
72 format.html { redirect_to_referer_or {render :html => 'Watcher removed.', :status => 200, :layout => true} }
73 73 format.js
74 74 format.api { render_api_ok }
75 75 end
76 76 rescue ActiveRecord::RecordNotFound
77 77 render_404
78 78 end
79 79
80 80 def autocomplete_for_user
81 81 @users = users_for_new_watcher
82 82 render :layout => false
83 83 end
84 84
85 85 private
86 86
87 87 def find_project
88 88 if params[:object_type] && params[:object_id]
89 89 @watchables = find_objets_from_params
90 90 @projects = @watchables.map(&:project).uniq
91 91 if @projects.size == 1
92 92 @project = @projects.first
93 93 end
94 94 elsif params[:project_id]
95 95 @project = Project.visible.find_by_param(params[:project_id])
96 96 end
97 97 end
98 98
99 99 def find_watchables
100 100 @watchables = find_objets_from_params
101 101 unless @watchables.present?
102 102 render_404
103 103 end
104 104 end
105 105
106 106 def set_watcher(watchables, user, watching)
107 107 watchables.each do |watchable|
108 108 watchable.set_watcher(user, watching)
109 109 end
110 110 respond_to do |format|
111 format.html { redirect_to_referer_or {render :text => (watching ? 'Watcher added.' : 'Watcher removed.'), :layout => true}}
111 format.html {
112 text = watching ? 'Watcher added.' : 'Watcher removed.'
113 redirect_to_referer_or {render :html => text, :status => 200, :layout => true}
114 }
112 115 format.js { render :partial => 'set_watcher', :locals => {:user => user, :watched => watchables} }
113 116 end
114 117 end
115 118
116 119 def users_for_new_watcher
117 120 scope = nil
118 121 if params[:q].blank? && @project.present?
119 122 scope = @project.users
120 123 else
121 124 scope = User.all.limit(100)
122 125 end
123 126 users = scope.active.visible.sorted.like(params[:q]).to_a
124 127 if @watchables && @watchables.size == 1
125 128 users -= @watchables.first.watcher_users
126 129 end
127 130 users
128 131 end
129 132
130 133 def find_objets_from_params
131 134 klass = Object.const_get(params[:object_type].camelcase) rescue nil
132 135 return unless klass && klass.respond_to?('watched_by')
133 136
134 137 scope = klass.where(:id => Array.wrap(params[:object_id]))
135 138 if klass.reflect_on_association(:project)
136 139 scope = scope.preload(:project => :enabled_modules)
137 140 end
138 141 objects = scope.to_a
139 142
140 143 raise Unauthorized if objects.any? do |w|
141 144 if w.respond_to?(:visible?)
142 145 !w.visible?
143 146 elsif w.respond_to?(:project) && w.project
144 147 !w.project.visible?
145 148 end
146 149 end
147 150 objects
148 151 end
149 152 end
@@ -1,96 +1,98
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2016 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 File.expand_path('../../test_helper', __FILE__)
19 19
20 20 class MailHandlerControllerTest < Redmine::ControllerTest
21 21 fixtures :users, :email_addresses, :projects, :enabled_modules, :roles, :members, :member_roles, :issues, :issue_statuses,
22 22 :trackers, :projects_trackers, :enumerations
23 23
24 24 FIXTURES_PATH = File.dirname(__FILE__) + '/../fixtures/mail_handler'
25 25
26 26 def setup
27 27 User.current = nil
28 28 end
29 29
30 30 def test_should_create_issue
31 31 # Enable API and set a key
32 32 Setting.mail_handler_api_enabled = 1
33 33 Setting.mail_handler_api_key = 'secret'
34 34
35 35 assert_difference 'Issue.count' do
36 36 post :index, :key => 'secret', :email => IO.read(File.join(FIXTURES_PATH, 'ticket_on_given_project.eml'))
37 37 end
38 38 assert_response 201
39 39 end
40 40
41 41 def test_should_create_issue_with_options
42 42 # Enable API and set a key
43 43 Setting.mail_handler_api_enabled = 1
44 44 Setting.mail_handler_api_key = 'secret'
45 45
46 46 assert_difference 'Issue.count' do
47 47 post :index, :key => 'secret',
48 48 :email => IO.read(File.join(FIXTURES_PATH, 'ticket_on_given_project.eml')),
49 49 :issue => {:is_private => '1'}
50 50 end
51 51 assert_response 201
52 52 issue = Issue.order(:id => :desc).first
53 53 assert_equal true, issue.is_private
54 54 end
55 55
56 56 def test_should_respond_with_422_if_not_created
57 57 Project.find('onlinestore').destroy
58 58
59 59 Setting.mail_handler_api_enabled = 1
60 60 Setting.mail_handler_api_key = 'secret'
61 61
62 62 assert_no_difference 'Issue.count' do
63 63 post :index, :key => 'secret', :email => IO.read(File.join(FIXTURES_PATH, 'ticket_on_given_project.eml'))
64 64 end
65 65 assert_response 422
66 66 end
67 67
68 68 def test_should_not_allow_with_api_disabled
69 69 # Disable API
70 70 Setting.mail_handler_api_enabled = 0
71 71 Setting.mail_handler_api_key = 'secret'
72 72
73 73 assert_no_difference 'Issue.count' do
74 74 post :index, :key => 'secret', :email => IO.read(File.join(FIXTURES_PATH, 'ticket_on_given_project.eml'))
75 75 end
76 76 assert_response 403
77 assert_include 'Access denied', response.body
77 78 end
78 79
79 80 def test_should_not_allow_with_wrong_key
80 81 Setting.mail_handler_api_enabled = 1
81 82 Setting.mail_handler_api_key = 'secret'
82 83
83 84 assert_no_difference 'Issue.count' do
84 85 post :index, :key => 'wrong', :email => IO.read(File.join(FIXTURES_PATH, 'ticket_on_given_project.eml'))
85 86 end
86 87 assert_response 403
88 assert_include 'Access denied', response.body
87 89 end
88 90
89 91 def test_new
90 92 Setting.mail_handler_api_enabled = 1
91 93 Setting.mail_handler_api_key = 'secret'
92 94
93 95 get :new, :key => 'secret'
94 96 assert_response :success
95 97 end
96 98 end
@@ -1,132 +1,134
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2016 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 File.expand_path('../../test_helper', __FILE__)
19 19
20 20 class SysControllerTest < Redmine::ControllerTest
21 21 fixtures :projects, :repositories, :enabled_modules
22 22
23 23 def setup
24 24 Setting.sys_api_enabled = '1'
25 25 Setting.enabled_scm = %w(Subversion Git)
26 26 end
27 27
28 28 def teardown
29 29 Setting.clear_cache
30 30 end
31 31
32 32 def test_projects_with_repository_enabled
33 33 get :projects
34 34 assert_response :success
35 35 assert_equal 'application/xml', @response.content_type
36 36
37 37 assert_select 'projects' do
38 38 assert_select 'project', Project.active.has_module(:repository).count
39 39 assert_select 'project' do
40 40 assert_select 'identifier'
41 41 assert_select 'is-public'
42 42 end
43 43 end
44 44 assert_select 'extra-info', 0
45 45 assert_select 'extra_info', 0
46 46 end
47 47
48 48 def test_create_project_repository
49 49 assert_nil Project.find(4).repository
50 50
51 51 post :create_project_repository, :params => {
52 52 :id => 4,
53 53 :vendor => 'Subversion',
54 54 :repository => { :url => 'file:///create/project/repository/subproject2'}
55 55 }
56 56 assert_response :created
57 57 assert_equal 'application/xml', @response.content_type
58 58
59 59 r = Project.find(4).repository
60 60 assert r.is_a?(Repository::Subversion)
61 61 assert_equal 'file:///create/project/repository/subproject2', r.url
62 62
63 63 assert_select 'repository-subversion' do
64 64 assert_select 'id', :text => r.id.to_s
65 65 assert_select 'url', :text => r.url
66 66 end
67 67 assert_select 'extra-info', 0
68 68 assert_select 'extra_info', 0
69 69 end
70 70
71 71 def test_create_already_existing
72 72 post :create_project_repository, :params => {
73 73 :id => 1,
74 74 :vendor => 'Subversion',
75 75 :repository => { :url => 'file:///create/project/repository/subproject2'}
76 76 }
77 77 assert_response :conflict
78 78 end
79 79
80 80 def test_create_with_failure
81 81 post :create_project_repository, :params => {
82 82 :id => 4,
83 83 :vendor => 'Subversion',
84 84 :repository => { :url => 'invalid url'}
85 85 }
86 86 assert_response :unprocessable_entity
87 87 end
88 88
89 89 def test_fetch_changesets
90 90 Repository::Subversion.any_instance.expects(:fetch_changesets).twice.returns(true)
91 91 get :fetch_changesets
92 92 assert_response :success
93 93 end
94 94
95 95 def test_fetch_changesets_one_project_by_identifier
96 96 Repository::Subversion.any_instance.expects(:fetch_changesets).once.returns(true)
97 97 get :fetch_changesets, :params => {:id => 'ecookbook'}
98 98 assert_response :success
99 99 end
100 100
101 101 def test_fetch_changesets_one_project_by_id
102 102 Repository::Subversion.any_instance.expects(:fetch_changesets).once.returns(true)
103 103 get :fetch_changesets, :params => {:id => '1'}
104 104 assert_response :success
105 105 end
106 106
107 107 def test_fetch_changesets_unknown_project
108 108 get :fetch_changesets, :params => {:id => 'unknown'}
109 109 assert_response 404
110 110 end
111 111
112 112 def test_disabled_ws_should_respond_with_403_error
113 113 with_settings :sys_api_enabled => '0' do
114 114 get :projects
115 115 assert_response 403
116 assert_include 'Access denied', response.body
116 117 end
117 118 end
118 119
119 120 def test_api_key
120 121 with_settings :sys_api_key => 'my_secret_key' do
121 122 get :projects, :params => {:key => 'my_secret_key'}
122 123 assert_response :success
123 124 end
124 125 end
125 126
126 127 def test_wrong_key_should_respond_with_403_error
127 128 with_settings :sys_api_enabled => 'my_secret_key' do
128 129 get :projects, :params => {:key => 'wrong_key'}
129 130 assert_response 403
131 assert_include 'Access denied', response.body
130 132 end
131 133 end
132 134 end
@@ -1,335 +1,380
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2016 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 File.expand_path('../../test_helper', __FILE__)
19 19
20 20 class WatchersControllerTest < Redmine::ControllerTest
21 21 fixtures :projects, :users, :roles, :members, :member_roles, :enabled_modules,
22 22 :issues, :trackers, :projects_trackers, :issue_statuses, :enumerations, :watchers
23 23
24 24 def setup
25 25 User.current = nil
26 26 end
27 27
28 def test_watch_a_single_object_as_html
29 @request.session[:user_id] = 3
30 assert_difference('Watcher.count') do
31 post :watch, :params => {:object_type => 'issue', :object_id => '1'}
32 assert_response :success
33 assert_include 'Watcher added', response.body
34 end
35 assert Issue.find(1).watched_by?(User.find(3))
36 end
37
28 38 def test_watch_a_single_object
29 39 @request.session[:user_id] = 3
30 40 assert_difference('Watcher.count') do
31 41 xhr :post, :watch, :params => {:object_type => 'issue', :object_id => '1'}
32 42 assert_response :success
33 43 assert_include '$(".issue-1-watcher")', response.body
34 44 end
35 45 assert Issue.find(1).watched_by?(User.find(3))
36 46 end
37 47
38 48 def test_watch_a_collection_with_a_single_object
39 49 @request.session[:user_id] = 3
40 50 assert_difference('Watcher.count') do
41 51 xhr :post, :watch, :params => {:object_type => 'issue', :object_id => ['1']}
42 52 assert_response :success
43 53 assert_include '$(".issue-1-watcher")', response.body
44 54 end
45 55 assert Issue.find(1).watched_by?(User.find(3))
46 56 end
47 57
48 58 def test_watch_a_collection_with_multiple_objects
49 59 @request.session[:user_id] = 3
50 60 assert_difference('Watcher.count', 2) do
51 61 xhr :post, :watch, :params => {:object_type => 'issue', :object_id => ['1', '3']}
52 62 assert_response :success
53 63 assert_include '$(".issue-bulk-watcher")', response.body
54 64 end
55 65 assert Issue.find(1).watched_by?(User.find(3))
56 66 assert Issue.find(3).watched_by?(User.find(3))
57 67 end
58 68
59 69 def test_watch_a_news_module_should_add_watcher
60 70 @request.session[:user_id] = 7
61 71 assert_not_nil m = Project.find(1).enabled_module('news')
62 72
63 73 assert_difference 'Watcher.count' do
64 74 xhr :post, :watch, :params => {:object_type => 'enabled_module', :object_id => m.id.to_s}
65 75 assert_response :success
66 76 end
67 77 assert m.reload.watched_by?(User.find(7))
68 78 end
69 79
70 80 def test_watch_a_private_news_module_without_permission_should_fail
71 81 @request.session[:user_id] = 7
72 82 assert_not_nil m = Project.find(2).enabled_module('news')
73 83
74 84 assert_no_difference 'Watcher.count' do
75 85 xhr :post, :watch, :params => {:object_type => 'enabled_module', :object_id => m.id.to_s}
76 86 assert_response 403
77 87 end
78 88 end
79 89
80 90 def test_watch_should_be_denied_without_permission
81 91 Role.find(2).remove_permission! :view_issues
82 92 @request.session[:user_id] = 3
83 93 assert_no_difference('Watcher.count') do
84 94 xhr :post, :watch, :params => {:object_type => 'issue', :object_id => '1'}
85 95 assert_response 403
86 96 end
87 97 end
88 98
89 99 def test_watch_invalid_class_should_respond_with_404
90 100 @request.session[:user_id] = 3
91 101 assert_no_difference('Watcher.count') do
92 102 xhr :post, :watch, :params => {:object_type => 'foo', :object_id => '1'}
93 103 assert_response 404
94 104 end
95 105 end
96 106
97 107 def test_watch_invalid_object_should_respond_with_404
98 108 @request.session[:user_id] = 3
99 109 assert_no_difference('Watcher.count') do
100 110 xhr :post, :watch, :params => {:object_type => 'issue', :object_id => '999'}
101 111 assert_response 404
102 112 end
103 113 end
104 114
115 def test_unwatch_as_html
116 @request.session[:user_id] = 3
117 assert_difference('Watcher.count', -1) do
118 delete :unwatch, :params => {:object_type => 'issue', :object_id => '2'}
119 assert_response :success
120 assert_include 'Watcher removed', response.body
121 end
122 assert !Issue.find(1).watched_by?(User.find(3))
123 end
124
105 125 def test_unwatch
106 126 @request.session[:user_id] = 3
107 127 assert_difference('Watcher.count', -1) do
108 128 xhr :delete, :unwatch, :params => {:object_type => 'issue', :object_id => '2'}
109 129 assert_response :success
110 130 assert_include '$(".issue-2-watcher")', response.body
111 131 end
112 132 assert !Issue.find(1).watched_by?(User.find(3))
113 133 end
114 134
115 135 def test_unwatch_a_collection_with_multiple_objects
116 136 @request.session[:user_id] = 3
117 137 Watcher.create!(:user_id => 3, :watchable => Issue.find(1))
118 138 Watcher.create!(:user_id => 3, :watchable => Issue.find(3))
119 139
120 140 assert_difference('Watcher.count', -2) do
121 141 xhr :delete, :unwatch, :params => {:object_type => 'issue', :object_id => ['1', '3']}
122 142 assert_response :success
123 143 assert_include '$(".issue-bulk-watcher")', response.body
124 144 end
125 145 assert !Issue.find(1).watched_by?(User.find(3))
126 146 assert !Issue.find(3).watched_by?(User.find(3))
127 147 end
128 148
129 149 def test_new
130 150 @request.session[:user_id] = 2
131 151 xhr :get, :new, :params => {:object_type => 'issue', :object_id => '2'}
132 152 assert_response :success
133 153 assert_match /ajax-modal/, response.body
134 154 end
135 155
136 156 def test_new_with_multiple_objects
137 157 @request.session[:user_id] = 2
138 158 xhr :get, :new, :params => {:object_type => 'issue', :object_id => ['1', '2']}
139 159 assert_response :success
140 160 assert_match /ajax-modal/, response.body
141 161 end
142 162
143 163 def test_new_for_new_record_with_project_id
144 164 @request.session[:user_id] = 2
145 165 xhr :get, :new, :params => {:project_id => 1}
146 166 assert_response :success
147 167 assert_match /ajax-modal/, response.body
148 168 end
149 169
150 170 def test_new_for_new_record_with_project_identifier
151 171 @request.session[:user_id] = 2
152 172 xhr :get, :new, :params => {:project_id => 'ecookbook'}
153 173 assert_response :success
154 174 assert_match /ajax-modal/, response.body
155 175 end
156 176
177 def test_create_as_html
178 @request.session[:user_id] = 2
179 assert_difference('Watcher.count') do
180 post :create, :params => {
181 :object_type => 'issue', :object_id => '2',
182 :watcher => {:user_id => '4'}
183 }
184 assert_response :success
185 assert_include 'Watcher added', response.body
186 end
187 assert Issue.find(2).watched_by?(User.find(4))
188 end
189
157 190 def test_create
158 191 @request.session[:user_id] = 2
159 192 assert_difference('Watcher.count') do
160 193 xhr :post, :create, :params => {
161 194 :object_type => 'issue', :object_id => '2',
162 195 :watcher => {:user_id => '4'}
163 196 }
164 197 assert_response :success
165 198 assert_match /watchers/, response.body
166 199 assert_match /ajax-modal/, response.body
167 200 end
168 201 assert Issue.find(2).watched_by?(User.find(4))
169 202 end
170 203
171 204 def test_create_with_mutiple_users
172 205 @request.session[:user_id] = 2
173 206 assert_difference('Watcher.count', 2) do
174 207 xhr :post, :create, :params => {
175 208 :object_type => 'issue', :object_id => '2',
176 209 :watcher => {:user_ids => ['4', '7']}
177 210 }
178 211 assert_response :success
179 212 assert_match /watchers/, response.body
180 213 assert_match /ajax-modal/, response.body
181 214 end
182 215 assert Issue.find(2).watched_by?(User.find(4))
183 216 assert Issue.find(2).watched_by?(User.find(7))
184 217 end
185 218
186 219 def test_create_with_mutiple_objects
187 220 @request.session[:user_id] = 2
188 221 assert_difference('Watcher.count', 4) do
189 222 xhr :post, :create, :params => {
190 223 :object_type => 'issue', :object_id => ['1', '2'],
191 224 :watcher => {:user_ids => ['4', '7']}
192 225 }
193 226 assert_response :success
194 227 assert_match /watchers/, response.body
195 228 assert_match /ajax-modal/, response.body
196 229 end
197 230 assert Issue.find(1).watched_by?(User.find(4))
198 231 assert Issue.find(2).watched_by?(User.find(4))
199 232 assert Issue.find(1).watched_by?(User.find(7))
200 233 assert Issue.find(2).watched_by?(User.find(7))
201 234 end
202 235
203 236 def test_autocomplete_on_watchable_creation
204 237 @request.session[:user_id] = 2
205 238 xhr :get, :autocomplete_for_user, :params => {:q => 'mi', :project_id => 'ecookbook'}
206 239 assert_response :success
207 240 assert_select 'input', :count => 4
208 241 assert_select 'input[name=?][value="1"]', 'watcher[user_ids][]'
209 242 assert_select 'input[name=?][value="2"]', 'watcher[user_ids][]'
210 243 assert_select 'input[name=?][value="8"]', 'watcher[user_ids][]'
211 244 assert_select 'input[name=?][value="9"]', 'watcher[user_ids][]'
212 245 end
213 246
214 247 def test_search_non_member_on_create
215 248 @request.session[:user_id] = 2
216 249 project = Project.find_by_name("ecookbook")
217 250 user = User.generate!(:firstname => 'issue15622')
218 251 membership = user.membership(project)
219 252 assert_nil membership
220 253 xhr :get, :autocomplete_for_user, :params => {:q => 'issue15622', :project_id => 'ecookbook'}
221 254 assert_response :success
222 255 assert_select 'input', :count => 1
223 256 end
224 257
225 258 def test_autocomplete_on_watchable_update
226 259 @request.session[:user_id] = 2
227 260 xhr :get, :autocomplete_for_user, :params => {
228 261 :object_type => 'issue', :object_id => '2',
229 262 :project_id => 'ecookbook', :q => 'mi'
230 263 }
231 264 assert_response :success
232 265 assert_select 'input', :count => 3
233 266 assert_select 'input[name=?][value="2"]', 'watcher[user_ids][]'
234 267 assert_select 'input[name=?][value="8"]', 'watcher[user_ids][]'
235 268 assert_select 'input[name=?][value="9"]', 'watcher[user_ids][]'
236 269 end
237 270
238 271 def test_search_and_add_non_member_on_update
239 272 @request.session[:user_id] = 2
240 273 project = Project.find_by_name("ecookbook")
241 274 user = User.generate!(:firstname => 'issue15622')
242 275 membership = user.membership(project)
243 276 assert_nil membership
244 277
245 278 xhr :get, :autocomplete_for_user, :params => {
246 279 :object_type => 'issue', :object_id => '2',
247 280 :project_id => 'ecookbook', :q => 'issue15622'
248 281 }
249 282 assert_response :success
250 283 assert_select 'input', :count => 1
251 284
252 285 assert_difference('Watcher.count', 1) do
253 286 xhr :post, :create, :params => {
254 287 :object_type => 'issue', :object_id => '2',
255 288 :watcher => {:user_ids => ["#{user.id}"]}
256 289 }
257 290 assert_response :success
258 291 assert_match /watchers/, response.body
259 292 assert_match /ajax-modal/, response.body
260 293 end
261 294 assert Issue.find(2).watched_by?(user)
262 295 end
263 296
264 297 def test_autocomplete_for_user_should_return_visible_users
265 298 Role.update_all :users_visibility => 'members_of_visible_projects'
266 299
267 300 hidden = User.generate!(:lastname => 'autocomplete_hidden')
268 301 visible = User.generate!(:lastname => 'autocomplete_visible')
269 302 User.add_to_project(visible, Project.find(1))
270 303
271 304 @request.session[:user_id] = 2
272 305 xhr :get, :autocomplete_for_user, :params => {:q => 'autocomp', :project_id => 'ecookbook'}
273 306 assert_response :success
274 307
275 308 assert_include visible.name, response.body
276 309 assert_not_include hidden.name, response.body
277 310 end
278 311
279 312 def test_append
280 313 @request.session[:user_id] = 2
281 314 assert_no_difference 'Watcher.count' do
282 315 xhr :post, :append, :params => {
283 316 :watcher => {:user_ids => ['4', '7']}, :project_id => 'ecookbook'
284 317 }
285 318 assert_response :success
286 319 assert_include 'watchers_inputs', response.body
287 320 assert_include 'issue[watcher_user_ids][]', response.body
288 321 end
289 322 end
290 323
291 324 def test_append_without_user_should_render_nothing
292 325 @request.session[:user_id] = 2
293 326 xhr :post, :append, :params => {:project_id => 'ecookbook'}
294 327 assert_response :success
295 328 assert response.body.blank?
296 329 end
297 330
331 def test_destroy_as_html
332 @request.session[:user_id] = 2
333 assert_difference('Watcher.count', -1) do
334 delete :destroy, :params => {
335 :object_type => 'issue', :object_id => '2', :user_id => '3'
336 }
337 assert_response :success
338 assert_include 'Watcher removed', response.body
339 end
340 assert !Issue.find(2).watched_by?(User.find(3))
341 end
342
298 343 def test_destroy
299 344 @request.session[:user_id] = 2
300 345 assert_difference('Watcher.count', -1) do
301 346 xhr :delete, :destroy, :params => {
302 347 :object_type => 'issue', :object_id => '2', :user_id => '3'
303 348 }
304 349 assert_response :success
305 350 assert_match /watchers/, response.body
306 351 end
307 352 assert !Issue.find(2).watched_by?(User.find(3))
308 353 end
309 354
310 355 def test_destroy_locked_user
311 356 user = User.find(3)
312 357 user.lock!
313 358 assert user.reload.locked?
314 359
315 360 @request.session[:user_id] = 2
316 361 assert_difference('Watcher.count', -1) do
317 362 xhr :delete, :destroy, :params => {
318 363 :object_type => 'issue', :object_id => '2', :user_id => '3'
319 364 }
320 365 assert_response :success
321 366 assert_match /watchers/, response.body
322 367 end
323 368 assert !Issue.find(2).watched_by?(User.find(3))
324 369 end
325 370
326 371 def test_destroy_invalid_user_should_respond_with_404
327 372 @request.session[:user_id] = 2
328 373 assert_no_difference('Watcher.count') do
329 374 delete :destroy, :params => {
330 375 :object_type => 'issue', :object_id => '2', :user_id => '999'
331 376 }
332 377 assert_response 404
333 378 end
334 379 end
335 380 end
@@ -1,47 +1,56
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2016 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 File.expand_path('../../../test_helper', __FILE__)
19 19
20 20 class Redmine::ApiTest::ApiTest < Redmine::ApiTest::Base
21 21 fixtures :users
22 22
23 23 def test_api_should_work_with_protect_from_forgery
24 24 ActionController::Base.allow_forgery_protection = true
25 25 assert_difference('User.count') do
26 26 post '/users.xml', {
27 27 :user => {
28 28 :login => 'foo', :firstname => 'Firstname', :lastname => 'Lastname',
29 29 :mail => 'foo@example.net', :password => 'secret123'}
30 30 },
31 31 credentials('admin')
32 32 assert_response 201
33 33 end
34 34 ensure
35 35 ActionController::Base.allow_forgery_protection = false
36 36 end
37 37
38 38 def test_json_datetime_format
39 39 get '/users/1.json', {}, credentials('admin')
40 40 assert_include '"created_on":"2006-07-19T17:12:21Z"', response.body
41 41 end
42 42
43 43 def test_xml_datetime_format
44 44 get '/users/1.xml', {}, credentials('admin')
45 45 assert_include '<created_on>2006-07-19T17:12:21Z</created_on>', response.body
46 46 end
47
48 def test_head_response_should_have_empty_body
49 assert_difference('Issue.count', -1) do
50 delete '/issues/6.xml', {}, credentials('jsmith')
51
52 assert_response :ok
53 assert_equal '', response.body
54 end
55 end
47 56 end
General Comments 0
You need to be logged in to leave comments. Login now