##// END OF EJS Templates
Don't redirect to lost password page after login (#13741)....
Jean-Philippe Lang -
r15769:6a1865905f38
parent child
Show More
@@ -1,677 +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, :set_localization, :check_password_change
54 before_action :session_expiration, :user_setup, :check_if_login_required, :set_localization, :check_password_change
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|account/lost_password)})
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 :status => status
657 head :status => status
658 end
658 end
659
659
660 # Renders API response on validation failure
660 # Renders API response on validation failure
661 # for an object or an array of objects
661 # for an object or an array of objects
662 def render_validation_errors(objects)
662 def render_validation_errors(objects)
663 messages = Array.wrap(objects).map {|object| object.errors.full_messages}.flatten
663 messages = Array.wrap(objects).map {|object| object.errors.full_messages}.flatten
664 render_api_errors(messages)
664 render_api_errors(messages)
665 end
665 end
666
666
667 def render_api_errors(*messages)
667 def render_api_errors(*messages)
668 @error_messages = messages.flatten
668 @error_messages = messages.flatten
669 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
669 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
670 end
670 end
671
671
672 # Overrides #_include_layout? so that #render with no arguments
672 # Overrides #_include_layout? so that #render with no arguments
673 # doesn't use the layout for api requests
673 # doesn't use the layout for api requests
674 def _include_layout?(*args)
674 def _include_layout?(*args)
675 api_request? ? false : super
675 api_request? ? false : super
676 end
676 end
677 end
677 end
General Comments 0
You need to be logged in to leave comments. Login now