def run_async_task(self, site=None, user=None, cmd=None, form_dict=None, hijack_std=False):
	ret = {}
	frappe.init(site)
	frappe.connect()

	frappe.local.task_id = self.request.id

	if hijack_std:
		original_stdout, original_stderr = sys.stdout, sys.stderr
		sys.stdout, sys.stderr = get_std_streams(self.request.id)
		frappe.local.stdout, frappe.local.stderr = sys.stdout, sys.stderr

	try:
		set_task_status(self.request.id, "Running")
		frappe.db.commit()
		frappe.set_user(user)
		# sleep(60)
		frappe.local.form_dict = frappe._dict(form_dict)
		execute_cmd(cmd, from_async=True)
		ret = frappe.local.response

	except Exception, e:
		frappe.db.rollback()
		ret = frappe.local.response
		http_status_code = getattr(e, "http_status_code", 500)
		ret['status_code'] = http_status_code
		frappe.errprint(frappe.get_traceback())
		frappe.utils.response.make_logs()
		set_task_status(self.request.id, "Error", response=ret)
		task_logger.error('Exception in running {}: {}'.format(cmd, ret['exc']))
Beispiel #2
0
def run_async_task(self, site, user, cmd, form_dict):
	ret = {}
	frappe.init(site)
	frappe.connect()
	sys.stdout, sys.stderr = get_std_streams(self.request.id)
	frappe.local.stdout, frappe.local.stderr = sys.stdout, sys.stderr
	frappe.local.task_id = self.request.id
	frappe.cache()
	try:
		set_task_status(self.request.id, "Running")
		frappe.db.commit()
		frappe.set_user(user)
		# sleep(60)
		frappe.local.form_dict = frappe._dict(form_dict)
		execute_cmd(cmd, from_async=True)
		ret = frappe.local.response
	except Exception, e:
		frappe.db.rollback()
		if not frappe.flags.in_test:
			frappe.db.commit()

		ret = frappe.local.response
		http_status_code = getattr(e, "http_status_code", 500)
		ret['status_code'] = http_status_code
		frappe.errprint(frappe.get_traceback())
		frappe.utils.response.make_logs()
		set_task_status(self.request.id, "Failed", response=ret)
		task_logger.error('Exception in running {}: {}'.format(cmd, ret['exc']))
Beispiel #3
0
def run_async_task(self, site=None, user=None, cmd=None, form_dict=None, hijack_std=False):
	ret = {}
	frappe.init(site)
	frappe.connect()

	frappe.local.task_id = self.request.id

	if hijack_std:
		original_stdout, original_stderr = sys.stdout, sys.stderr
		sys.stdout, sys.stderr = get_std_streams(self.request.id)
		frappe.local.stdout, frappe.local.stderr = sys.stdout, sys.stderr

	try:
		set_task_status(self.request.id, "Running")
		frappe.db.commit()
		frappe.set_user(user)
		# sleep(60)
		frappe.local.form_dict = frappe._dict(form_dict)
		execute_cmd(cmd, from_async=True)
		ret = frappe.local.response

	except Exception, e:
		frappe.db.rollback()
		ret = frappe.local.response
		http_status_code = getattr(e, "http_status_code", 500)
		ret['status_code'] = http_status_code
		frappe.errprint(frappe.get_traceback())
		frappe.utils.response.make_logs()
		set_task_status(self.request.id, "Error", response=ret)
		task_logger.error('Exception in running {}: {}'.format(cmd, ret['exc']))
