two_factor_auths_controller.rb 1.98 KB
Newer Older
1
class Profiles::TwoFactorAuthsController < Profiles::ApplicationController
2
  skip_before_action :check_2fa_requirement
3

4
  def new
5
    unless current_user.otp_secret
6
      current_user.otp_secret = User.generate_otp_secret(32)
7
    end
8

9 10 11
    unless current_user.otp_grace_period_started_at && two_factor_grace_period
      current_user.otp_grace_period_started_at = Time.current
    end
12

13
    current_user.save! if current_user.changed?
14

15 16 17 18 19 20 21
    if two_factor_authentication_required?
      if two_factor_grace_period_expired?
        flash.now[:alert] = 'You must enable Two-factor Authentication for your account.'
      else
        grace_period_deadline = current_user.otp_grace_period_started_at + two_factor_grace_period.hours
        flash.now[:alert] = "You must enable Two-factor Authentication for your account before #{l(grace_period_deadline)}."
      end
22 23
    end

24
    @qr_code = build_qr_code
25 26 27
  end

  def create
28
    if current_user.validate_and_consume_otp!(params[:pin_code])
29
      current_user.two_factor_enabled = true
30
      @codes = current_user.generate_otp_backup_codes!
31
      current_user.save!
32

33
      render 'create'
34 35 36
    else
      @error = 'Invalid pin code'
      @qr_code = build_qr_code
37

38 39
      render 'new'
    end
40 41
  end

42
  def codes
43
    @codes = current_user.generate_otp_backup_codes!
44 45 46
    current_user.save!
  end

47
  def destroy
48
    current_user.disable_two_factor!
49 50 51

    redirect_to profile_account_path
  end
52

53
  def skip
54
    if two_factor_grace_period_expired?
55 56 57 58 59 60 61
      redirect_to new_profile_two_factor_auth_path, alert: 'Cannot skip two factor authentication setup'
    else
      session[:skip_tfa] = current_user.otp_grace_period_started_at + two_factor_grace_period.hours
      redirect_to root_path
    end
  end

62 63 64
  private

  def build_qr_code
65
    issuer = "#{issuer_host} | #{current_user.email}"
66 67 68
    uri = current_user.otp_provisioning_uri(current_user.email, issuer: issuer)
    RQRCode::render_qrcode(uri, :svg, level: :m, unit: 3)
  end
69 70 71 72

  def issuer_host
    Gitlab.config.gitlab.host
  end
73
end