GitLab steht wegen Wartungsarbeiten am Montag, den 10. Mai, zwischen 17:00 und 19:00 Uhr nicht zur Verfügung.

account_controller.rb 11.9 KB
Newer Older
1
# Redmine - project management software
jplang's avatar
jplang committed
2
# Copyright (C) 2006-2017  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 23
  self.main_menu = false

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

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

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

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

jplang's avatar
jplang committed
60
  # Lets user choose a new password
61
  def lost_password
jplang's avatar
jplang committed
62
    (redirect_to(home_url); return) unless Setting.lost_password?
63 64
    if prt = (params[:token] || session[:password_recovery_token])
      @token = Token.find_token("recovery", prt.to_s)
jplang's avatar
jplang committed
65 66 67 68
      if @token.nil? || @token.expired?
        redirect_to home_url
        return
      end
69 70 71 72 73 74 75 76

      # redirect to remove the token query parameter from the URL and add it to the session
      if request.query_parameters[:token].present?
        session[:password_recovery_token] = @token.value
        redirect_to lost_password_url
        return
      end

77
      @user = @token.user
jplang's avatar
jplang committed
78 79 80 81
      unless @user && @user.active?
        redirect_to home_url
        return
      end
82
      if request.post?
83 84 85 86 87 88 89
        if @user.must_change_passwd? && @user.check_password?(params[:new_password])
          flash.now[:error] = l(:notice_new_password_must_be_different)
        else
          @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]
          @user.must_change_passwd = false
          if @user.save
            @token.destroy
90
            Mailer.password_updated(@user, { remote_ip: request.remote_ip })
91 92 93 94
            flash[:notice] = l(:notice_account_password_updated)
            redirect_to signin_path
            return
          end
95
        end
96 97 98 99 100
      end
      render :template => "account/password_recovery"
      return
    else
      if request.post?
101
        email = params[:mail].to_s.strip
102
        user = User.find_by_mail(email)
103 104
        # user not found
        unless user
jplang's avatar
jplang committed
105 106 107
          flash.now[:error] = l(:notice_account_unknown_email)
          return
        end
108 109 110 111
        unless user.active?
          handle_inactive_user(user, lost_password_path)
          return
        end
jplang's avatar
jplang committed
112 113 114 115 116
        # user cannot change its password
        unless user.change_password_allowed?
          flash.now[:error] = l(:notice_can_t_change_password)
          return
        end
117 118 119
        # create a new token for password recovery
        token = Token.new(:user => user, :action => "recovery")
        if token.save
120
          # Don't use the param to send the email
121
          recipent = user.mails.detect {|e| email.casecmp(e) == 0} || user.mail
122
          Mailer.lost_password(token, recipent).deliver
123
          flash[:notice] = l(:notice_account_lost_email_sent)
jplang's avatar
jplang committed
124
          redirect_to signin_path
125 126 127 128 129
          return
        end
      end
    end
  end
130

131 132
  # User self-registration
  def register
jplang's avatar
jplang committed
133
    (redirect_to(home_url); return) unless Setting.self_registration? || session[:auth_source_registration]
134
    if !request.post?
135
      session[:auth_source_registration] = nil
136
      @user = User.new(:language => current_language.to_s)
137
    else
138
      user_params = params[:user] || {}
jplang's avatar
jplang committed
139
      @user = User.new
140
      @user.safe_attributes = user_params
141
      @user.pref.safe_attributes = params[:pref]
142
      @user.admin = false
143
      @user.register
144
      if session[:auth_source_registration]
145
        @user.activate
146 147
        @user.login = session[:auth_source_registration][:login]
        @user.auth_source_id = session[:auth_source_registration][:auth_source_id]
148
        if @user.save
149
          session[:auth_source_registration] = nil
150
          self.logged_user = @user
151
          flash[:notice] = l(:notice_account_activated)
jplang's avatar
jplang committed
152
          redirect_to my_account_path
153 154
        end
      else
155 156 157
        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
158

159 160
        case Setting.self_registration
        when '1'
161
          register_by_email_activation(@user)
162
        when '3'
163
          register_automatically(@user)
164
        else
165
          register_manually_by_administrator(@user)
166 167 168 169
        end
      end
    end
  end
170

171 172
  # Token based account activation
  def activate
jplang's avatar
jplang committed
173
    (redirect_to(home_url); return) unless Setting.self_registration? && params[:token].present?
jplang's avatar
jplang committed
174
    token = Token.find_token('register', params[:token].to_s)
jplang's avatar
jplang committed
175
    (redirect_to(home_url); return) unless token and !token.expired?
176
    user = token.user
jplang's avatar
jplang committed
177
    (redirect_to(home_url); return) unless user.registered?
178
    user.activate
179 180 181 182
    if user.save
      token.destroy
      flash[:notice] = l(:notice_account_activated)
    end
