account_controller.rb 11.4 KB
Newer Older
1
# Redmine - project management software
jplang's avatar
jplang committed
2
# Copyright (C) 2006-2016  Jean-Philippe Lang
3
4
5
6
7
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
8
#
9
10
11
12
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
13
#
14
15
16
17
18
19
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

class AccountController < ApplicationController
  helper :custom_fields
20
21
  include CustomFieldsHelper

22
  # prevents login action to be filtered by check_if_login_required application scope filter
23
  skip_before_action :check_if_login_required, :check_password_change
24

25
26
27
28
29
30
31
32
  # Overrides ApplicationController#verify_authenticity_token to disable
  # token verification on openid callbacks
  def verify_authenticity_token
    unless using_open_id?
      super
    end
  end

33
34
35
  # Login request and validation
  def login
    if request.get?
36
      if User.current.logged?
37
        redirect_back_or_default home_url, :referer => true
38
      end
39
    else
edavis10's avatar
edavis10 committed
40
      authenticate_user
41
    end
42
43
44
  rescue AuthSourceException => e
    logger.error "An error occured when authenticating #{params[:username]}: #{e.message}"
    render_error :message => e.message
45
46
47
48
  end

  # Log out current user and redirect to welcome page
  def logout
49
50
51
52
53
54
55
    if User.current.anonymous?
      redirect_to home_url
    elsif request.post?
      logout_user
      redirect_to home_url
    end
    # display the logout form
56
  end
57

jplang's avatar
jplang committed
58
  # Lets user choose a new password
59
  def lost_password
jplang's avatar
jplang committed
60
    (redirect_to(home_url); return) unless Setting.lost_password?
61
    if params[:token]
jplang's avatar
jplang committed
62
      @token = Token.find_token("recovery", params[:token].to_s)
jplang's avatar
jplang committed
63
64
65
66
      if @token.nil? || @token.expired?
        redirect_to home_url
        return
      end
67
      @user = @token.user
jplang's avatar
jplang committed
68
69
70
71
      unless @user && @user.active?
        redirect_to home_url
        return
      end
72
73
74
75
      if request.post?
        @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]
        if @user.save
          @token.destroy
76
          Mailer.password_updated(@user)
77
          flash[:notice] = l(:notice_account_password_updated)
jplang's avatar
jplang committed
78
          redirect_to signin_path
79
          return
80
        end
81
82
83
84
85
      end
      render :template => "account/password_recovery"
      return
    else
      if request.post?
86
87
        email = params[:mail].to_s
        user = User.find_by_mail(email)
88
89
        # user not found
        unless user
jplang's avatar
jplang committed
90
91
92
          flash.now[:error] = l(:notice_account_unknown_email)
          return
        end
93
94
95
96
        unless user.active?
          handle_inactive_user(user, lost_password_path)
          return
        end
jplang's avatar
jplang committed
97
98
99
100
101
        # user cannot change its password
        unless user.change_password_allowed?
          flash.now[:error] = l(:notice_can_t_change_password)
          return
        end
102
103
104
        # create a new token for password recovery
        token = Token.new(:user => user, :action => "recovery")
        if token.save
105
          # Don't use the param to send the email
106
          recipent = user.mails.detect {|e| email.casecmp(e) == 0} || user.mail
107
          Mailer.lost_password(token, recipent).deliver
108
          flash[:notice] = l(:notice_account_lost_email_sent)
jplang's avatar
jplang committed
109
          redirect_to signin_path
110
111
112
113
114
          return
        end
      end
    end
  end
115

116
117
  # User self-registration
  def register
jplang's avatar
jplang committed
118
    (redirect_to(home_url); return) unless Setting.self_registration? || session[:auth_source_registration]
119
    if request.get?
120
      session[:auth_source_registration] = nil
121
      @user = User.new(:language => current_language.to_s)
122
    else
123
      user_params = params[:user] || {}
jplang's avatar
jplang committed
124
      @user = User.new
125
      @user.safe_attributes = user_params
126
      @user.pref.attributes = params[:pref] if params[:pref]
127
      @user.admin = false
128
      @user.register
