##// END OF EJS Templates
Merged r13785 (#18665)....
Jean-Philippe Lang -
r13420:3c7aa17b5c3a
parent child
Show More
@@ -1,654 +1,656
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2014 Jean-Philippe Lang
2 # Copyright (C) 2006-2014 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 RoutesHelper
26 include RoutesHelper
27 helper :routes
27 helper :routes
28
28
29 class_attribute :accept_api_auth_actions
29 class_attribute :accept_api_auth_actions
30 class_attribute :accept_rss_auth_actions
30 class_attribute :accept_rss_auth_actions
31 class_attribute :model_object
31 class_attribute :model_object
32
32
33 layout 'base'
33 layout 'base'
34
34
35 protect_from_forgery
35 protect_from_forgery
36
36
37 def verify_authenticity_token
37 def verify_authenticity_token
38 unless api_request?
38 unless api_request?
39 super
39 super
40 end
40 end
41 end
41 end
42
42
43 def handle_unverified_request
43 def handle_unverified_request
44 unless api_request?
44 unless api_request?
45 super
45 super
46 cookies.delete(autologin_cookie_name)
46 cookies.delete(autologin_cookie_name)
47 self.logged_user = nil
47 self.logged_user = nil
48 set_localization
48 set_localization
49 render_error :status => 422, :message => "Invalid form authenticity token."
49 render_error :status => 422, :message => "Invalid form authenticity token."
50 end
50 end
51 end
51 end
52
52
53 before_filter :session_expiration, :user_setup, :force_logout_if_password_changed, :check_if_login_required, :check_password_change, :set_localization
53 before_filter :session_expiration, :user_setup, :force_logout_if_password_changed, :check_if_login_required, :check_password_change, :set_localization
54
54
55 rescue_from ::Unauthorized, :with => :deny_access
55 rescue_from ::Unauthorized, :with => :deny_access
56 rescue_from ::ActionView::MissingTemplate, :with => :missing_template
56 rescue_from ::ActionView::MissingTemplate, :with => :missing_template
57
57
58 include Redmine::Search::Controller
58 include Redmine::Search::Controller
59 include Redmine::MenuManager::MenuController
59 include Redmine::MenuManager::MenuController
60 helper Redmine::MenuManager::MenuHelper
60 helper Redmine::MenuManager::MenuHelper
61
61
62 def session_expiration
62 def session_expiration
63 if session[:user_id]
63 if session[:user_id]
64 if session_expired? && !try_to_autologin
64 if session_expired? && !try_to_autologin
65 set_localization(User.active.find_by_id(session[:user_id]))
65 set_localization(User.active.find_by_id(session[:user_id]))
66 reset_session
66 reset_session
67 flash[:error] = l(:error_session_expired)
67 flash[:error] = l(:error_session_expired)
68 redirect_to signin_url
68 redirect_to signin_url
69 else
69 else
70 session[:atime] = Time.now.utc.to_i
70 session[:atime] = Time.now.utc.to_i
71 end
71 end
72 end
72 end
73 end
73 end
74
74
75 def session_expired?
75 def session_expired?
76 if Setting.session_lifetime?
76 if Setting.session_lifetime?
77 unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
77 unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
78 return true
78 return true
79 end
79 end
80 end
80 end
81 if Setting.session_timeout?
81 if Setting.session_timeout?
82 unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
82 unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
83 return true
83 return true
84 end
84 end
85 end
85 end
86 false
86 false
87 end
87 end
88
88
89 def start_user_session(user)
89 def start_user_session(user)
90 session[:user_id] = user.id
90 session[:user_id] = user.id
91 session[:ctime] = Time.now.utc.to_i
91 session[:ctime] = Time.now.utc.to_i
92 session[:atime] = Time.now.utc.to_i
92 session[:atime] = Time.now.utc.to_i
93 if user.must_change_password?
93 if user.must_change_password?
94 session[:pwd] = '1'
94 session[:pwd] = '1'
95 end
95 end
96 end
96 end
97
97
98 def user_setup
98 def user_setup
99 # Check the settings cache for each request
99 # Check the settings cache for each request
100 Setting.check_cache
100 Setting.check_cache
101 # Find the current user
101 # Find the current user
102 User.current = find_current_user
102 User.current = find_current_user
103 logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
103 logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
104 end
104 end
105
105
106 # Returns the current user or nil if no user is logged in
106 # Returns the current user or nil if no user is logged in
107 # and starts a session if needed
107 # and starts a session if needed
108 def find_current_user
108 def find_current_user
109 user = nil
109 user = nil
110 unless api_request?
110 unless api_request?
111 if session[:user_id]
111 if session[:user_id]
112 # existing session
112 # existing session
113 user = (User.active.find(session[:user_id]) rescue nil)
113 user = (User.active.find(session[:user_id]) rescue nil)
114 elsif autologin_user = try_to_autologin
114 elsif autologin_user = try_to_autologin
115 user = autologin_user
115 user = autologin_user
116 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
116 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
117 # RSS key authentication does not start a session
117 # RSS key authentication does not start a session
118 user = User.find_by_rss_key(params[:key])
118 user = User.find_by_rss_key(params[:key])
119 end
119 end
120 end
120 end
121 if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
121 if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
122 if (key = api_key_from_request)
122 if (key = api_key_from_request)
123 # Use API key
123 # Use API key
124 user = User.find_by_api_key(key)
124 user = User.find_by_api_key(key)
125 elsif request.authorization.to_s =~ /\ABasic /i
125 elsif request.authorization.to_s =~ /\ABasic /i
126 # HTTP Basic, either username/password or API key/random
126 # HTTP Basic, either username/password or API key/random
127 authenticate_with_http_basic do |username, password|
127 authenticate_with_http_basic do |username, password|
128 user = User.try_to_login(username, password) || User.find_by_api_key(username)
128 user = User.try_to_login(username, password) || User.find_by_api_key(username)
129 end
129 end
130 if user && user.must_change_password?
130 if user && user.must_change_password?
131 render_error :message => 'You must change your password', :status => 403
131 render_error :message => 'You must change your password', :status => 403
132 return
132 return
133 end
133 end
134 end
134 end
135 # Switch user if requested by an admin user
135 # Switch user if requested by an admin user
136 if user && user.admin? && (username = api_switch_user_from_request)
136 if user && user.admin? && (username = api_switch_user_from_request)
137 su = User.find_by_login(username)
137 su = User.find_by_login(username)
138 if su && su.active?
138 if su && su.active?
139 logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
139 logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
140 user = su
140 user = su
141 else
141 else
142 render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
142 render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
143 end
143 end
144 end
144 end
145 end
145 end
146 user
146 user
147 end
147 end
148
148
149 def force_logout_if_password_changed
149 def force_logout_if_password_changed
150 passwd_changed_on = User.current.passwd_changed_on || Time.at(0)
150 passwd_changed_on = User.current.passwd_changed_on || Time.at(0)
151 # Make sure we force logout only for web browser sessions, not API calls
151 # Make sure we force logout only for web browser sessions, not API calls
152 # if the password was changed after the session creation.
152 # if the password was changed after the session creation.
153 if session[:user_id] && passwd_changed_on.utc.to_i > session[:ctime].to_i
153 if session[:user_id] && passwd_changed_on.utc.to_i > session[:ctime].to_i
154 reset_session
154 reset_session
155 set_localization
155 set_localization
156 flash[:error] = l(:error_session_expired)
156 flash[:error] = l(:error_session_expired)
157 redirect_to signin_url
157 redirect_to signin_url
158 end
158 end
159 end
159 end
160
160
161 def autologin_cookie_name
161 def autologin_cookie_name
162 Redmine::Configuration['autologin_cookie_name'].presence || 'autologin'
162 Redmine::Configuration['autologin_cookie_name'].presence || 'autologin'
163 end
163 end
164
164
165 def try_to_autologin
165 def try_to_autologin
166 if cookies[autologin_cookie_name] && Setting.autologin?
166 if cookies[autologin_cookie_name] && Setting.autologin?
167 # auto-login feature starts a new session
167 # auto-login feature starts a new session
168 user = User.try_to_autologin(cookies[autologin_cookie_name])
168 user = User.try_to_autologin(cookies[autologin_cookie_name])
169 if user
169 if user
170 reset_session
170 reset_session
171 start_user_session(user)
171 start_user_session(user)
172 end
172 end
173 user
173 user
174 end
174 end
175 end
175 end
176
176
177 # Sets the logged in user
177 # Sets the logged in user
178 def logged_user=(user)
178 def logged_user=(user)
179 reset_session
179 reset_session
180 if user && user.is_a?(User)
180 if user && user.is_a?(User)
181 User.current = user
181 User.current = user
182 start_user_session(user)
182 start_user_session(user)
183 else
183 else
184 User.current = User.anonymous
184 User.current = User.anonymous
185 end
185 end
186 end
186 end
187
187
188 # Logs out current user
188 # Logs out current user
189 def logout_user
189 def logout_user
190 if User.current.logged?
190 if User.current.logged?
191 cookies.delete(autologin_cookie_name)
191 cookies.delete(autologin_cookie_name)
192 Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
192 Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
193 self.logged_user = nil
193 self.logged_user = nil
194 end
194 end
195 end
195 end
196
196
197 # check if login is globally required to access the application
197 # check if login is globally required to access the application
198 def check_if_login_required
198 def check_if_login_required
199 # no check needed if user is already logged in
199 # no check needed if user is already logged in
200 return true if User.current.logged?
200 return true if User.current.logged?
201 require_login if Setting.login_required?
201 require_login if Setting.login_required?
202 end
202 end
203
203
204 def check_password_change
204 def check_password_change
205 if session[:pwd]
205 if session[:pwd]
206 if User.current.must_change_password?
206 if User.current.must_change_password?
207 redirect_to my_password_path
207 redirect_to my_password_path
208 else
208 else
209 session.delete(:pwd)
209 session.delete(:pwd)
210 end
210 end
211 end
211 end
212 end
212 end
213
213
214 def set_localization(user=User.current)
214 def set_localization(user=User.current)
215 lang = nil
215 lang = nil
216 if user && user.logged?
216 if user && user.logged?
217 lang = find_language(user.language)
217 lang = find_language(user.language)
218 end
218 end
219 if lang.nil? && !Setting.force_default_language_for_anonymous? && request.env['HTTP_ACCEPT_LANGUAGE']
219 if lang.nil? && !Setting.force_default_language_for_anonymous? && request.env['HTTP_ACCEPT_LANGUAGE']
220 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
220 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
221 if !accept_lang.blank?
221 if !accept_lang.blank?
222 accept_lang = accept_lang.downcase
222 accept_lang = accept_lang.downcase
223 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
223 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
224 end
224 end
225 end
225 end
226 lang ||= Setting.default_language
226 lang ||= Setting.default_language
227 set_language_if_valid(lang)
227 set_language_if_valid(lang)
228 end
228 end
229
229
230 def require_login
230 def require_login
231 if !User.current.logged?
231 if !User.current.logged?
232 # Extract only the basic url parameters on non-GET requests
232 # Extract only the basic url parameters on non-GET requests
233 if request.get?
233 if request.get?
234 url = url_for(params)
234 url = url_for(params)
235 else
235 else
236 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
236 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
237 end
237 end
238 respond_to do |format|
238 respond_to do |format|
239 format.html {
239 format.html {
240 if request.xhr?
240 if request.xhr?
241 head :unauthorized
241 head :unauthorized
242 else
242 else
243 redirect_to :controller => "account", :action => "login", :back_url => url
243 redirect_to :controller => "account", :action => "login", :back_url => url
244 end
244 end
245 }
245 }
246 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
246 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
247 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
247 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
248 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
248 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
249 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
249 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
250 end
250 end
251 return false
251 return false
252 end
252 end
253 true
253 true
254 end
254 end
255
255
256 def require_admin
256 def require_admin
257 return unless require_login
257 return unless require_login
258 if !User.current.admin?
258 if !User.current.admin?
259 render_403
259 render_403
260 return false
260 return false
261 end
261 end
262 true
262 true
263 end
263 end
264
264
265 def deny_access
265 def deny_access
266 User.current.logged? ? render_403 : require_login
266 User.current.logged? ? render_403 : require_login
267 end
267 end
268
268
269 # Authorize the user for the requested action
269 # Authorize the user for the requested action
270 def authorize(ctrl = params[:controller], action = params[:action], global = false)
270 def authorize(ctrl = params[:controller], action = params[:action], global = false)
271 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
271 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
272 if allowed
272 if allowed
273 true
273 true
274 else
274 else
275 if @project && @project.archived?
275 if @project && @project.archived?
276 render_403 :message => :notice_not_authorized_archived_project
276 render_403 :message => :notice_not_authorized_archived_project
277 else
277 else
278 deny_access
278 deny_access
279 end
279 end
280 end
280 end
281 end
281 end
282
282
283 # Authorize the user for the requested action outside a project
283 # Authorize the user for the requested action outside a project
284 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
284 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
285 authorize(ctrl, action, global)
285 authorize(ctrl, action, global)
286 end
286 end
287
287
288 # Find project of id params[:id]
288 # Find project of id params[:id]
289 def find_project
289 def find_project
290 @project = Project.find(params[:id])
290 @project = Project.find(params[:id])
291 rescue ActiveRecord::RecordNotFound
291 rescue ActiveRecord::RecordNotFound
292 render_404
292 render_404
293 end
293 end
294
294
295 # Find project of id params[:project_id]
295 # Find project of id params[:project_id]
296 def find_project_by_project_id
296 def find_project_by_project_id
297 @project = Project.find(params[:project_id])
297 @project = Project.find(params[:project_id])
298 rescue ActiveRecord::RecordNotFound
298 rescue ActiveRecord::RecordNotFound
299 render_404
299 render_404
300 end
300 end
301
301
302 # Find a project based on params[:project_id]
302 # Find a project based on params[:project_id]
303 # TODO: some subclasses override this, see about merging their logic
303 # TODO: some subclasses override this, see about merging their logic
304 def find_optional_project
304 def find_optional_project
305 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
305 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
306 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
306 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
307 allowed ? true : deny_access
307 allowed ? true : deny_access
308 rescue ActiveRecord::RecordNotFound
308 rescue ActiveRecord::RecordNotFound
309 render_404
309 render_404
310 end
310 end
311
311
312 # Finds and sets @project based on @object.project
312 # Finds and sets @project based on @object.project
313 def find_project_from_association
313 def find_project_from_association
314 render_404 unless @object.present?
314 render_404 unless @object.present?
315
315
316 @project = @object.project
316 @project = @object.project
317 end
317 end
318
318
319 def find_model_object
319 def find_model_object
320 model = self.class.model_object
320 model = self.class.model_object
321 if model
321 if model
322 @object = model.find(params[:id])
322 @object = model.find(params[:id])
323 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
323 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
324 end
324 end
325 rescue ActiveRecord::RecordNotFound
325 rescue ActiveRecord::RecordNotFound
326 render_404
326 render_404
327 end
327 end
328
328
329 def self.model_object(model)
329 def self.model_object(model)
330 self.model_object = model
330 self.model_object = model
331 end
331 end
332
332
333 # Find the issue whose id is the :id parameter
333 # Find the issue whose id is the :id parameter
334 # Raises a Unauthorized exception if the issue is not visible
334 # Raises a Unauthorized exception if the issue is not visible
335 def find_issue
335 def find_issue
336 # Issue.visible.find(...) can not be used to redirect user to the login form
336 # Issue.visible.find(...) can not be used to redirect user to the login form
337 # if the issue actually exists but requires authentication
337 # if the issue actually exists but requires authentication
338 @issue = Issue.find(params[:id])
338 @issue = Issue.find(params[:id])
339 raise Unauthorized unless @issue.visible?
339 raise Unauthorized unless @issue.visible?
340 @project = @issue.project
340 @project = @issue.project
341 rescue ActiveRecord::RecordNotFound
341 rescue ActiveRecord::RecordNotFound
342 render_404
342 render_404
343 end
343 end
344
344
345 # Find issues with a single :id param or :ids array param
345 # Find issues with a single :id param or :ids array param
346 # Raises a Unauthorized exception if one of the issues is not visible
346 # Raises a Unauthorized exception if one of the issues is not visible
347 def find_issues
347 def find_issues
348 @issues = Issue.where(:id => (params[:id] || params[:ids])).preload(:project, :status, :tracker, :priority, :author, :assigned_to, :relations_to).to_a
348 @issues = Issue.where(:id => (params[:id] || params[:ids])).preload(:project, :status, :tracker, :priority, :author, :assigned_to, :relations_to).to_a
349 raise ActiveRecord::RecordNotFound if @issues.empty?
349 raise ActiveRecord::RecordNotFound if @issues.empty?
350 raise Unauthorized unless @issues.all?(&:visible?)
350 raise Unauthorized unless @issues.all?(&:visible?)
351 @projects = @issues.collect(&:project).compact.uniq
351 @projects = @issues.collect(&:project).compact.uniq
352 @project = @projects.first if @projects.size == 1
352 @project = @projects.first if @projects.size == 1
353 rescue ActiveRecord::RecordNotFound
353 rescue ActiveRecord::RecordNotFound
354 render_404
354 render_404
355 end
355 end
356
356
357 def find_attachments
357 def find_attachments
358 if (attachments = params[:attachments]).present?
358 if (attachments = params[:attachments]).present?
359 att = attachments.values.collect do |attachment|
359 att = attachments.values.collect do |attachment|
360 Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
360 Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
361 end
361 end
362 att.compact!
362 att.compact!
363 end
363 end
364 @attachments = att || []
364 @attachments = att || []
365 end
365 end
366
366
367 # make sure that the user is a member of the project (or admin) if project is private
367 # make sure that the user is a member of the project (or admin) if project is private
368 # used as a before_filter for actions that do not require any particular permission on the project
368 # used as a before_filter for actions that do not require any particular permission on the project
369 def check_project_privacy
369 def check_project_privacy
370 if @project && !@project.archived?
370 if @project && !@project.archived?
371 if @project.visible?
371 if @project.visible?
372 true
372 true
373 else
373 else
374 deny_access
374 deny_access
375 end
375 end
376 else
376 else
377 @project = nil
377 @project = nil
378 render_404
378 render_404
379 false
379 false
380 end
380 end
381 end
381 end
382
382
383 def back_url
383 def back_url
384 url = params[:back_url]
384 url = params[:back_url]
385 if url.nil? && referer = request.env['HTTP_REFERER']
385 if url.nil? && referer = request.env['HTTP_REFERER']
386 url = CGI.unescape(referer.to_s)
386 url = CGI.unescape(referer.to_s)
387 end
387 end
388 url
388 url
389 end
389 end
390
390
391 def redirect_back_or_default(default, options={})
391 def redirect_back_or_default(default, options={})
392 back_url = params[:back_url].to_s
392 back_url = params[:back_url].to_s
393 if back_url.present? && valid_back_url?(back_url)
393 if back_url.present? && valid_back_url?(back_url)
394 redirect_to(back_url)
394 redirect_to(back_url)
395 return
395 return
396 elsif options[:referer]
396 elsif options[:referer]
397 redirect_to_referer_or default
397 redirect_to_referer_or default
398 return
398 return
399 end
399 end
400 redirect_to default
400 redirect_to default
401 false
401 false
402 end
402 end
403
403
404 # Returns true if back_url is a valid url for redirection, otherwise false
404 # Returns true if back_url is a valid url for redirection, otherwise false
405 def valid_back_url?(back_url)
405 def valid_back_url?(back_url)
406 if CGI.unescape(back_url).include?('..')
406 if CGI.unescape(back_url).include?('..')
407 return false
407 return false
408 end
408 end
409
409
410 begin
410 begin
411 uri = URI.parse(back_url)
411 uri = URI.parse(back_url)
412 rescue URI::InvalidURIError
412 rescue URI::InvalidURIError
413 return false
413 return false
414 end
414 end
415
415
416 if uri.host.present? && uri.host != request.host
416 if uri.host.present? && uri.host != request.host
417 return false
417 return false
418 end
418 end
419
419
420 if uri.path.match(%r{/(login|account/register)})
420 if uri.path.match(%r{/(login|account/register)})
421 return false
421 return false
422 end
422 end
423
423
424 if relative_url_root.present? && !uri.path.starts_with?(relative_url_root)
424 if relative_url_root.present? && !uri.path.starts_with?(relative_url_root)
425 return false
425 return false
426 end
426 end
427
427
428 return true
428 return true
429 end
429 end
430 private :valid_back_url?
430 private :valid_back_url?
431
431
432 # Redirects to the request referer if present, redirects to args or call block otherwise.
432 # Redirects to the request referer if present, redirects to args or call block otherwise.
433 def redirect_to_referer_or(*args, &block)
433 def redirect_to_referer_or(*args, &block)
434 redirect_to :back
434 redirect_to :back
435 rescue ::ActionController::RedirectBackError
435 rescue ::ActionController::RedirectBackError
436 if args.any?
436 if args.any?
437 redirect_to *args
437 redirect_to *args
438 elsif block_given?
438 elsif block_given?
439 block.call
439 block.call
440 else
440 else
441 raise "#redirect_to_referer_or takes arguments or a block"
441 raise "#redirect_to_referer_or takes arguments or a block"
442 end
442 end
443 end
443 end
444
444
445 def render_403(options={})
445 def render_403(options={})
446 @project = nil
446 @project = nil
447 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
447 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
448 return false
448 return false
449 end
449 end
450
450
451 def render_404(options={})
451 def render_404(options={})
452 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
452 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
453 return false
453 return false
454 end
454 end
455
455
456 # Renders an error response
456 # Renders an error response
457 def render_error(arg)
457 def render_error(arg)
458 arg = {:message => arg} unless arg.is_a?(Hash)
458 arg = {:message => arg} unless arg.is_a?(Hash)
459
459
460 @message = arg[:message]
460 @message = arg[:message]
461 @message = l(@message) if @message.is_a?(Symbol)
461 @message = l(@message) if @message.is_a?(Symbol)
462 @status = arg[:status] || 500
462 @status = arg[:status] || 500
463
463
464 respond_to do |format|
464 respond_to do |format|
465 format.html {
465 format.html {
466 render :template => 'common/error', :layout => use_layout, :status => @status
466 render :template => 'common/error', :layout => use_layout, :status => @status
467 }
467 }
468 format.any { head @status }
468 format.any { head @status }
469 end
469 end
470 end
470 end
471
471
472 # Handler for ActionView::MissingTemplate exception
472 # Handler for ActionView::MissingTemplate exception
473 def missing_template
473 def missing_template
474 logger.warn "Missing template, responding with 404"
474 logger.warn "Missing template, responding with 404"
475 @project = nil
475 @project = nil
476 render_404
476 render_404
477 end
477 end
478
478
479 # Filter for actions that provide an API response
479 # Filter for actions that provide an API response
480 # but have no HTML representation for non admin users
480 # but have no HTML representation for non admin users
481 def require_admin_or_api_request
481 def require_admin_or_api_request
482 return true if api_request?
482 return true if api_request?
483 if User.current.admin?
483 if User.current.admin?
484 true
484 true
485 elsif User.current.logged?
485 elsif User.current.logged?
486 render_error(:status => 406)
486 render_error(:status => 406)
487 else
487 else
488 deny_access
488 deny_access
489 end
489 end
490 end
490 end
491
491
492 # Picks which layout to use based on the request
492 # Picks which layout to use based on the request
493 #
493 #
494 # @return [boolean, string] name of the layout to use or false for no layout
494 # @return [boolean, string] name of the layout to use or false for no layout
495 def use_layout
495 def use_layout
496 request.xhr? ? false : 'base'
496 request.xhr? ? false : 'base'
497 end
497 end
498
498
499 def render_feed(items, options={})
499 def render_feed(items, options={})
500 @items = items || []
500 @items = items || []
501 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
501 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
502 @items = @items.slice(0, Setting.feeds_limit.to_i)
502 @items = @items.slice(0, Setting.feeds_limit.to_i)
503 @title = options[:title] || Setting.app_title
503 @title = options[:title] || Setting.app_title
504 render :template => "common/feed", :formats => [:atom], :layout => false,
504 render :template => "common/feed", :formats => [:atom], :layout => false,
505 :content_type => 'application/atom+xml'
505 :content_type => 'application/atom+xml'
506 end
506 end
507
507
508 def self.accept_rss_auth(*actions)
508 def self.accept_rss_auth(*actions)
509 if actions.any?
509 if actions.any?
510 self.accept_rss_auth_actions = actions
510 self.accept_rss_auth_actions = actions
511 else
511 else
512 self.accept_rss_auth_actions || []
512 self.accept_rss_auth_actions || []
513 end
513 end
514 end
514 end
515
515
516 def accept_rss_auth?(action=action_name)
516 def accept_rss_auth?(action=action_name)
517 self.class.accept_rss_auth.include?(action.to_sym)
517 self.class.accept_rss_auth.include?(action.to_sym)
518 end
518 end
519
519
520 def self.accept_api_auth(*actions)
520 def self.accept_api_auth(*actions)
521 if actions.any?
521 if actions.any?
522 self.accept_api_auth_actions = actions
522 self.accept_api_auth_actions = actions
523 else
523 else
524 self.accept_api_auth_actions || []
524 self.accept_api_auth_actions || []
525 end
525 end
526 end
526 end
527
527
528 def accept_api_auth?(action=action_name)
528 def accept_api_auth?(action=action_name)
529 self.class.accept_api_auth.include?(action.to_sym)
529 self.class.accept_api_auth.include?(action.to_sym)
530 end
530 end
531
531
532 # Returns the number of objects that should be displayed
532 # Returns the number of objects that should be displayed
533 # on the paginated list
533 # on the paginated list
534 def per_page_option
534 def per_page_option
535 per_page = nil
535 per_page = nil
536 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
536 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
537 per_page = params[:per_page].to_s.to_i
537 per_page = params[:per_page].to_s.to_i
538 session[:per_page] = per_page
538 session[:per_page] = per_page
539 elsif session[:per_page]
539 elsif session[:per_page]
540 per_page = session[:per_page]
540 per_page = session[:per_page]
541 else
541 else
542 per_page = Setting.per_page_options_array.first || 25
542 per_page = Setting.per_page_options_array.first || 25
543 end
543 end
544 per_page
544 per_page
545 end
545 end
546
546
547 # Returns offset and limit used to retrieve objects
547 # Returns offset and limit used to retrieve objects
548 # for an API response based on offset, limit and page parameters
548 # for an API response based on offset, limit and page parameters
549 def api_offset_and_limit(options=params)
549 def api_offset_and_limit(options=params)
550 if options[:offset].present?
550 if options[:offset].present?
551 offset = options[:offset].to_i
551 offset = options[:offset].to_i
552 if offset < 0
552 if offset < 0
553 offset = 0
553 offset = 0
554 end
554 end
555 end
555 end
556 limit = options[:limit].to_i
556 limit = options[:limit].to_i
557 if limit < 1
557 if limit < 1
558 limit = 25
558 limit = 25
559 elsif limit > 100
559 elsif limit > 100
560 limit = 100
560 limit = 100
561 end
561 end
562 if offset.nil? && options[:page].present?
562 if offset.nil? && options[:page].present?
563 offset = (options[:page].to_i - 1) * limit
563 offset = (options[:page].to_i - 1) * limit
564 offset = 0 if offset < 0
564 offset = 0 if offset < 0
565 end
565 end
566 offset ||= 0
566 offset ||= 0
567
567
568 [offset, limit]
568 [offset, limit]
569 end
569 end
570
570
571 # qvalues http header parser
571 # qvalues http header parser
572 # code taken from webrick
572 # code taken from webrick
573 def parse_qvalues(value)
573 def parse_qvalues(value)
574 tmp = []
574 tmp = []
575 if value
575 if value
576 parts = value.split(/,\s*/)
576 parts = value.split(/,\s*/)
577 parts.each {|part|
577 parts.each {|part|
578 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
578 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
579 val = m[1]
579 val = m[1]
580 q = (m[2] or 1).to_f
580 q = (m[2] or 1).to_f
581 tmp.push([val, q])
581 tmp.push([val, q])
582 end
582 end
583 }
583 }
584 tmp = tmp.sort_by{|val, q| -q}
584 tmp = tmp.sort_by{|val, q| -q}
585 tmp.collect!{|val, q| val}
585 tmp.collect!{|val, q| val}
586 end
586 end
587 return tmp
587 return tmp
588 rescue
588 rescue
589 nil
589 nil
590 end
590 end
591
591
592 # Returns a string that can be used as filename value in Content-Disposition header
592 # Returns a string that can be used as filename value in Content-Disposition header
593 def filename_for_content_disposition(name)
593 def filename_for_content_disposition(name)
594 request.env['HTTP_USER_AGENT'] =~ %r{(MSIE|Trident)} ? ERB::Util.url_encode(name) : name
594 request.env['HTTP_USER_AGENT'] =~ %r{(MSIE|Trident)} ? ERB::Util.url_encode(name) : name
595 end
595 end
596
596
597 def api_request?
597 def api_request?
598 %w(xml json).include? params[:format]
598 %w(xml json).include? params[:format]
599 end
599 end
600
600
601 # Returns the API key present in the request
601 # Returns the API key present in the request
602 def api_key_from_request
602 def api_key_from_request
603 if params[:key].present?
603 if params[:key].present?
604 params[:key].to_s
604 params[:key].to_s
605 elsif request.headers["X-Redmine-API-Key"].present?
605 elsif request.headers["X-Redmine-API-Key"].present?
606 request.headers["X-Redmine-API-Key"].to_s
606 request.headers["X-Redmine-API-Key"].to_s
607 end
607 end
608 end
608 end
609
609
610 # Returns the API 'switch user' value if present
610 # Returns the API 'switch user' value if present
611 def api_switch_user_from_request
611 def api_switch_user_from_request
612 request.headers["X-Redmine-Switch-User"].to_s.presence
612 request.headers["X-Redmine-Switch-User"].to_s.presence
613 end
613 end
614
614
615 # Renders a warning flash if obj has unsaved attachments
615 # Renders a warning flash if obj has unsaved attachments
616 def render_attachment_warning_if_needed(obj)
616 def render_attachment_warning_if_needed(obj)
617 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
617 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
618 end
618 end
619
619
620 # Rescues an invalid query statement. Just in case...
620 # Rescues an invalid query statement. Just in case...
621 def query_statement_invalid(exception)
621 def query_statement_invalid(exception)
622 logger.error "Query::StatementInvalid: #{exception.message}" if logger
622 logger.error "Query::StatementInvalid: #{exception.message}" if logger
623 session.delete(:query)
623 session.delete(:query)
624 sort_clear if respond_to?(:sort_clear)
624 sort_clear if respond_to?(:sort_clear)
625 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
625 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
626 end
626 end
627
627
628 # Renders a 200 response for successfull updates or deletions via the API
628 # Renders a 200 response for successfull updates or deletions via the API
629 def render_api_ok
629 def render_api_ok
630 render_api_head :ok
630 render_api_head :ok
631 end
631 end
632
632
633 # Renders a head API response
633 # Renders a head API response
634 def render_api_head(status)
634 def render_api_head(status)
635 # #head would return a response body with one space
635 # #head would return a response body with one space
636 render :text => '', :status => status, :layout => nil
636 render :text => '', :status => status, :layout => nil
637 end
637 end
638
638
639 # Renders API response on validation failure
639 # Renders API response on validation failure
640 # for an object or an array of objects
640 def render_validation_errors(objects)
641 def render_validation_errors(objects)
641 if objects.is_a?(Array)
642 messages = Array.wrap(objects).map {|object| object.errors.full_messages}.flatten
642 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
643 render_api_errors(messages)
643 else
644 end
644 @error_messages = objects.errors.full_messages
645
645 end
646 def render_api_errors(*messages)
647 @error_messages = messages.flatten
646 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
648 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
647 end
649 end
648
650
649 # Overrides #_include_layout? so that #render with no arguments
651 # Overrides #_include_layout? so that #render with no arguments
650 # doesn't use the layout for api requests
652 # doesn't use the layout for api requests
651 def _include_layout?(*args)
653 def _include_layout?(*args)
652 api_request? ? false : super
654 api_request? ? false : super
653 end
655 end
654 end
656 end
@@ -1,154 +1,160
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2014 Jean-Philippe Lang
2 # Copyright (C) 2006-2014 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 GroupsController < ApplicationController
18 class GroupsController < ApplicationController
19 layout 'admin'
19 layout 'admin'
20
20
21 before_filter :require_admin
21 before_filter :require_admin
22 before_filter :find_group, :except => [:index, :new, :create]
22 before_filter :find_group, :except => [:index, :new, :create]
23 accept_api_auth :index, :show, :create, :update, :destroy, :add_users, :remove_user
23 accept_api_auth :index, :show, :create, :update, :destroy, :add_users, :remove_user
24
24
25 helper :custom_fields
25 helper :custom_fields
26
26
27 def index
27 def index
28 respond_to do |format|
28 respond_to do |format|
29 format.html {
29 format.html {
30 @groups = Group.sorted.all
30 @groups = Group.sorted.all
31 @user_count_by_group_id = user_count_by_group_id
31 @user_count_by_group_id = user_count_by_group_id
32 }
32 }
33 format.api {
33 format.api {
34 scope = Group.sorted
34 scope = Group.sorted
35 scope = scope.givable unless params[:builtin] == '1'
35 scope = scope.givable unless params[:builtin] == '1'
36 @groups = scope.all
36 @groups = scope.all
37 }
37 }
38 end
38 end
39 end
39 end
40
40
41 def show
41 def show
42 respond_to do |format|
42 respond_to do |format|
43 format.html
43 format.html
44 format.api
44 format.api
45 end
45 end
46 end
46 end
47
47
48 def new
48 def new
49 @group = Group.new
49 @group = Group.new
50 end
50 end
51
51
52 def create
52 def create
53 @group = Group.new
53 @group = Group.new
54 @group.safe_attributes = params[:group]
54 @group.safe_attributes = params[:group]
55
55
56 respond_to do |format|
56 respond_to do |format|
57 if @group.save
57 if @group.save
58 format.html {
58 format.html {
59 flash[:notice] = l(:notice_successful_create)
59 flash[:notice] = l(:notice_successful_create)
60 redirect_to(params[:continue] ? new_group_path : groups_path)
60 redirect_to(params[:continue] ? new_group_path : groups_path)
61 }
61 }
62 format.api { render :action => 'show', :status => :created, :location => group_url(@group) }
62 format.api { render :action => 'show', :status => :created, :location => group_url(@group) }
63 else
63 else
64 format.html { render :action => "new" }
64 format.html { render :action => "new" }
65 format.api { render_validation_errors(@group) }
65 format.api { render_validation_errors(@group) }
66 end
66 end
67 end
67 end
68 end
68 end
69
69
70 def edit
70 def edit
71 end
71 end
72
72
73 def update
73 def update
74 @group.safe_attributes = params[:group]
74 @group.safe_attributes = params[:group]
75
75
76 respond_to do |format|
76 respond_to do |format|
77 if @group.save
77 if @group.save
78 flash[:notice] = l(:notice_successful_update)
78 flash[:notice] = l(:notice_successful_update)
79 format.html { redirect_to(groups_path) }
79 format.html { redirect_to(groups_path) }
80 format.api { render_api_ok }
80 format.api { render_api_ok }
81 else
81 else
82 format.html { render :action => "edit" }
82 format.html { render :action => "edit" }
83 format.api { render_validation_errors(@group) }
83 format.api { render_validation_errors(@group) }
84 end
84 end
85 end
85 end
86 end
86 end
87
87
88 def destroy
88 def destroy
89 @group.destroy
89 @group.destroy
90
90
91 respond_to do |format|
91 respond_to do |format|
92 format.html { redirect_to(groups_path) }
92 format.html { redirect_to(groups_path) }
93 format.api { render_api_ok }
93 format.api { render_api_ok }
94 end
94 end
95 end
95 end
96
96
97 def add_users
97 def add_users
98 @users = User.where(:id => (params[:user_id] || params[:user_ids])).all
98 @users = User.not_in_group(@group).where(:id => (params[:user_id] || params[:user_ids])).to_a
99 @group.users << @users if request.post?
99 @group.users << @users
100 respond_to do |format|
100 respond_to do |format|
101 format.html { redirect_to edit_group_path(@group, :tab => 'users') }
101 format.html { redirect_to edit_group_path(@group, :tab => 'users') }
102 format.js
102 format.js
103 format.api { render_api_ok }
103 format.api {
104 if @users.any?
105 render_api_ok
106 else
107 render_api_errors "#{l(:label_user)} #{l('activerecord.errors.messages.invalid')}"
108 end
109 }
104 end
110 end
105 end
111 end
106
112
107 def remove_user
113 def remove_user
108 @group.users.delete(User.find(params[:user_id])) if request.delete?
114 @group.users.delete(User.find(params[:user_id])) if request.delete?
109 respond_to do |format|
115 respond_to do |format|
110 format.html { redirect_to edit_group_path(@group, :tab => 'users') }
116 format.html { redirect_to edit_group_path(@group, :tab => 'users') }
111 format.js
117 format.js
112 format.api { render_api_ok }
118 format.api { render_api_ok }
113 end
119 end
114 end
120 end
115
121
116 def autocomplete_for_user
122 def autocomplete_for_user
117 respond_to do |format|
123 respond_to do |format|
118 format.js
124 format.js
119 end
125 end
120 end
126 end
121
127
122 def edit_membership
128 def edit_membership
123 @membership = Member.edit_membership(params[:membership_id], params[:membership], @group)
129 @membership = Member.edit_membership(params[:membership_id], params[:membership], @group)
124 @membership.save if request.post?
130 @membership.save if request.post?
125 respond_to do |format|
131 respond_to do |format|
126 format.html { redirect_to edit_group_path(@group, :tab => 'memberships') }
132 format.html { redirect_to edit_group_path(@group, :tab => 'memberships') }
127 format.js
133 format.js
128 end
134 end
129 end
135 end
130
136
131 def destroy_membership
137 def destroy_membership
132 Member.find(params[:membership_id]).destroy if request.post?
138 Member.find(params[:membership_id]).destroy if request.post?
133 respond_to do |format|
139 respond_to do |format|
134 format.html { redirect_to edit_group_path(@group, :tab => 'memberships') }
140 format.html { redirect_to edit_group_path(@group, :tab => 'memberships') }
135 format.js
141 format.js
136 end
142 end
137 end
143 end
138
144
139 private
145 private
140
146
141 def find_group
147 def find_group
142 @group = Group.find(params[:id])
148 @group = Group.find(params[:id])
143 rescue ActiveRecord::RecordNotFound
149 rescue ActiveRecord::RecordNotFound
144 render_404
150 render_404
145 end
151 end
146
152
147 def user_count_by_group_id
153 def user_count_by_group_id
148 h = User.joins(:groups).group('group_id').count
154 h = User.joins(:groups).group('group_id').count
149 h.keys.each do |key|
155 h.keys.each do |key|
150 h[key.to_i] = h.delete(key)
156 h[key.to_i] = h.delete(key)
151 end
157 end
152 h
158 h
153 end
159 end
154 end
160 end
@@ -1,200 +1,213
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2014 Jean-Philippe Lang
2 # Copyright (C) 2006-2014 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::GroupsTest < Redmine::ApiTest::Base
20 class Redmine::ApiTest::GroupsTest < Redmine::ApiTest::Base
21 fixtures :users, :groups_users
21 fixtures :users, :groups_users
22
22
23 def setup
23 def setup
24 Setting.rest_api_enabled = '1'
24 Setting.rest_api_enabled = '1'
25 end
25 end
26
26
27 test "GET /groups.xml should require authentication" do
27 test "GET /groups.xml should require authentication" do
28 get '/groups.xml'
28 get '/groups.xml'
29 assert_response 401
29 assert_response 401
30 end
30 end
31
31
32 test "GET /groups.xml should return givable groups" do
32 test "GET /groups.xml should return givable groups" do
33 get '/groups.xml', {}, credentials('admin')
33 get '/groups.xml', {}, credentials('admin')
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 'groups' do
37 assert_select 'groups' do
38 assert_select 'group', Group.givable.count
38 assert_select 'group', Group.givable.count
39 assert_select 'group' do
39 assert_select 'group' do
40 assert_select 'name', :text => 'A Team'
40 assert_select 'name', :text => 'A Team'
41 assert_select 'id', :text => '10'
41 assert_select 'id', :text => '10'
42 end
42 end
43 end
43 end
44 end
44 end
45
45
46 test "GET /groups.xml?builtin=1 should return all groups" do
46 test "GET /groups.xml?builtin=1 should return all groups" do
47 get '/groups.xml?builtin=1', {}, credentials('admin')
47 get '/groups.xml?builtin=1', {}, credentials('admin')
48 assert_response :success
48 assert_response :success
49 assert_equal 'application/xml', response.content_type
49 assert_equal 'application/xml', response.content_type
50
50
51 assert_select 'groups' do
51 assert_select 'groups' do
52 assert_select 'group', Group.givable.count + 2
52 assert_select 'group', Group.givable.count + 2
53 assert_select 'group' do
53 assert_select 'group' do
54 assert_select 'builtin', :text => 'non_member'
54 assert_select 'builtin', :text => 'non_member'
55 assert_select 'id', :text => '12'
55 assert_select 'id', :text => '12'
56 end
56 end
57 assert_select 'group' do
57 assert_select 'group' do
58 assert_select 'builtin', :text => 'anonymous'
58 assert_select 'builtin', :text => 'anonymous'
59 assert_select 'id', :text => '13'
59 assert_select 'id', :text => '13'
60 end
60 end
61 end
61 end
62 end
62 end
63
63
64 test "GET /groups.json should require authentication" do
64 test "GET /groups.json should require authentication" do
65 get '/groups.json'
65 get '/groups.json'
66 assert_response 401
66 assert_response 401
67 end
67 end
68
68
69 test "GET /groups.json should return groups" do
69 test "GET /groups.json should return groups" do
70 get '/groups.json', {}, credentials('admin')
70 get '/groups.json', {}, credentials('admin')
71 assert_response :success
71 assert_response :success
72 assert_equal 'application/json', response.content_type
72 assert_equal 'application/json', response.content_type
73
73
74 json = MultiJson.load(response.body)
74 json = MultiJson.load(response.body)
75 groups = json['groups']
75 groups = json['groups']
76 assert_kind_of Array, groups
76 assert_kind_of Array, groups
77 group = groups.detect {|g| g['name'] == 'A Team'}
77 group = groups.detect {|g| g['name'] == 'A Team'}
78 assert_not_nil group
78 assert_not_nil group
79 assert_equal({'id' => 10, 'name' => 'A Team'}, group)
79 assert_equal({'id' => 10, 'name' => 'A Team'}, group)
80 end
80 end
81
81
82 test "GET /groups/:id.xml should return the group" do
82 test "GET /groups/:id.xml should return the group" do
83 get '/groups/10.xml', {}, credentials('admin')
83 get '/groups/10.xml', {}, credentials('admin')
84 assert_response :success
84 assert_response :success
85 assert_equal 'application/xml', response.content_type
85 assert_equal 'application/xml', response.content_type
86
86
87 assert_select 'group' do
87 assert_select 'group' do
88 assert_select 'name', :text => 'A Team'
88 assert_select 'name', :text => 'A Team'
89 assert_select 'id', :text => '10'
89 assert_select 'id', :text => '10'
90 end
90 end
91 end
91 end
92
92
93 test "GET /groups/:id.xml should return the builtin group" do
93 test "GET /groups/:id.xml should return the builtin group" do
94 get '/groups/12.xml', {}, credentials('admin')
94 get '/groups/12.xml', {}, credentials('admin')
95 assert_response :success
95 assert_response :success
96 assert_equal 'application/xml', response.content_type
96 assert_equal 'application/xml', response.content_type
97
97
98 assert_select 'group' do
98 assert_select 'group' do
99 assert_select 'builtin', :text => 'non_member'
99 assert_select 'builtin', :text => 'non_member'
100 assert_select 'id', :text => '12'
100 assert_select 'id', :text => '12'
101 end
101 end
102 end
102 end
103
103
104 test "GET /groups/:id.xml should include users if requested" do
104 test "GET /groups/:id.xml should include users if requested" do
105 get '/groups/10.xml?include=users', {}, credentials('admin')
105 get '/groups/10.xml?include=users', {}, credentials('admin')
106 assert_response :success
106 assert_response :success
107 assert_equal 'application/xml', response.content_type
107 assert_equal 'application/xml', response.content_type
108
108
109 assert_select 'group' do
109 assert_select 'group' do
110 assert_select 'users' do
110 assert_select 'users' do
111 assert_select 'user', Group.find(10).users.count
111 assert_select 'user', Group.find(10).users.count
112 assert_select 'user[id=8]'
112 assert_select 'user[id=8]'
113 end
113 end
114 end
114 end
115 end
115 end
116
116
117 test "GET /groups/:id.xml include memberships if requested" do
117 test "GET /groups/:id.xml include memberships if requested" do
118 get '/groups/10.xml?include=memberships', {}, credentials('admin')
118 get '/groups/10.xml?include=memberships', {}, credentials('admin')
119 assert_response :success
119 assert_response :success
120 assert_equal 'application/xml', response.content_type
120 assert_equal 'application/xml', response.content_type
121
121
122 assert_select 'group' do
122 assert_select 'group' do
123 assert_select 'memberships'
123 assert_select 'memberships'
124 end
124 end
125 end
125 end
126
126
127 test "POST /groups.xml with valid parameters should create the group" do
127 test "POST /groups.xml with valid parameters should create the group" do
128 assert_difference('Group.count') do
128 assert_difference('Group.count') do
129 post '/groups.xml', {:group => {:name => 'Test', :user_ids => [2, 3]}}, credentials('admin')
129 post '/groups.xml', {:group => {:name => 'Test', :user_ids => [2, 3]}}, credentials('admin')
130 assert_response :created
130 assert_response :created
131 assert_equal 'application/xml', response.content_type
131 assert_equal 'application/xml', response.content_type
132 end
132 end
133
133
134 group = Group.order('id DESC').first
134 group = Group.order('id DESC').first
135 assert_equal 'Test', group.name
135 assert_equal 'Test', group.name
136 assert_equal [2, 3], group.users.map(&:id).sort
136 assert_equal [2, 3], group.users.map(&:id).sort
137
137
138 assert_select 'group' do
138 assert_select 'group' do
139 assert_select 'name', :text => 'Test'
139 assert_select 'name', :text => 'Test'
140 end
140 end
141 end
141 end
142
142
143 test "POST /groups.xml with invalid parameters should return errors" do
143 test "POST /groups.xml with invalid parameters should return errors" do
144 assert_no_difference('Group.count') do
144 assert_no_difference('Group.count') do
145 post '/groups.xml', {:group => {:name => ''}}, credentials('admin')
145 post '/groups.xml', {:group => {:name => ''}}, credentials('admin')
146 end
146 end
147 assert_response :unprocessable_entity
147 assert_response :unprocessable_entity
148 assert_equal 'application/xml', response.content_type
148 assert_equal 'application/xml', response.content_type
149
149
150 assert_select 'errors' do
150 assert_select 'errors' do
151 assert_select 'error', :text => /Name can't be blank/
151 assert_select 'error', :text => /Name can't be blank/
152 end
152 end
153 end
153 end
154
154
155 test "PUT /groups/:id.xml with valid parameters should update the group" do
155 test "PUT /groups/:id.xml with valid parameters should update the group" do
156 put '/groups/10.xml', {:group => {:name => 'New name', :user_ids => [2, 3]}}, credentials('admin')
156 put '/groups/10.xml', {:group => {:name => 'New name', :user_ids => [2, 3]}}, credentials('admin')
157 assert_response :ok
157 assert_response :ok
158 assert_equal '', @response.body
158 assert_equal '', @response.body
159
159
160 group = Group.find(10)
160 group = Group.find(10)
161 assert_equal 'New name', group.name
161 assert_equal 'New name', group.name
162 assert_equal [2, 3], group.users.map(&:id).sort
162 assert_equal [2, 3], group.users.map(&:id).sort
163 end
163 end
164
164
165 test "PUT /groups/:id.xml with invalid parameters should return errors" do
165 test "PUT /groups/:id.xml with invalid parameters should return errors" do
166 put '/groups/10.xml', {:group => {:name => ''}}, credentials('admin')
166 put '/groups/10.xml', {:group => {:name => ''}}, credentials('admin')
167 assert_response :unprocessable_entity
167 assert_response :unprocessable_entity
168 assert_equal 'application/xml', response.content_type
168 assert_equal 'application/xml', response.content_type
169
169
170 assert_select 'errors' do
170 assert_select 'errors' do
171 assert_select 'error', :text => /Name can't be blank/
171 assert_select 'error', :text => /Name can't be blank/
172 end
172 end
173 end
173 end
174
174
175 test "DELETE /groups/:id.xml should delete the group" do
175 test "DELETE /groups/:id.xml should delete the group" do
176 assert_difference 'Group.count', -1 do
176 assert_difference 'Group.count', -1 do
177 delete '/groups/10.xml', {}, credentials('admin')
177 delete '/groups/10.xml', {}, credentials('admin')
178 assert_response :ok
178 assert_response :ok
179 assert_equal '', @response.body
179 assert_equal '', @response.body
180 end
180 end
181 end
181 end
182
182
183 test "POST /groups/:id/users.xml should add user to the group" do
183 test "POST /groups/:id/users.xml should add user to the group" do
184 assert_difference 'Group.find(10).users.count' do
184 assert_difference 'Group.find(10).users.count' do
185 post '/groups/10/users.xml', {:user_id => 5}, credentials('admin')
185 post '/groups/10/users.xml', {:user_id => 5}, credentials('admin')
186 assert_response :ok
186 assert_response :ok
187 assert_equal '', @response.body
187 assert_equal '', @response.body
188 end
188 end
189 assert_include User.find(5), Group.find(10).users
189 assert_include User.find(5), Group.find(10).users
190 end
190 end
191
191
192 test "POST /groups/:id/users.xml should not add the user if already added" do
193 Group.find(10).users << User.find(5)
194
195 assert_no_difference 'Group.find(10).users.count' do
196 post '/groups/10/users.xml', {:user_id => 5}, credentials('admin')
197 assert_response :unprocessable_entity
198 end
199
200 assert_select 'errors' do
201 assert_select 'error', :text => /User is invalid/
202 end
203 end
204
192 test "DELETE /groups/:id/users/:user_id.xml should remove user from the group" do
205 test "DELETE /groups/:id/users/:user_id.xml should remove user from the group" do
193 assert_difference 'Group.find(10).users.count', -1 do
206 assert_difference 'Group.find(10).users.count', -1 do
194 delete '/groups/10/users/8.xml', {}, credentials('admin')
207 delete '/groups/10/users/8.xml', {}, credentials('admin')
195 assert_response :ok
208 assert_response :ok
196 assert_equal '', @response.body
209 assert_equal '', @response.body
197 end
210 end
198 assert_not_include User.find(8), Group.find(10).users
211 assert_not_include User.find(8), Group.find(10).users
199 end
212 end
200 end
213 end
General Comments 0
You need to be logged in to leave comments. Login now