Exemple #1
0
def get_link_options(web_form_name,
                     doctype,
                     allow_read_on_all_link_options=False):
    web_form_doc = dataent.get_doc("Web Form", web_form_name)
    doctype_validated = False
    limited_to_user = False
    if web_form_doc.login_required:
        # check if dataent session user is not guest or admin
        if dataent.session.user != 'Guest':
            doctype_validated = True

            if not allow_read_on_all_link_options:
                limited_to_user = True

    else:
        for field in web_form_doc.web_form_fields:
            if field.options == doctype:
                doctype_validated = True
                break

    if doctype_validated:
        link_options = []
        if limited_to_user:
            link_options = "\n".join([
                doc.name for doc in dataent.get_all(
                    doctype, filters={"owner": dataent.session.user})
            ])
        else:
            link_options = "\n".join(
                [doc.name for doc in dataent.get_all(doctype)])

        return link_options

    else:
        raise dataent.PermissionError('Not Allowed, {0}'.format(doctype))
Exemple #2
0
def delete(web_form_name, docname):
    web_form = dataent.get_doc("Web Form", web_form_name)

    owner = dataent.db.get_value(web_form.doc_type, docname, "owner")
    if dataent.session.user == owner and web_form.allow_delete:
        dataent.delete_doc(web_form.doc_type, docname, ignore_permissions=True)
    else:
        raise dataent.PermissionError("Not Allowed")
Exemple #3
0
 def append_table(self, table_name):
     self.tables.append(table_name)
     doctype = table_name[4:-1]
     if (not self.flags.ignore_permissions) and (
             not dataent.has_permission(doctype)):
         dataent.flags.error_message = _(
             'Insufficient Permission for {0}').format(
                 dataent.bold(doctype))
         raise dataent.PermissionError(doctype)
Exemple #4
0
def is_whitelisted(method):
    # check if whitelisted
    if dataent.session['user'] == 'Guest':
        if (method not in dataent.guest_methods):
            dataent.msgprint(_("Not permitted"))
            raise dataent.PermissionError('Not Allowed, {0}'.format(method))

        if method not in dataent.xss_safe_methods:
            # strictly sanitize form_dict
            # escapes html characters like <> except for predefined tags like a, b, ul etc.
            for key, value in dataent.form_dict.items():
                if isinstance(value, string_types):
                    dataent.form_dict[key] = dataent.utils.sanitize_html(value)

    else:
        if not method in dataent.whitelisted:
            dataent.msgprint(_("Not permitted"))
            raise dataent.PermissionError('Not Allowed, {0}'.format(method))
Exemple #5
0
def validate_print_permission(doc):
    if dataent.form_dict.get("key"):
        if dataent.form_dict.key == doc.get_signature():
            return

    for ptype in ("read", "print"):
        if (not dataent.has_permission(doc.doctype, ptype, doc)
                and not dataent.has_website_permission(doc)):
            raise dataent.PermissionError(_("No {0} permission").format(ptype))
Exemple #6
0
def can_export(doctype, raise_exception=False):
    if not ("System Manager" in dataent.get_roles()
            or has_permission(doctype, "export")):
        if raise_exception:
            raise dataent.PermissionError(
                "You are not allowed to export: {doctype}".format(
                    doctype=doctype))
        else:
            return False
    return True
Exemple #7
0
def get(name):
    """
	   Return the :term:`doclist` of the `Page` specified by `name`
	"""
    page = dataent.get_doc('Page', name)
    if page.is_permitted():
        page.load_assets()
        docs = dataent._dict(page.as_dict())
        if getattr(page, '_dynamic_page', None):
            docs['_dynamic_page'] = 1

        return docs
    else:
        dataent.response['403'] = 1
        raise dataent.PermissionError('No read permission for Page %s' %
                                      (page.title or name))