129
      if session[:auth_source_registration]
130
        @user.activate
131
132
        @user.login = session[:auth_source_registration][:login]
        @user.auth_source_id = session[:auth_source_registration][:auth_source_id]
133
        if @user.save
134
          session[:auth_source_registration] = nil
135
          self.logged_user = @user
136
          flash[:notice] = l(:notice_account_activated)
jplang's avatar
jplang committed
137
          redirect_to my_account_path
138
139
        end
      else
140
141
142
        unless user_params[:identity_url].present? && user_params[:password].blank? && user_params[:password_confirmation].blank?
          @user.password, @user.password_confirmation = user_params[:password], user_params[:password_confirmation]
        end
143

144
145
        case Setting.self_registration
        when '1'
146
          register_by_email_activation(@user)
147
        when '3'
148
          register_automatically(@user)
149
        else
150
          register_manually_by_administrator(@user)
151
152
153
154
        end
      end
    end
  end
155

156
157
  # Token based account activation
  def activate
jplang's avatar
jplang committed
158
    (redirect_to(home_url); return) unless Setting.self_registration? && params[:token].present?
jplang's avatar
jplang committed
159
    token = Token.find_token('register', params[:token].to_s)
jplang's avatar
jplang committed
160
    (redirect_to(home_url); return) unless token and !token.expired?
161
    user = token.user
jplang's avatar
jplang committed
162
    (redirect_to(home_url); return) unless user.registered?
163
    user.activate
164
165
166
167
    if user.save
      token.destroy
      flash[:notice] = l(:notice_account_activated)
    end
jplang's avatar
jplang committed
168
    redirect_to signin_path
169
  end
170

171
172
173
174
175
176
177
178
179
180
181
182
183
  # Sends a new account activation email
  def activation_email
    if session[:registered_user_id] && Setting.self_registration == '1'
      user_id = session.delete(:registered_user_id).to_i
      user = User.find_by_id(user_id)
      if user && user.registered?
        register_by_email_activation(user)
        return
      end
    end
    redirect_to(home_url)
  end

184
  private
185

edavis10's avatar
edavis10 committed
186
187
188
189
190
191
192
193
  def authenticate_user
    if Setting.openid? && using_open_id?
      open_id_authenticate(params[:openid_url])
    else
      password_authentication
    end
  end

194
  def password_authentication
195
    user = User.try_to_login(params[:username], params[:password], false)
edavis10's avatar
edavis10 committed
196

197
    if user.nil?
edavis10's avatar
edavis10 committed
198
      invalid_credentials
199
    elsif user.new_record?
200
      onthefly_creation_failed(user, {:login => user.login, :auth_source_id => user.auth_source_id })
201
202
    else
      # Valid user
203
204
      if user.active?
        successful_authentication(user)
205
        update_sudo_timestamp! # activate Sudo Mode
206
207
208
      else
        handle_inactive_user(user)
      end
209
210
211
212
    end
  end

  def open_id_authenticate(openid_url)
213
    back_url = signin_url(:autologin => params[:autologin])
214
215
216
217
    authenticate_with_open_id(
          openid_url, :required => [:nickname, :fullname, :email],
          :return_to => back_url, :method => :post
    ) do |result, identity_url, registration|
218
219
220
      if result.successful?
        user = User.find_or_initialize_by_identity_url(identity_url)
        if user.new_record?
221
          # Self-registration off
jplang's avatar
jplang committed
222
          (redirect_to(home_url); return) unless Setting.self_registration?
223
          # Create on the fly
224
225
226
          user.login = registration['nickname'] unless registration['nickname'].nil?
          user.mail = registration['email'] unless registration['email'].nil?
          user.firstname, user.lastname = registration['fullname'].split(' ') unless registration['fullname'].nil?
227
          user.random_password
228
          user.register
229
230
          case Setting.self_registration
          when '1'
231
            register_by_email_activation(user) do
232
              onthefly_creation_failed(user)
233
234
            end
          when '3'
235
            register_automatically(user) do
236
              onthefly_creation_failed(user)
237
            end
238
          else
239
            register_manually_by_administrator(user) do