jplang's avatar
jplang committed
183
    redirect_to signin_path
184
  end
185

186 187 188 189 190 191 192 193 194 195 196 197 198
  # 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

199
  private
200

edavis10's avatar
edavis10 committed
201 202 203 204 205 206 207 208
  def authenticate_user
    if Setting.openid? && using_open_id?
      open_id_authenticate(params[:openid_url])
    else
      password_authentication
    end
  end

209
  def password_authentication
210
    user = User.try_to_login(params[:username], params[:password], false)
edavis10's avatar
edavis10 committed
211

212
    if user.nil?
edavis10's avatar
edavis10 committed
213
      invalid_credentials
214
    elsif user.new_record?
215
      onthefly_creation_failed(user, {:login => user.login, :auth_source_id => user.auth_source_id })
216 217
    else
      # Valid user
218 219
      if user.active?
        successful_authentication(user)
220
        update_sudo_timestamp! # activate Sudo Mode
221 222 223
      else
        handle_inactive_user(user)
      end
224 225 226 227
    end
  end

  def open_id_authenticate(openid_url)
228
    back_url = signin_url(:autologin => params[:autologin])
229 230 231 232
    authenticate_with_open_id(
          openid_url, :required => [:nickname, :fullname, :email],
          :return_to => back_url, :method => :post
    ) do |result, identity_url, registration|
233 234 235
      if result.successful?
        user = User.find_or_initialize_by_identity_url(identity_url)
        if user.new_record?
236
          # Self-registration off
jplang's avatar
jplang committed
237
          (redirect_to(home_url); return) unless Setting.self_registration?
238
          # Create on the fly
239 240 241
          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?
242
          user.random_password
243
          user.register
244 245
          case Setting.self_registration
          when '1'
246
            register_by_email_activation(user) do
247
              onthefly_creation_failed(user)
248 249
            end
          when '3'
250
            register_automatically(user) do
251
              onthefly_creation_failed(user)
252
            end
253
          else
254
            register_manually_by_administrator(user) do
255
              onthefly_creation_failed(user)
256
            end
257
          end
258
        else
259
          # Existing record
260 261 262
          if user.active?
            successful_authentication(user)
          else
263
            handle_inactive_user(user)
264
          end
265 266 267 268
        end
      end
    end
  end
269

270
  def successful_authentication(user)
jplang's avatar
jplang committed
271
    logger.info "Successful authentication for '#{user.login}' from #{request.remote_ip} at #{Time.now.utc}"
272 273 274 275
    # Valid user
    self.logged_user = user
    # generate a key and set cookie if autologin
    if params[:autologin] && Setting.autologin?
276
      set_autologin_cookie(user)
277
    end
278
    call_hook(:controller_account_success_authentication_after, {:user => user })
jplang's avatar
jplang committed
279
    redirect_back_or_default my_page_path
280
  end
281

282
  def set_autologin_cookie(user)
283
    token = user.generate_autologin_token
284 285 286 287
    secure = Redmine::Configuration['autologin_cookie_secure']
    if secure.nil?
      secure = request.ssl?
    end
288
    cookie_options = {
289
      :value => token,
290
      :expires => 1.year.from_now,
291
      :path => (Redmine::Configuration['autologin_cookie_path'] || RedmineApp::Application.config.relative_url_root || '/'),
292
      :secure => secure,
293
      :httponly => true
294
    }
295
    cookies[autologin_cookie_name] = cookie_options
296
  end
297

298 299 300 301
  # 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?
302
    render :action => 'register'
303 304
  end

edavis10's avatar
edavis10 committed
305
  def invalid_credentials
306
    logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}"
307
    flash.now[:error] = l(:notice_account_invalid_credentials)
edavis10's avatar
edavis10 committed
308 309
  end

310 311 312 313 314 315
  # 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
316
      Mailer.register(token).deliver
jplang's avatar
jplang committed
317
      flash[:notice] = l(:notice_account_register_done, :email => ERB::Util.h(user.mail))
jplang's avatar
jplang committed
318
      redirect_to signin_path
319 320 321 322
    else
      yield if block_given?
    end
  end
323

324 325 326 327 328
  # Automatically register a user
  #
  # Pass a block for behavior when a user fails to save
  def register_automatically(user, &block)
    # Automatic activation
329
    user.activate
330
    user.last_login_on = Time.now
331 332 333
    if user.save
      self.logged_user = user
      flash[:notice] = l(:notice_account_activated)
jplang's avatar
jplang committed
334
      redirect_to my_account_path
335 336 337 338
    else
      yield if block_given?
    end
  end
339

340 341 342 343 344 345
  # 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
346
      Mailer.account_activation_request(user).deliver
347
      account_pending(user)
348 349 350 351
    else
      yield if block_given?
    end
  end
352

353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
  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
374
  end
jplang's avatar
jplang committed
375
end