Exemple #8
0
def get_list(doctype, *args, **kwargs):
    '''wrapper for DatabaseQuery'''
    kwargs.pop('cmd', None)
    kwargs.pop('ignore_permissions', None)

    # If doctype is child table
    if dataent.is_table(doctype):
        # Example dataent.db.get_list('Purchase Receipt Item', {'parent': 'Purchase Receipt'})
        # Here purchase receipt is the parent doctype of the child doctype Purchase Receipt Item

        if not kwargs.get('parent'):
            dataent.flags.error_message = _(
                'Parent is required to get child table data')
            raise dataent.PermissionError(doctype)

        check_parent_permission(kwargs.get('parent'), doctype)
        del kwargs['parent']

    return DatabaseQuery(doctype).execute(None, *args, **kwargs)
Exemple #9
0
def getdoc(doctype, name, user=None):
    """
	Loads a doclist for a given document. This method is called directly from the client.
	Requries "doctype", "name" as form variables.
	Will also call the "onload" method on the document.
	"""

    if not (doctype and name):
        raise Exception('doctype and name required!')

    if not name:
        name = doctype

    if not dataent.db.exists(doctype, name):
        return []

    try:
        doc = dataent.get_doc(doctype, name)
        run_onload(doc)

        if not doc.has_permission("read"):
            dataent.flags.error_message = _(
                'Insufficient Permission for {0}').format(
                    dataent.bold(doctype + ' ' + name))
            raise dataent.PermissionError(("read", doctype, name))

        doc.apply_fieldlevel_read_permissions()

        # add file list
        doc.add_viewed()
        get_docinfo(doc)

    except Exception:
        dataent.errprint(dataent.utils.get_traceback())
        raise

    if doc and not name.startswith('_'):
        dataent.get_user().update_recent(doctype, name)

    doc.add_seen()

    dataent.response.docs.append(doc)
Exemple #10
0
def delete_multiple(web_form_name, docnames):
    web_form = dataent.get_doc("Web Form", web_form_name)

    docnames = json.loads(docnames)

    allowed_docnames = []
    restricted_docnames = []

    for docname in docnames:
        owner = dataent.db.get_value(web_form.doc_type, docname, "owner")
        if dataent.session.user == owner and web_form.allow_delete:
            allowed_docnames.append(docname)
        else:
            restricted_docnames.append(docname)

    for docname in allowed_docnames:
        dataent.delete_doc(web_form.doc_type, docname, ignore_permissions=True)

    if restricted_docnames:
        raise dataent.PermissionError(
            "You do not have permisssion to delete " +
            ", ".join(restricted_docnames))
Exemple #11
0
    def execute(self,
                query=None,
                fields=None,
                filters=None,
                or_filters=None,
                docstatus=None,
                group_by=None,
                order_by=None,
                limit_start=False,
                limit_page_length=None,
                as_list=False,
                with_childnames=False,
                debug=False,
                ignore_permissions=False,
                user=None,
                with_comment_count=False,
                join='left join',
                distinct=False,
                start=None,
                page_length=None,
                limit=None,
                ignore_ifnull=False,
                save_user_settings=False,
                save_user_settings_fields=False,
                update=None,
                add_total_row=None,
                user_settings=None,
                reference_doctype=None):
        if not ignore_permissions and not dataent.has_permission(
                self.doctype, "read", user=user):
            dataent.flags.error_message = _(
                'Insufficient Permission for {0}').format(
                    dataent.bold(self.doctype))
            raise dataent.PermissionError(self.doctype)

        # filters and fields swappable
        # its hard to remember what comes first
        if (isinstance(fields, dict) or (isinstance(fields, list) and fields
                                         and isinstance(fields[0], list))):
            # if fields is given as dict/list of list, its probably filters
            filters, fields = fields, filters

        elif fields and isinstance(filters, list) \
         and len(filters) > 1 and isinstance(filters[0], string_types):
            # if `filters` is a list of strings, its probably fields
            filters, fields = fields, filters

        if fields:
            self.fields = fields
        else:
            self.fields = ["`tab{0}`.`name`".format(self.doctype)]

        if start: limit_start = start
        if page_length: limit_page_length = page_length
        if limit: limit_page_length = limit

        self.filters = filters or []
        self.or_filters = or_filters or []
        self.docstatus = docstatus or []
        self.group_by = group_by
        self.order_by = order_by
        self.limit_start = 0 if (limit_start is False) else cint(limit_start)
        self.limit_page_length = cint(
            limit_page_length) if limit_page_length else None
        self.with_childnames = with_childnames
        self.debug = debug
        self.join = join
        self.distinct = distinct
        self.as_list = as_list
        self.ignore_ifnull = ignore_ifnull
        self.flags.ignore_permissions = ignore_permissions
        self.user = user or dataent.session.user
        self.update = update
        self.user_settings_fields = copy.deepcopy(self.fields)

        # for contextual user permission check
        # to determine which user permission is applicable on link field of specific doctype
        self.reference_doctype = reference_doctype or self.doctype

        if user_settings:
            self.user_settings = json.loads(user_settings)

        if query:
            result = self.run_custom_query(query)
        else:
            result = self.build_and_run()

        if with_comment_count and not as_list and self.doctype:
            self.add_comment_count(result)

        if save_user_settings:
            self.save_user_settings_fields = save_user_settings_fields
            self.update_user_settings()

        return result