Beispiel #4
0
    def test_reportview_get(self):
        user = frappe.get_doc("User", "*****@*****.**")
        add_child_table_to_blog_post()

        user_roles = frappe.get_roles()
        user.remove_roles(*user_roles)
        user.add_roles("Blogger")

        make_property_setter("Blog Post", "published", "permlevel", 1, "Int")
        reset("Blog Post")
        add("Blog Post", "Website Manager", 1)
        update("Blog Post", "Website Manager", 1, "write", 1)

        frappe.set_user(user.name)

        frappe.local.request = frappe._dict()
        frappe.local.request.method = "POST"

        frappe.local.form_dict = frappe._dict({
            "doctype":
            "Blog Post",
            "fields": ["published", "title", "`tabTest Child`.`test_field`"],
        })

        # even if * is passed, fields which are not accessible should be filtered out
        response = execute_cmd("frappe.desk.reportview.get")
        self.assertListEqual(response["keys"], ["title"])
        frappe.local.form_dict = frappe._dict({
            "doctype": "Blog Post",
            "fields": ["*"],
        })

        response = execute_cmd("frappe.desk.reportview.get")
        self.assertNotIn("published", response["keys"])

        frappe.set_user("Administrator")
        user.add_roles("Website Manager")
        frappe.set_user(user.name)

        frappe.set_user("Administrator")

        # Admin should be able to see access all fields
        frappe.local.form_dict = frappe._dict({
            "doctype":
            "Blog Post",
            "fields": ["published", "title", "`tabTest Child`.`test_field`"],
        })

        response = execute_cmd("frappe.desk.reportview.get")
        self.assertListEqual(response["keys"],
                             ["published", "title", "test_field"])

        # reset user roles
        user.remove_roles("Blogger", "Website Manager")
        user.add_roles(*user_roles)
Beispiel #5
0
	def test_run_doc_method(self):
		from frappe.handler import execute_cmd

		if not frappe.db.exists('Report', 'Test Run Doc Method'):
			report = frappe.get_doc({
				'doctype': 'Report',
				'ref_doctype': 'User',
				'report_name': 'Test Run Doc Method',
				'report_type': 'Query Report',
				'is_standard': 'No',
				'roles': [
					{'role': 'System Manager'}
				]
			}).insert()
		else:
			report = frappe.get_doc('Report', 'Test Run Doc Method')

		frappe.local.request = frappe._dict()
		frappe.local.request.method = 'GET'

		# Whitelisted, works as expected
		frappe.local.form_dict = frappe._dict({
			'dt': report.doctype,
			'dn': report.name,
			'method': 'toggle_disable',
			'cmd': 'run_doc_method',
			'args': 0
		})

		execute_cmd(frappe.local.form_dict.cmd)

		# Not whitelisted, throws permission error
		frappe.local.form_dict = frappe._dict({
			'dt': report.doctype,
			'dn': report.name,
			'method': 'create_report_py',
			'cmd': 'run_doc_method',
			'args': 0
		})

		self.assertRaises(
			frappe.PermissionError,
			execute_cmd,
			frappe.local.form_dict.cmd
		)
Beispiel #6
0
    def test_run_doc_method(self):
        from frappe.handler import execute_cmd

        if not frappe.db.exists("Report", "Test Run Doc Method"):
            report = frappe.get_doc({
                "doctype": "Report",
                "ref_doctype": "User",
                "report_name": "Test Run Doc Method",
                "report_type": "Query Report",
                "is_standard": "No",
                "roles": [{
                    "role": "System Manager"
                }],
            }).insert()
        else:
            report = frappe.get_doc("Report", "Test Run Doc Method")

        frappe.local.request = frappe._dict()
        frappe.local.request.method = "GET"

        # Whitelisted, works as expected
        frappe.local.form_dict = frappe._dict({
            "dt": report.doctype,
            "dn": report.name,
            "method": "toggle_disable",
            "cmd": "run_doc_method",
            "args": 0,
        })

        execute_cmd(frappe.local.form_dict.cmd)

        # Not whitelisted, throws permission error
        frappe.local.form_dict = frappe._dict({
            "dt": report.doctype,
            "dn": report.name,
            "method": "create_report_py",
            "cmd": "run_doc_method",
            "args": 0,
        })

        self.assertRaises(frappe.PermissionError, execute_cmd,
                          frappe.local.form_dict.cmd)
