comparison app/controllers/.svn/text-base/application_controller.rb.svn-base @ 0:513646585e45

* Import Redmine trunk SVN rev 3859
author Chris Cannam
date Fri, 23 Jul 2010 15:52:44 +0100
parents
children 1d32c0a0efbf
comparison
equal deleted inserted replaced
-1:000000000000 0:513646585e45
1 # redMine - project management software
2 # Copyright (C) 2006-2007 Jean-Philippe Lang
3 #
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
18 require 'uri'
19 require 'cgi'
20
21 class ApplicationController < ActionController::Base
22 include Redmine::I18n
23
24 layout 'base'
25 exempt_from_layout 'builder'
26
27 # Remove broken cookie after upgrade from 0.8.x (#4292)
28 # See https://rails.lighthouseapp.com/projects/8994/tickets/3360
29 # TODO: remove it when Rails is fixed
30 before_filter :delete_broken_cookies
31 def delete_broken_cookies
32 if cookies['_redmine_session'] && cookies['_redmine_session'] !~ /--/
33 cookies.delete '_redmine_session'
34 redirect_to home_path
35 return false
36 end
37 end
38
39 before_filter :user_setup, :check_if_login_required, :set_localization
40 filter_parameter_logging :password
41 protect_from_forgery
42
43 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
44
45 include Redmine::Search::Controller
46 include Redmine::MenuManager::MenuController
47 helper Redmine::MenuManager::MenuHelper
48
49 Redmine::Scm::Base.all.each do |scm|
50 require_dependency "repository/#{scm.underscore}"
51 end
52
53 def user_setup
54 # Check the settings cache for each request
55 Setting.check_cache
56 # Find the current user
57 User.current = find_current_user
58 end
59
60 # Returns the current user or nil if no user is logged in
61 # and starts a session if needed
62 def find_current_user
63 if session[:user_id]
64 # existing session
65 (User.active.find(session[:user_id]) rescue nil)
66 elsif cookies[:autologin] && Setting.autologin?
67 # auto-login feature starts a new session
68 user = User.try_to_autologin(cookies[:autologin])
69 session[:user_id] = user.id if user
70 user
71 elsif params[:format] == 'atom' && params[:key] && accept_key_auth_actions.include?(params[:action])
72 # RSS key authentication does not start a session
73 User.find_by_rss_key(params[:key])
74 elsif Setting.rest_api_enabled? && ['xml', 'json'].include?(params[:format])
75 if params[:key].present? && accept_key_auth_actions.include?(params[:action])
76 # Use API key
77 User.find_by_api_key(params[:key])
78 else
79 # HTTP Basic, either username/password or API key/random
80 authenticate_with_http_basic do |username, password|
81 User.try_to_login(username, password) || User.find_by_api_key(username)
82 end
83 end
84 end
85 end
86
87 # Sets the logged in user
88 def logged_user=(user)
89 reset_session
90 if user && user.is_a?(User)
91 User.current = user
92 session[:user_id] = user.id
93 else
94 User.current = User.anonymous
95 end
96 end
97
98 # check if login is globally required to access the application
99 def check_if_login_required
100 # no check needed if user is already logged in
101 return true if User.current.logged?
102 require_login if Setting.login_required?
103 end
104
105 def set_localization
106 lang = nil
107 if User.current.logged?
108 lang = find_language(User.current.language)
109 end
110 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
111 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
112 if !accept_lang.blank?
113 accept_lang = accept_lang.downcase
114 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
115 end
116 end
117 lang ||= Setting.default_language
118 set_language_if_valid(lang)
119 end
120
121 def require_login
122 if !User.current.logged?
123 # Extract only the basic url parameters on non-GET requests
124 if request.get?
125 url = url_for(params)
126 else
127 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
128 end
129 respond_to do |format|
130 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
131 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
132 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
133 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
134 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
135 end
136 return false
137 end
138 true
139 end
140
141 def require_admin
142 return unless require_login
143 if !User.current.admin?
144 render_403
145 return false
146 end
147 true
148 end
149
150 def deny_access
151 User.current.logged? ? render_403 : require_login
152 end
153
154 # Authorize the user for the requested action
155 def authorize(ctrl = params[:controller], action = params[:action], global = false)
156 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project, :global => global)
157 allowed ? true : deny_access
158 end
159
160 # Authorize the user for the requested action outside a project
161 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
162 authorize(ctrl, action, global)
163 end
164
165 # Find project of id params[:id]
166 def find_project
167 @project = Project.find(params[:id])
168 rescue ActiveRecord::RecordNotFound
169 render_404
170 end
171
172 # Find a project based on params[:project_id]
173 # TODO: some subclasses override this, see about merging their logic
174 def find_optional_project
175 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
176 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
177 allowed ? true : deny_access
178 rescue ActiveRecord::RecordNotFound
179 render_404
180 end
181
182 # Finds and sets @project based on @object.project
183 def find_project_from_association
184 render_404 unless @object.present?
185
186 @project = @object.project
187 rescue ActiveRecord::RecordNotFound
188 render_404
189 end
190
191 def find_model_object
192 model = self.class.read_inheritable_attribute('model_object')
193 if model
194 @object = model.find(params[:id])
195 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
196 end
197 rescue ActiveRecord::RecordNotFound
198 render_404
199 end
200
201 def self.model_object(model)
202 write_inheritable_attribute('model_object', model)
203 end
204
205 # make sure that the user is a member of the project (or admin) if project is private
206 # used as a before_filter for actions that do not require any particular permission on the project
207 def check_project_privacy
208 if @project && @project.active?
209 if @project.is_public? || User.current.member_of?(@project) || User.current.admin?
210 true
211 else
212 User.current.logged? ? render_403 : require_login
213 end
214 else
215 @project = nil
216 render_404
217 false
218 end
219 end
220
221 def redirect_back_or_default(default)
222 back_url = CGI.unescape(params[:back_url].to_s)
223 if !back_url.blank?
224 begin
225 uri = URI.parse(back_url)
226 # do not redirect user to another host or to the login or register page
227 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
228 redirect_to(back_url)
229 return
230 end
231 rescue URI::InvalidURIError
232 # redirect to default
233 end
234 end
235 redirect_to default
236 end
237
238 def render_403
239 @project = nil
240 respond_to do |format|
241 format.html { render :template => "common/403", :layout => (request.xhr? ? false : 'base'), :status => 403 }
242 format.atom { head 403 }
243 format.xml { head 403 }
244 format.js { head 403 }
245 format.json { head 403 }
246 end
247 return false
248 end
249
250 def render_404
251 respond_to do |format|
252 format.html { render :template => "common/404", :layout => !request.xhr?, :status => 404 }
253 format.atom { head 404 }
254 format.xml { head 404 }
255 format.js { head 404 }
256 format.json { head 404 }
257 end
258 return false
259 end
260
261 def render_error(msg)
262 respond_to do |format|
263 format.html {
264 flash.now[:error] = msg
265 render :text => '', :layout => !request.xhr?, :status => 500
266 }
267 format.atom { head 500 }
268 format.xml { head 500 }
269 format.js { head 500 }
270 format.json { head 500 }
271 end
272 end
273
274 def invalid_authenticity_token
275 if api_request?
276 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
277 end
278 render_error "Invalid form authenticity token."
279 end
280
281 def render_feed(items, options={})
282 @items = items || []
283 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
284 @items = @items.slice(0, Setting.feeds_limit.to_i)
285 @title = options[:title] || Setting.app_title
286 render :template => "common/feed.atom.rxml", :layout => false, :content_type => 'application/atom+xml'
287 end
288
289 def self.accept_key_auth(*actions)
290 actions = actions.flatten.map(&:to_s)
291 write_inheritable_attribute('accept_key_auth_actions', actions)
292 end
293
294 def accept_key_auth_actions
295 self.class.read_inheritable_attribute('accept_key_auth_actions') || []
296 end
297
298 # Returns the number of objects that should be displayed
299 # on the paginated list
300 def per_page_option
301 per_page = nil
302 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
303 per_page = params[:per_page].to_s.to_i
304 session[:per_page] = per_page
305 elsif session[:per_page]
306 per_page = session[:per_page]
307 else
308 per_page = Setting.per_page_options_array.first || 25
309 end
310 per_page
311 end
312
313 # qvalues http header parser
314 # code taken from webrick
315 def parse_qvalues(value)
316 tmp = []
317 if value
318 parts = value.split(/,\s*/)
319 parts.each {|part|
320 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
321 val = m[1]
322 q = (m[2] or 1).to_f
323 tmp.push([val, q])
324 end
325 }
326 tmp = tmp.sort_by{|val, q| -q}
327 tmp.collect!{|val, q| val}
328 end
329 return tmp
330 rescue
331 nil
332 end
333
334 # Returns a string that can be used as filename value in Content-Disposition header
335 def filename_for_content_disposition(name)
336 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
337 end
338
339 def api_request?
340 %w(xml json).include? params[:format]
341 end
342
343 # Renders a warning flash if obj has unsaved attachments
344 def render_attachment_warning_if_needed(obj)
345 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
346 end
347
348 # Rescues an invalid query statement. Just in case...
349 def query_statement_invalid(exception)
350 logger.error "Query::StatementInvalid: #{exception.message}" if logger
351 session.delete(:query)
352 sort_clear if respond_to?(:sort_clear)
353 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
354 end
355
356 # Converts the errors on an ActiveRecord object into a common JSON format
357 def object_errors_to_json(object)
358 object.errors.collect do |attribute, error|
359 { attribute => error }
360 end.to_json
361 end
362
363 end