Exemple #12
0
def make(doctype=None,
         name=None,
         content=None,
         subject=None,
         sent_or_received="Sent",
         sender=None,
         sender_full_name=None,
         recipients=None,
         communication_medium="Email",
         send_email=False,
         print_html=None,
         print_format=None,
         attachments='[]',
         send_me_a_copy=False,
         cc=None,
         bcc=None,
         flags=None,
         read_receipt=None,
         print_letterhead=True):
    """Make a new communication.

	:param doctype: Reference DocType.
	:param name: Reference Document name.
	:param content: Communication body.
	:param subject: Communication subject.
	:param sent_or_received: Sent or Received (default **Sent**).
	:param sender: Communcation sender (default current user).
	:param recipients: Communication recipients as list.
	:param communication_medium: Medium of communication (default **Email**).
	:param send_mail: Send via email (default **False**).
	:param print_html: HTML Print format to be sent as attachment.
	:param print_format: Print Format name of parent document to be sent as attachment.
	:param attachments: List of attachments as list of files or JSON string.
	:param send_me_a_copy: Send a copy to the sender (default **False**).
	"""

    is_error_report = (doctype == "User" and name == dataent.session.user
                       and subject == "Error Report")
    send_me_a_copy = cint(send_me_a_copy)

    if doctype and name and not is_error_report and not dataent.has_permission(
            doctype, "email",
            name) and not (flags or {}).get('ignore_doctype_permissions'):
        raise dataent.PermissionError(
            "You are not allowed to send emails related to: {doctype} {name}".
            format(doctype=doctype, name=name))

    if not sender:
        sender = get_formatted_email(dataent.session.user)

    comm = dataent.get_doc({
        "doctype": "Communication",
        "subject": subject,
        "content": content,
        "sender": sender,
        "sender_full_name": sender_full_name,
        "recipients": recipients,
        "cc": cc or None,
        "bcc": bcc or None,
        "communication_medium": communication_medium,
        "sent_or_received": sent_or_received,
        "reference_doctype": doctype,
        "reference_name": name,
        "message_id": get_message_id().strip(" <>"),
        "read_receipt": read_receipt,
        "has_attachment": 1 if attachments else 0
    })
    comm.insert(ignore_permissions=True)

    if not doctype:
        # if no reference given, then send it against the communication
        comm.db_set(
            dict(reference_doctype='Communication', reference_name=comm.name))

    if isinstance(attachments, string_types):
        attachments = json.loads(attachments)

    # if not committed, delayed task doesn't find the communication
    if attachments:
        add_attachments("Communication", comm.name, attachments)

    dataent.db.commit()

    if cint(send_email):
        dataent.flags.print_letterhead = cint(print_letterhead)
        comm.send(print_html,
                  print_format,
                  attachments,
                  send_me_a_copy=send_me_a_copy)

    return {
        "name":
        comm.name,
        "emails_not_sent_to":
        ", ".join(comm.emails_not_sent_to)
        if hasattr(comm, "emails_not_sent_to") else None
    }