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