  def email_login
    raise Discourse::NotFound if !SiteSetting.enable_local_logins_via_email
    second_factor_token = params[:second_factor_token]
    second_factor_method = params[:second_factor_method].to_i
    token = params[:token]
    valid_token = !!EmailToken.valid_token_format?(token)
    user = EmailToken.confirmable(token)&.user

    if valid_token && user&.totp_enabled?
      if !second_factor_token.present?
        @second_factor_required = true
        @backup_codes_enabled = true if user&.backup_codes_enabled?
        return render layout: 'no_ember'
      elsif !user.authenticate_second_factor(second_factor_token, second_factor_method)
        RateLimiter.new(nil, "second-factor-min-#{request.remote_ip}", 3, 1.minute).performed!
        @error = I18n.t('login.invalid_second_factor_code')
        return render layout: 'no_ember'
      end
    end

    if user = EmailToken.confirm(token)
      if login_not_approved_for?(user)
        @error = login_not_approved[:error]
      elsif payload = login_error_check(user)
        @error = payload[:error]
      else
        log_on_user(user)
        return redirect_to path("/")
      end
    else
      @error = I18n.t('email_login.invalid_token')
    end

    render layout: 'no_ember'
  end