240
              onthefly_creation_failed(user)
241
            end
242
          end
243
        else
244
          # Existing record
245
246
247
          if user.active?
            successful_authentication(user)
          else
248
            handle_inactive_user(user)
249
          end
250
251
252
253
        end
      end
    end
  end
254

255
  def successful_authentication(user)
jplang's avatar
jplang committed
256
    logger.info "Successful authentication for '#{user.login}' from #{request.remote_ip} at #{Time.now.utc}"
257
258
259
260
    # Valid user
    self.logged_user = user
    # generate a key and set cookie if autologin
    if params[:autologin] && Setting.autologin?
261
      set_autologin_cookie(user)
262
    end
263
    call_hook(:controller_account_success_authentication_after, {:user => user })
jplang's avatar
jplang committed
264
    redirect_back_or_default my_page_path
265
  end
266

267
268
  def set_autologin_cookie(user)
    token = Token.create(:user => user, :action => 'autologin')
269
270
271
272
    secure = Redmine::Configuration['autologin_cookie_secure']
    if secure.nil?
      secure = request.ssl?
    end
273
274
275
    cookie_options = {
      :value => token.value,
      :expires => 1.year.from_now,
276
      :path => (Redmine::Configuration['autologin_cookie_path'] || RedmineApp::Application.config.relative_url_root || '/'),
277
      :secure => secure,
278
      :httponly => true
279
    }
280
    cookies[autologin_cookie_name] = cookie_options
281
  end
282

283
284
285
286
  # Onthefly creation failed, display the registration form to fill/fix attributes
  def onthefly_creation_failed(user, auth_source_options = { })
    @user = user
    session[:auth_source_registration] = auth_source_options unless auth_source_options.empty?
287
    render :action => 'register'
288
289
  end

edavis10's avatar
edavis10 committed
290
  def invalid_credentials
291
    logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}"
292
    flash.now[:error] = l(:notice_account_invalid_credentials)
edavis10's avatar
edavis10 committed
293
294
  end

295
296
297
298
299
300
  # Register a user for email activation.
  #
  # Pass a block for behavior when a user fails to save
  def register_by_email_activation(user, &block)
    token = Token.new(:user => user, :action => "register")
    if user.save and token.save
301
      Mailer.register(token).deliver
jplang's avatar
jplang committed
302
      flash[:notice] = l(:notice_account_register_done, :email => ERB::Util.h(user.mail))
jplang's avatar
jplang committed
303
      redirect_to signin_path
304
305
306
307
    else
      yield if block_given?
    end
  end
308

309
310
311
312
313
  # Automatically register a user
  #
  # Pass a block for behavior when a user fails to save
  def register_automatically(user, &block)
    # Automatic activation
314
    user.activate
315
    user.last_login_on = Time.now
316
317
318
    if user.save
      self.logged_user = user
      flash[:notice] = l(:notice_account_activated)
jplang's avatar
jplang committed
319
      redirect_to my_account_path
320
321
322
323
    else
      yield if block_given?
    end
  end
324

325
326
327
328
329
330
  # Manual activation by the administrator
  #
  # Pass a block for behavior when a user fails to save
  def register_manually_by_administrator(user, &block)
    if user.save
      # Sends an email to the administrators
331
      Mailer.account_activation_request(user).deliver
332
      account_pending(user)
333
334
335
336
    else
      yield if block_given?
    end
  end
337

338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
  def handle_inactive_user(user, redirect_path=signin_path)
    if user.registered?
      account_pending(user, redirect_path)
    else
      account_locked(user, redirect_path)
    end
  end

  def account_pending(user, redirect_path=signin_path)
    if Setting.self_registration == '1'
      flash[:error] = l(:notice_account_not_activated_yet, :url => activation_email_path)
      session[:registered_user_id] = user.id
    else
      flash[:error] = l(:notice_account_pending)
    end
    redirect_to redirect_path
  end

  def account_locked(user, redirect_path=signin_path)
    flash[:error] = l(:notice_account_locked)
    redirect_to redirect_path
359
  end
jplang's avatar
jplang committed
360
end