Beispiel #7
0
	def _run(args, set_in_response=True):
		from frappe.tasks import run_async_task
		from frappe.handler import execute_cmd
		if frappe.conf.disable_async:
			return execute_cmd(cmd, from_async=True)
		args = frappe._dict(args)
		task = run_async_task.delay(frappe.local.site,
			(frappe.session and frappe.session.user) or 'Administrator', cmd, args)
		if set_in_response:
			frappe.local.response['task_id'] = task.id
		return task.id
Beispiel #8
0
 def queue(*args, **kwargs):
     from frappe.tasks import run_async_task
     from frappe.handler import execute_cmd
     if frappe.conf.disable_async:
         return execute_cmd(cmd, from_async=True)
     task = run_async_task.delay(frappe.local.site,
                                 (frappe.session and frappe.session.user)
                                 or 'Administrator', cmd,
                                 frappe.local.form_dict)
     frappe.local.response['task_id'] = task.id
     return {"status": "queued", "task_id": task.id}
Beispiel #9
0
	def queue(*args, **kwargs):
		from frappe.tasks import run_async_task
		from frappe.handler import execute_cmd
		if frappe.conf.disable_async:
			return execute_cmd(cmd, from_async=True)
		task = run_async_task.delay(frappe.local.site,
			(frappe.session and frappe.session.user) or 'Administrator', cmd,
				frappe.local.form_dict)
		frappe.local.response['task_id'] = task.id
		return {
			"status": "queued",
			"task_id": task.id
		}
Beispiel #10
0
    def run(args, set_in_response=True):
        from frappe.tasks import run_async_task
        from frappe.handler import execute_cmd

        if frappe.conf.disable_async:
            return execute_cmd(cmd, from_async=True)
        args = frappe._dict(args)
        task = run_async_task.delay(
            site=frappe.local.site,
            user=(frappe.session and frappe.session.user) or "Administrator",
            cmd=cmd,
            form_dict=args,
        )
        if set_in_response:
            frappe.local.response["task_id"] = task.id
        return task.id
Beispiel #11
0
	def test_http_valid_method_access(self):
		from frappe.client import delete
		from frappe.handler import execute_cmd

		frappe.set_user("Administrator")

		frappe.local.request = frappe._dict()
		frappe.local.request.method = 'POST'

		frappe.local.form_dict = frappe._dict({
			'doc': dict(doctype='ToDo', description='Valid http method'),
			'cmd': 'frappe.client.save'
		})
		todo = execute_cmd('frappe.client.save')

		self.assertEqual(todo.get('description'), 'Valid http method')

		delete("ToDo", todo.name)
Beispiel #12
0
    def test_http_valid_method_access(self):
        from frappe.client import delete
        from frappe.handler import execute_cmd

        frappe.set_user("Administrator")

        frappe.local.request = frappe._dict()
        frappe.local.request.method = "POST"

        frappe.local.form_dict = frappe._dict({
            "doc":
            dict(doctype="ToDo", description="Valid http method"),
            "cmd":
            "frappe.client.save"
        })
        todo = execute_cmd("frappe.client.save")

        self.assertEqual(todo.get("description"), "Valid http method")

        delete("ToDo", todo.name)
Beispiel #13
0
    def test_reportview_get_aggregation(self):
        # test aggregation based on child table field
        frappe.local.form_dict = frappe._dict({
            "doctype": "DocType",
            "fields":
            """["`tabDocField`.`label` as field_label","`tabDocField`.`name` as field_name"]""",
            "filters": "[]",
            "order_by": "_aggregate_column desc",
            "start": 0,
            "page_length": 20,
            "view": "Report",
            "with_comment_count": 0,
            "group_by": "field_label, field_name",
            "aggregate_on_field": "columns",
            "aggregate_on_doctype": "DocField",
            "aggregate_function": "sum",
        })

        response = execute_cmd("frappe.desk.reportview.get")
        self.assertListEqual(
            response["keys"],
            ["field_label", "field_name", "_aggregate_column", "columns"])
Beispiel #14
0
def call_whitelisted_function(function, **kwargs):
	"""Executes a whitelisted function or Server Script of type API"""

	return call_with_form_dict(lambda: execute_cmd(function), kwargs)