##// END OF EJS Templates
Merged r11519 and r11520 from trunk (#13335)....
Jean-Philippe Lang -
r11339:4413e0e52e2c
parent child
Show More
@@ -1,305 +1,304
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2013 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class AccountController < ApplicationController
19 19 helper :custom_fields
20 20 include CustomFieldsHelper
21 21
22 22 # prevents login action to be filtered by check_if_login_required application scope filter
23 23 skip_before_filter :check_if_login_required
24 24
25 25 # Login request and validation
26 26 def login
27 27 if request.get?
28 28 if User.current.logged?
29 29 redirect_to home_url
30 30 end
31 31 else
32 32 authenticate_user
33 33 end
34 34 rescue AuthSourceException => e
35 35 logger.error "An error occured when authenticating #{params[:username]}: #{e.message}"
36 36 render_error :message => e.message
37 37 end
38 38
39 39 # Log out current user and redirect to welcome page
40 40 def logout
41 41 if User.current.anonymous?
42 42 redirect_to home_url
43 43 elsif request.post?
44 44 logout_user
45 45 redirect_to home_url
46 46 end
47 47 # display the logout form
48 48 end
49 49
50 50 # Lets user choose a new password
51 51 def lost_password
52 52 (redirect_to(home_url); return) unless Setting.lost_password?
53 53 if params[:token]
54 54 @token = Token.find_token("recovery", params[:token].to_s)
55 55 if @token.nil? || @token.expired?
56 56 redirect_to home_url
57 57 return
58 58 end
59 59 @user = @token.user
60 60 unless @user && @user.active?
61 61 redirect_to home_url
62 62 return
63 63 end
64 64 if request.post?
65 65 @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]
66 66 if @user.save
67 67 @token.destroy
68 68 flash[:notice] = l(:notice_account_password_updated)
69 69 redirect_to signin_path
70 70 return
71 71 end
72 72 end
73 73 render :template => "account/password_recovery"
74 74 return
75 75 else
76 76 if request.post?
77 77 user = User.find_by_mail(params[:mail].to_s)
78 78 # user not found or not active
79 79 unless user && user.active?
80 80 flash.now[:error] = l(:notice_account_unknown_email)
81 81 return
82 82 end
83 83 # user cannot change its password
84 84 unless user.change_password_allowed?
85 85 flash.now[:error] = l(:notice_can_t_change_password)
86 86 return
87 87 end
88 88 # create a new token for password recovery
89 89 token = Token.new(:user => user, :action => "recovery")
90 90 if token.save
91 91 Mailer.lost_password(token).deliver
92 92 flash[:notice] = l(:notice_account_lost_email_sent)
93 93 redirect_to signin_path
94 94 return
95 95 end
96 96 end
97 97 end
98 98 end
99 99
100 100 # User self-registration
101 101 def register
102 102 (redirect_to(home_url); return) unless Setting.self_registration? || session[:auth_source_registration]
103 103 if request.get?
104 104 session[:auth_source_registration] = nil
105 105 @user = User.new(:language => current_language.to_s)
106 106 else
107 107 user_params = params[:user] || {}
108 108 @user = User.new
109 109 @user.safe_attributes = user_params
110 110 @user.admin = false
111 111 @user.register
112 112 if session[:auth_source_registration]
113 113 @user.activate
114 114 @user.login = session[:auth_source_registration][:login]
115 115 @user.auth_source_id = session[:auth_source_registration][:auth_source_id]
116 116 if @user.save
117 117 session[:auth_source_registration] = nil
118 118 self.logged_user = @user
119 119 flash[:notice] = l(:notice_account_activated)
120 120 redirect_to my_account_path
121 121 end
122 122 else
123 123 @user.login = params[:user][:login]
124 124 unless user_params[:identity_url].present? && user_params[:password].blank? && user_params[:password_confirmation].blank?
125 125 @user.password, @user.password_confirmation = user_params[:password], user_params[:password_confirmation]
126 126 end
127 127
128 128 case Setting.self_registration
129 129 when '1'
130 130 register_by_email_activation(@user)
131 131 when '3'
132 132 register_automatically(@user)
133 133 else
134 134 register_manually_by_administrator(@user)
135 135 end
136 136 end
137 137 end
138 138 end
139 139
140 140 # Token based account activation
141 141 def activate
142 142 (redirect_to(home_url); return) unless Setting.self_registration? && params[:token].present?
143 143 token = Token.find_token('register', params[:token].to_s)
144 144 (redirect_to(home_url); return) unless token and !token.expired?
145 145 user = token.user
146 146 (redirect_to(home_url); return) unless user.registered?
147 147 user.activate
148 148 if user.save
149 149 token.destroy
150 150 flash[:notice] = l(:notice_account_activated)
151 151 end
152 152 redirect_to signin_path
153 153 end
154 154
155 155 private
156 156
157 157 def authenticate_user
158 158 if Setting.openid? && using_open_id?
159 159 open_id_authenticate(params[:openid_url])
160 160 else
161 161 password_authentication
162 162 end
163 163 end
164 164
165 165 def password_authentication
166 166 user = User.try_to_login(params[:username], params[:password])
167 167
168 168 if user.nil?
169 169 invalid_credentials
170 170 elsif user.new_record?
171 171 onthefly_creation_failed(user, {:login => user.login, :auth_source_id => user.auth_source_id })
172 172 else
173 173 # Valid user
174 174 successful_authentication(user)
175 175 end
176 176 end
177 177
178 178 def open_id_authenticate(openid_url)
179 179 back_url = signin_url(:autologin => params[:autologin])
180 180
181 181 authenticate_with_open_id(openid_url, :required => [:nickname, :fullname, :email], :return_to => back_url, :method => :post) do |result, identity_url, registration|
182 182 if result.successful?
183 183 user = User.find_or_initialize_by_identity_url(identity_url)
184 184 if user.new_record?
185 185 # Self-registration off
186 186 (redirect_to(home_url); return) unless Setting.self_registration?
187 187
188 188 # Create on the fly
189 189 user.login = registration['nickname'] unless registration['nickname'].nil?
190 190 user.mail = registration['email'] unless registration['email'].nil?
191 191 user.firstname, user.lastname = registration['fullname'].split(' ') unless registration['fullname'].nil?
192 192 user.random_password
193 193 user.register
194 194
195 195 case Setting.self_registration
196 196 when '1'
197 197 register_by_email_activation(user) do
198 198 onthefly_creation_failed(user)
199 199 end
200 200 when '3'
201 201 register_automatically(user) do
202 202 onthefly_creation_failed(user)
203 203 end
204 204 else
205 205 register_manually_by_administrator(user) do
206 206 onthefly_creation_failed(user)
207 207 end
208 208 end
209 209 else
210 210 # Existing record
211 211 if user.active?
212 212 successful_authentication(user)
213 213 else
214 214 account_pending
215 215 end
216 216 end
217 217 end
218 218 end
219 219 end
220 220
221 221 def successful_authentication(user)
222 222 logger.info "Successful authentication for '#{user.login}' from #{request.remote_ip} at #{Time.now.utc}"
223 223 # Valid user
224 224 self.logged_user = user
225 225 # generate a key and set cookie if autologin
226 226 if params[:autologin] && Setting.autologin?
227 227 set_autologin_cookie(user)
228 228 end
229 229 call_hook(:controller_account_success_authentication_after, {:user => user })
230 230 redirect_back_or_default my_page_path
231 231 end
232 232
233 233 def set_autologin_cookie(user)
234 234 token = Token.create(:user => user, :action => 'autologin')
235 cookie_name = Redmine::Configuration['autologin_cookie_name'] || 'autologin'
236 235 cookie_options = {
237 236 :value => token.value,
238 237 :expires => 1.year.from_now,
239 238 :path => (Redmine::Configuration['autologin_cookie_path'] || '/'),
240 239 :secure => (Redmine::Configuration['autologin_cookie_secure'] ? true : false),
241 240 :httponly => true
242 241 }
243 cookies[cookie_name] = cookie_options
242 cookies[autologin_cookie_name] = cookie_options
244 243 end
245 244
246 245 # Onthefly creation failed, display the registration form to fill/fix attributes
247 246 def onthefly_creation_failed(user, auth_source_options = { })
248 247 @user = user
249 248 session[:auth_source_registration] = auth_source_options unless auth_source_options.empty?
250 249 render :action => 'register'
251 250 end
252 251
253 252 def invalid_credentials
254 253 logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}"
255 254 flash.now[:error] = l(:notice_account_invalid_creditentials)
256 255 end
257 256
258 257 # Register a user for email activation.
259 258 #
260 259 # Pass a block for behavior when a user fails to save
261 260 def register_by_email_activation(user, &block)
262 261 token = Token.new(:user => user, :action => "register")
263 262 if user.save and token.save
264 263 Mailer.register(token).deliver
265 264 flash[:notice] = l(:notice_account_register_done)
266 265 redirect_to signin_path
267 266 else
268 267 yield if block_given?
269 268 end
270 269 end
271 270
272 271 # Automatically register a user
273 272 #
274 273 # Pass a block for behavior when a user fails to save
275 274 def register_automatically(user, &block)
276 275 # Automatic activation
277 276 user.activate
278 277 user.last_login_on = Time.now
279 278 if user.save
280 279 self.logged_user = user
281 280 flash[:notice] = l(:notice_account_activated)
282 281 redirect_to my_account_path
283 282 else
284 283 yield if block_given?
285 284 end
286 285 end
287 286
288 287 # Manual activation by the administrator
289 288 #
290 289 # Pass a block for behavior when a user fails to save
291 290 def register_manually_by_administrator(user, &block)
292 291 if user.save
293 292 # Sends an email to the administrators
294 293 Mailer.account_activation_request(user).deliver
295 294 account_pending
296 295 else
297 296 yield if block_given?
298 297 end
299 298 end
300 299
301 300 def account_pending
302 301 flash[:notice] = l(:notice_account_pending)
303 302 redirect_to signin_path
304 303 end
305 304 end
@@ -1,603 +1,607
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2013 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 require 'uri'
19 19 require 'cgi'
20 20
21 21 class Unauthorized < Exception; end
22 22
23 23 class ApplicationController < ActionController::Base
24 24 include Redmine::I18n
25 25 include Redmine::Pagination
26 26 include RoutesHelper
27 27 helper :routes
28 28
29 29 class_attribute :accept_api_auth_actions
30 30 class_attribute :accept_rss_auth_actions
31 31 class_attribute :model_object
32 32
33 33 layout 'base'
34 34
35 35 protect_from_forgery
36 36 def handle_unverified_request
37 37 super
38 cookies.delete(:autologin)
38 cookies.delete(autologin_cookie_name)
39 39 end
40 40
41 41 before_filter :session_expiration, :user_setup, :check_if_login_required, :set_localization
42 42
43 43 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
44 44 rescue_from ::Unauthorized, :with => :deny_access
45 45 rescue_from ::ActionView::MissingTemplate, :with => :missing_template
46 46
47 47 include Redmine::Search::Controller
48 48 include Redmine::MenuManager::MenuController
49 49 helper Redmine::MenuManager::MenuHelper
50 50
51 51 def session_expiration
52 52 if session[:user_id]
53 53 if session_expired? && !try_to_autologin
54 54 reset_session
55 55 flash[:error] = l(:error_session_expired)
56 56 redirect_to signin_url
57 57 else
58 58 session[:atime] = Time.now.utc.to_i
59 59 end
60 60 end
61 61 end
62 62
63 63 def session_expired?
64 64 if Setting.session_lifetime?
65 65 unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
66 66 return true
67 67 end
68 68 end
69 69 if Setting.session_timeout?
70 70 unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
71 71 return true
72 72 end
73 73 end
74 74 false
75 75 end
76 76
77 77 def start_user_session(user)
78 78 session[:user_id] = user.id
79 79 session[:ctime] = Time.now.utc.to_i
80 80 session[:atime] = Time.now.utc.to_i
81 81 end
82 82
83 83 def user_setup
84 84 # Check the settings cache for each request
85 85 Setting.check_cache
86 86 # Find the current user
87 87 User.current = find_current_user
88 88 logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
89 89 end
90 90
91 91 # Returns the current user or nil if no user is logged in
92 92 # and starts a session if needed
93 93 def find_current_user
94 94 user = nil
95 95 unless api_request?
96 96 if session[:user_id]
97 97 # existing session
98 98 user = (User.active.find(session[:user_id]) rescue nil)
99 99 elsif autologin_user = try_to_autologin
100 100 user = autologin_user
101 101 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
102 102 # RSS key authentication does not start a session
103 103 user = User.find_by_rss_key(params[:key])
104 104 end
105 105 end
106 106 if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
107 107 if (key = api_key_from_request)
108 108 # Use API key
109 109 user = User.find_by_api_key(key)
110 110 else
111 111 # HTTP Basic, either username/password or API key/random
112 112 authenticate_with_http_basic do |username, password|
113 113 user = User.try_to_login(username, password) || User.find_by_api_key(username)
114 114 end
115 115 end
116 116 # Switch user if requested by an admin user
117 117 if user && user.admin? && (username = api_switch_user_from_request)
118 118 su = User.find_by_login(username)
119 119 if su && su.active?
120 120 logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
121 121 user = su
122 122 else
123 123 render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
124 124 end
125 125 end
126 126 end
127 127 user
128 128 end
129 129
130 def autologin_cookie_name
131 Redmine::Configuration['autologin_cookie_name'].presence || 'autologin'
132 end
133
130 134 def try_to_autologin
131 if cookies[:autologin] && Setting.autologin?
135 if cookies[autologin_cookie_name] && Setting.autologin?
132 136 # auto-login feature starts a new session
133 user = User.try_to_autologin(cookies[:autologin])
137 user = User.try_to_autologin(cookies[autologin_cookie_name])
134 138 if user
135 139 reset_session
136 140 start_user_session(user)
137 141 end
138 142 user
139 143 end
140 144 end
141 145
142 146 # Sets the logged in user
143 147 def logged_user=(user)
144 148 reset_session
145 149 if user && user.is_a?(User)
146 150 User.current = user
147 151 start_user_session(user)
148 152 else
149 153 User.current = User.anonymous
150 154 end
151 155 end
152 156
153 157 # Logs out current user
154 158 def logout_user
155 159 if User.current.logged?
156 cookies.delete :autologin
160 cookies.delete(autologin_cookie_name)
157 161 Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
158 162 self.logged_user = nil
159 163 end
160 164 end
161 165
162 166 # check if login is globally required to access the application
163 167 def check_if_login_required
164 168 # no check needed if user is already logged in
165 169 return true if User.current.logged?
166 170 require_login if Setting.login_required?
167 171 end
168 172
169 173 def set_localization
170 174 lang = nil
171 175 if User.current.logged?
172 176 lang = find_language(User.current.language)
173 177 end
174 178 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
175 179 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
176 180 if !accept_lang.blank?
177 181 accept_lang = accept_lang.downcase
178 182 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
179 183 end
180 184 end
181 185 lang ||= Setting.default_language
182 186 set_language_if_valid(lang)
183 187 end
184 188
185 189 def require_login
186 190 if !User.current.logged?
187 191 # Extract only the basic url parameters on non-GET requests
188 192 if request.get?
189 193 url = url_for(params)
190 194 else
191 195 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
192 196 end
193 197 respond_to do |format|
194 198 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
195 199 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
196 200 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
197 201 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
198 202 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
199 203 end
200 204 return false
201 205 end
202 206 true
203 207 end
204 208
205 209 def require_admin
206 210 return unless require_login
207 211 if !User.current.admin?
208 212 render_403
209 213 return false
210 214 end
211 215 true
212 216 end
213 217
214 218 def deny_access
215 219 User.current.logged? ? render_403 : require_login
216 220 end
217 221
218 222 # Authorize the user for the requested action
219 223 def authorize(ctrl = params[:controller], action = params[:action], global = false)
220 224 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
221 225 if allowed
222 226 true
223 227 else
224 228 if @project && @project.archived?
225 229 render_403 :message => :notice_not_authorized_archived_project
226 230 else
227 231 deny_access
228 232 end
229 233 end
230 234 end
231 235
232 236 # Authorize the user for the requested action outside a project
233 237 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
234 238 authorize(ctrl, action, global)
235 239 end
236 240
237 241 # Find project of id params[:id]
238 242 def find_project
239 243 @project = Project.find(params[:id])
240 244 rescue ActiveRecord::RecordNotFound
241 245 render_404
242 246 end
243 247
244 248 # Find project of id params[:project_id]
245 249 def find_project_by_project_id
246 250 @project = Project.find(params[:project_id])
247 251 rescue ActiveRecord::RecordNotFound
248 252 render_404
249 253 end
250 254
251 255 # Find a project based on params[:project_id]
252 256 # TODO: some subclasses override this, see about merging their logic
253 257 def find_optional_project
254 258 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
255 259 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
256 260 allowed ? true : deny_access
257 261 rescue ActiveRecord::RecordNotFound
258 262 render_404
259 263 end
260 264
261 265 # Finds and sets @project based on @object.project
262 266 def find_project_from_association
263 267 render_404 unless @object.present?
264 268
265 269 @project = @object.project
266 270 end
267 271
268 272 def find_model_object
269 273 model = self.class.model_object
270 274 if model
271 275 @object = model.find(params[:id])
272 276 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
273 277 end
274 278 rescue ActiveRecord::RecordNotFound
275 279 render_404
276 280 end
277 281
278 282 def self.model_object(model)
279 283 self.model_object = model
280 284 end
281 285
282 286 # Find the issue whose id is the :id parameter
283 287 # Raises a Unauthorized exception if the issue is not visible
284 288 def find_issue
285 289 # Issue.visible.find(...) can not be used to redirect user to the login form
286 290 # if the issue actually exists but requires authentication
287 291 @issue = Issue.find(params[:id])
288 292 raise Unauthorized unless @issue.visible?
289 293 @project = @issue.project
290 294 rescue ActiveRecord::RecordNotFound
291 295 render_404
292 296 end
293 297
294 298 # Find issues with a single :id param or :ids array param
295 299 # Raises a Unauthorized exception if one of the issues is not visible
296 300 def find_issues
297 301 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
298 302 raise ActiveRecord::RecordNotFound if @issues.empty?
299 303 raise Unauthorized unless @issues.all?(&:visible?)
300 304 @projects = @issues.collect(&:project).compact.uniq
301 305 @project = @projects.first if @projects.size == 1
302 306 rescue ActiveRecord::RecordNotFound
303 307 render_404
304 308 end
305 309
306 310 def find_attachments
307 311 if (attachments = params[:attachments]).present?
308 312 att = attachments.values.collect do |attachment|
309 313 Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
310 314 end
311 315 att.compact!
312 316 end
313 317 @attachments = att || []
314 318 end
315 319
316 320 # make sure that the user is a member of the project (or admin) if project is private
317 321 # used as a before_filter for actions that do not require any particular permission on the project
318 322 def check_project_privacy
319 323 if @project && !@project.archived?
320 324 if @project.visible?
321 325 true
322 326 else
323 327 deny_access
324 328 end
325 329 else
326 330 @project = nil
327 331 render_404
328 332 false
329 333 end
330 334 end
331 335
332 336 def back_url
333 337 url = params[:back_url]
334 338 if url.nil? && referer = request.env['HTTP_REFERER']
335 339 url = CGI.unescape(referer.to_s)
336 340 end
337 341 url
338 342 end
339 343
340 344 def redirect_back_or_default(default)
341 345 back_url = params[:back_url].to_s
342 346 if back_url.present?
343 347 begin
344 348 uri = URI.parse(back_url)
345 349 # do not redirect user to another host or to the login or register page
346 350 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
347 351 redirect_to(back_url)
348 352 return
349 353 end
350 354 rescue URI::InvalidURIError
351 355 logger.warn("Could not redirect to invalid URL #{back_url}")
352 356 # redirect to default
353 357 end
354 358 end
355 359 redirect_to default
356 360 false
357 361 end
358 362
359 363 # Redirects to the request referer if present, redirects to args or call block otherwise.
360 364 def redirect_to_referer_or(*args, &block)
361 365 redirect_to :back
362 366 rescue ::ActionController::RedirectBackError
363 367 if args.any?
364 368 redirect_to *args
365 369 elsif block_given?
366 370 block.call
367 371 else
368 372 raise "#redirect_to_referer_or takes arguments or a block"
369 373 end
370 374 end
371 375
372 376 def render_403(options={})
373 377 @project = nil
374 378 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
375 379 return false
376 380 end
377 381
378 382 def render_404(options={})
379 383 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
380 384 return false
381 385 end
382 386
383 387 # Renders an error response
384 388 def render_error(arg)
385 389 arg = {:message => arg} unless arg.is_a?(Hash)
386 390
387 391 @message = arg[:message]
388 392 @message = l(@message) if @message.is_a?(Symbol)
389 393 @status = arg[:status] || 500
390 394
391 395 respond_to do |format|
392 396 format.html {
393 397 render :template => 'common/error', :layout => use_layout, :status => @status
394 398 }
395 399 format.any { head @status }
396 400 end
397 401 end
398 402
399 403 # Handler for ActionView::MissingTemplate exception
400 404 def missing_template
401 405 logger.warn "Missing template, responding with 404"
402 406 @project = nil
403 407 render_404
404 408 end
405 409
406 410 # Filter for actions that provide an API response
407 411 # but have no HTML representation for non admin users
408 412 def require_admin_or_api_request
409 413 return true if api_request?
410 414 if User.current.admin?
411 415 true
412 416 elsif User.current.logged?
413 417 render_error(:status => 406)
414 418 else
415 419 deny_access
416 420 end
417 421 end
418 422
419 423 # Picks which layout to use based on the request
420 424 #
421 425 # @return [boolean, string] name of the layout to use or false for no layout
422 426 def use_layout
423 427 request.xhr? ? false : 'base'
424 428 end
425 429
426 430 def invalid_authenticity_token
427 431 if api_request?
428 432 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
429 433 end
430 434 render_error "Invalid form authenticity token."
431 435 end
432 436
433 437 def render_feed(items, options={})
434 438 @items = items || []
435 439 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
436 440 @items = @items.slice(0, Setting.feeds_limit.to_i)
437 441 @title = options[:title] || Setting.app_title
438 442 render :template => "common/feed", :formats => [:atom], :layout => false,
439 443 :content_type => 'application/atom+xml'
440 444 end
441 445
442 446 def self.accept_rss_auth(*actions)
443 447 if actions.any?
444 448 self.accept_rss_auth_actions = actions
445 449 else
446 450 self.accept_rss_auth_actions || []
447 451 end
448 452 end
449 453
450 454 def accept_rss_auth?(action=action_name)
451 455 self.class.accept_rss_auth.include?(action.to_sym)
452 456 end
453 457
454 458 def self.accept_api_auth(*actions)
455 459 if actions.any?
456 460 self.accept_api_auth_actions = actions
457 461 else
458 462 self.accept_api_auth_actions || []
459 463 end
460 464 end
461 465
462 466 def accept_api_auth?(action=action_name)
463 467 self.class.accept_api_auth.include?(action.to_sym)
464 468 end
465 469
466 470 # Returns the number of objects that should be displayed
467 471 # on the paginated list
468 472 def per_page_option
469 473 per_page = nil
470 474 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
471 475 per_page = params[:per_page].to_s.to_i
472 476 session[:per_page] = per_page
473 477 elsif session[:per_page]
474 478 per_page = session[:per_page]
475 479 else
476 480 per_page = Setting.per_page_options_array.first || 25
477 481 end
478 482 per_page
479 483 end
480 484
481 485 # Returns offset and limit used to retrieve objects
482 486 # for an API response based on offset, limit and page parameters
483 487 def api_offset_and_limit(options=params)
484 488 if options[:offset].present?
485 489 offset = options[:offset].to_i
486 490 if offset < 0
487 491 offset = 0
488 492 end
489 493 end
490 494 limit = options[:limit].to_i
491 495 if limit < 1
492 496 limit = 25
493 497 elsif limit > 100
494 498 limit = 100
495 499 end
496 500 if offset.nil? && options[:page].present?
497 501 offset = (options[:page].to_i - 1) * limit
498 502 offset = 0 if offset < 0
499 503 end
500 504 offset ||= 0
501 505
502 506 [offset, limit]
503 507 end
504 508
505 509 # qvalues http header parser
506 510 # code taken from webrick
507 511 def parse_qvalues(value)
508 512 tmp = []
509 513 if value
510 514 parts = value.split(/,\s*/)
511 515 parts.each {|part|
512 516 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
513 517 val = m[1]
514 518 q = (m[2] or 1).to_f
515 519 tmp.push([val, q])
516 520 end
517 521 }
518 522 tmp = tmp.sort_by{|val, q| -q}
519 523 tmp.collect!{|val, q| val}
520 524 end
521 525 return tmp
522 526 rescue
523 527 nil
524 528 end
525 529
526 530 # Returns a string that can be used as filename value in Content-Disposition header
527 531 def filename_for_content_disposition(name)
528 532 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
529 533 end
530 534
531 535 def api_request?
532 536 %w(xml json).include? params[:format]
533 537 end
534 538
535 539 # Returns the API key present in the request
536 540 def api_key_from_request
537 541 if params[:key].present?
538 542 params[:key].to_s
539 543 elsif request.headers["X-Redmine-API-Key"].present?
540 544 request.headers["X-Redmine-API-Key"].to_s
541 545 end
542 546 end
543 547
544 548 # Returns the API 'switch user' value if present
545 549 def api_switch_user_from_request
546 550 request.headers["X-Redmine-Switch-User"].to_s.presence
547 551 end
548 552
549 553 # Renders a warning flash if obj has unsaved attachments
550 554 def render_attachment_warning_if_needed(obj)
551 555 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
552 556 end
553 557
554 558 # Sets the `flash` notice or error based the number of issues that did not save
555 559 #
556 560 # @param [Array, Issue] issues all of the saved and unsaved Issues
557 561 # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
558 562 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
559 563 if unsaved_issue_ids.empty?
560 564 flash[:notice] = l(:notice_successful_update) unless issues.empty?
561 565 else
562 566 flash[:error] = l(:notice_failed_to_save_issues,
563 567 :count => unsaved_issue_ids.size,
564 568 :total => issues.size,
565 569 :ids => '#' + unsaved_issue_ids.join(', #'))
566 570 end
567 571 end
568 572
569 573 # Rescues an invalid query statement. Just in case...
570 574 def query_statement_invalid(exception)
571 575 logger.error "Query::StatementInvalid: #{exception.message}" if logger
572 576 session.delete(:query)
573 577 sort_clear if respond_to?(:sort_clear)
574 578 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
575 579 end
576 580
577 581 # Renders a 200 response for successfull updates or deletions via the API
578 582 def render_api_ok
579 583 render_api_head :ok
580 584 end
581 585
582 586 # Renders a head API response
583 587 def render_api_head(status)
584 588 # #head would return a response body with one space
585 589 render :text => '', :status => status, :layout => nil
586 590 end
587 591
588 592 # Renders API response on validation failure
589 593 def render_validation_errors(objects)
590 594 if objects.is_a?(Array)
591 595 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
592 596 else
593 597 @error_messages = objects.errors.full_messages
594 598 end
595 599 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
596 600 end
597 601
598 602 # Overrides #_include_layout? so that #render with no arguments
599 603 # doesn't use the layout for api requests
600 604 def _include_layout?(*args)
601 605 api_request? ? false : super
602 606 end
603 607 end
@@ -1,185 +1,212
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2013 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 require File.expand_path('../../test_helper', __FILE__)
19 19
20 20 begin
21 21 require 'mocha'
22 22 rescue
23 23 # Won't run some tests
24 24 end
25 25
26 26 class AccountTest < ActionController::IntegrationTest
27 27 fixtures :users, :roles
28 28
29 29 # Replace this with your real tests.
30 30 def test_login
31 31 get "my/page"
32 32 assert_redirected_to "/login?back_url=http%3A%2F%2Fwww.example.com%2Fmy%2Fpage"
33 33 log_user('jsmith', 'jsmith')
34 34
35 35 get "my/account"
36 36 assert_response :success
37 37 assert_template "my/account"
38 38 end
39 39
40 40 def test_autologin
41 41 user = User.find(1)
42 42 Setting.autologin = "7"
43 43 Token.delete_all
44 44
45 45 # User logs in with 'autologin' checked
46 46 post '/login', :username => user.login, :password => 'admin', :autologin => 1
47 47 assert_redirected_to '/my/page'
48 48 token = Token.first
49 49 assert_not_nil token
50 50 assert_equal user, token.user
51 51 assert_equal 'autologin', token.action
52 52 assert_equal user.id, session[:user_id]
53 53 assert_equal token.value, cookies['autologin']
54 54
55 55 # Session is cleared
56 56 reset!
57 57 User.current = nil
58 58 # Clears user's last login timestamp
59 59 user.update_attribute :last_login_on, nil
60 60 assert_nil user.reload.last_login_on
61 61
62 62 # User comes back with his autologin cookie
63 63 cookies[:autologin] = token.value
64 64 get '/my/page'
65 65 assert_response :success
66 66 assert_template 'my/page'
67 67 assert_equal user.id, session[:user_id]
68 68 assert_not_nil user.reload.last_login_on
69 69 end
70 70
71 def test_autologin_should_use_autologin_cookie_name
72 Token.delete_all
73 Redmine::Configuration.stubs(:[]).with('autologin_cookie_name').returns('custom_autologin')
74 Redmine::Configuration.stubs(:[]).with('autologin_cookie_path').returns('/')
75 Redmine::Configuration.stubs(:[]).with('autologin_cookie_secure').returns(false)
76
77 with_settings :autologin => '7' do
78 assert_difference 'Token.count' do
79 post '/login', :username => 'admin', :password => 'admin', :autologin => 1
80 end
81 assert_response 302
82 assert cookies['custom_autologin'].present?
83 token = cookies['custom_autologin']
84
85 # Session is cleared
86 reset!
87 cookies['custom_autologin'] = token
88 get '/my/page'
89 assert_response :success
90
91 assert_difference 'Token.count', -1 do
92 post '/logout'
93 end
94 assert cookies['custom_autologin'].blank?
95 end
96 end
97
71 98 def test_lost_password
72 99 Token.delete_all
73 100
74 101 get "account/lost_password"
75 102 assert_response :success
76 103 assert_template "account/lost_password"
77 104 assert_select 'input[name=mail]'
78 105
79 106 post "account/lost_password", :mail => 'jSmith@somenet.foo'
80 107 assert_redirected_to "/login"
81 108
82 109 token = Token.first
83 110 assert_equal 'recovery', token.action
84 111 assert_equal 'jsmith@somenet.foo', token.user.mail
85 112 assert !token.expired?
86 113
87 114 get "account/lost_password", :token => token.value
88 115 assert_response :success
89 116 assert_template "account/password_recovery"
90 117 assert_select 'input[type=hidden][name=token][value=?]', token.value
91 118 assert_select 'input[name=new_password]'
92 119 assert_select 'input[name=new_password_confirmation]'
93 120
94 121 post "account/lost_password", :token => token.value, :new_password => 'newpass123', :new_password_confirmation => 'newpass123'
95 122 assert_redirected_to "/login"
96 123 assert_equal 'Password was successfully updated.', flash[:notice]
97 124
98 125 log_user('jsmith', 'newpass123')
99 126 assert_equal 0, Token.count
100 127 end
101 128
102 129 def test_register_with_automatic_activation
103 130 Setting.self_registration = '3'
104 131
105 132 get 'account/register'
106 133 assert_response :success
107 134 assert_template 'account/register'
108 135
109 136 post 'account/register', :user => {:login => "newuser", :language => "en", :firstname => "New", :lastname => "User", :mail => "newuser@foo.bar",
110 137 :password => "newpass123", :password_confirmation => "newpass123"}
111 138 assert_redirected_to '/my/account'
112 139 follow_redirect!
113 140 assert_response :success
114 141 assert_template 'my/account'
115 142
116 143 user = User.find_by_login('newuser')
117 144 assert_not_nil user
118 145 assert user.active?
119 146 assert_not_nil user.last_login_on
120 147 end
121 148
122 149 def test_register_with_manual_activation
123 150 Setting.self_registration = '2'
124 151
125 152 post 'account/register', :user => {:login => "newuser", :language => "en", :firstname => "New", :lastname => "User", :mail => "newuser@foo.bar",
126 153 :password => "newpass123", :password_confirmation => "newpass123"}
127 154 assert_redirected_to '/login'
128 155 assert !User.find_by_login('newuser').active?
129 156 end
130 157
131 158 def test_register_with_email_activation
132 159 Setting.self_registration = '1'
133 160 Token.delete_all
134 161
135 162 post 'account/register', :user => {:login => "newuser", :language => "en", :firstname => "New", :lastname => "User", :mail => "newuser@foo.bar",
136 163 :password => "newpass123", :password_confirmation => "newpass123"}
137 164 assert_redirected_to '/login'
138 165 assert !User.find_by_login('newuser').active?
139 166
140 167 token = Token.first
141 168 assert_equal 'register', token.action
142 169 assert_equal 'newuser@foo.bar', token.user.mail
143 170 assert !token.expired?
144 171
145 172 get 'account/activate', :token => token.value
146 173 assert_redirected_to '/login'
147 174 log_user('newuser', 'newpass123')
148 175 end
149 176
150 177 def test_onthefly_registration
151 178 # disable registration
152 179 Setting.self_registration = '0'
153 180 AuthSource.expects(:authenticate).returns({:login => 'foo', :firstname => 'Foo', :lastname => 'Smith', :mail => 'foo@bar.com', :auth_source_id => 66})
154 181
155 182 post '/login', :username => 'foo', :password => 'bar'
156 183 assert_redirected_to '/my/page'
157 184
158 185 user = User.find_by_login('foo')
159 186 assert user.is_a?(User)
160 187 assert_equal 66, user.auth_source_id
161 188 assert user.hashed_password.blank?
162 189 end
163 190
164 191 def test_onthefly_registration_with_invalid_attributes
165 192 # disable registration
166 193 Setting.self_registration = '0'
167 194 AuthSource.expects(:authenticate).returns({:login => 'foo', :lastname => 'Smith', :auth_source_id => 66})
168 195
169 196 post '/login', :username => 'foo', :password => 'bar'
170 197 assert_response :success
171 198 assert_template 'account/register'
172 199 assert_tag :input, :attributes => { :name => 'user[firstname]', :value => '' }
173 200 assert_tag :input, :attributes => { :name => 'user[lastname]', :value => 'Smith' }
174 201 assert_no_tag :input, :attributes => { :name => 'user[login]' }
175 202 assert_no_tag :input, :attributes => { :name => 'user[password]' }
176 203
177 204 post 'account/register', :user => {:firstname => 'Foo', :lastname => 'Smith', :mail => 'foo@bar.com'}
178 205 assert_redirected_to '/my/account'
179 206
180 207 user = User.find_by_login('foo')
181 208 assert user.is_a?(User)
182 209 assert_equal 66, user.auth_source_id
183 210 assert user.hashed_password.blank?
184 211 end
185 212 end
General Comments 0
You need to be logged in to leave comments. Login now