Beispiel #1
0
def get_context(context):
	if frappe.session.user != "Guest" and frappe.session.data.user_type=="System User":
		frappe.local.flags.redirect_location = "/desk"
		raise frappe.Redirect

	# get settings from site config
	context.no_header = True
	context.for_test = 'login.html'
	context["title"] = "Login"
	context["disable_signup"] = frappe.utils.cint(frappe.db.get_value("Website Settings", "Website Settings", "disable_signup"))

	for provider in ("google", "github", "facebook", "frappe"):
		if get_oauth_keys(provider):
			context["{provider}_login".format(provider=provider)] = get_oauth2_authorize_url(provider)
			context["social_login"] = True

	ldap_settings = get_ldap_settings()
	context["ldap_settings"] = ldap_settings

	login_name_placeholder = [_("Email address")]

	if frappe.utils.cint(frappe.get_system_settings("allow_login_using_mobile_number")):
		login_name_placeholder.append(_("Mobile number"))

	if frappe.utils.cint(frappe.get_system_settings("allow_login_using_user_name")):
		login_name_placeholder.append(_("Username"))

	context['login_name_placeholder'] = ' {0} '.format(_('or')).join(login_name_placeholder)

	return context
Beispiel #2
0
def get_user_permission_doctypes(user_permission_doctypes, user_permissions):
	"""returns a list of list like [["User", "Blog Post"], ["User"]]"""
	if cint(frappe.get_system_settings('ignore_user_permissions_if_missing')):
		# select those user permission doctypes for which user permissions exist!
		user_permission_doctypes = [
			list(set(doctypes).intersection(set(user_permissions.keys())))
			for doctypes in user_permission_doctypes]

	if len(user_permission_doctypes) > 1:
		# OPTIMIZATION
		# if intersection exists, use that to reduce the amount of querying
		# for example, [["Blogger", "Blog Category"], ["Blogger"]], should only search in [["Blogger"]] as the first and condition becomes redundant

		common = user_permission_doctypes[0]
		for i in range(1, len(user_permission_doctypes), 1):
			common = list(set(common).intersection(set(user_permission_doctypes[i])))
			if not common:
				break

		if common:
			# is common one of the user_permission_doctypes set?
			for doctypes in user_permission_doctypes:
				# are these lists equal?
				if set(common) == set(doctypes):
					user_permission_doctypes = [common]
					break

	return user_permission_doctypes
Beispiel #3
0
	def add_user_permissions(self, user_permissions, user_permission_doctypes=None):
		user_permission_doctypes = frappe.permissions.get_user_permission_doctypes(user_permission_doctypes, user_permissions)
		meta = frappe.get_meta(self.doctype)
		for doctypes in user_permission_doctypes:
			match_filters = {}
			match_conditions = []
			# check in links
			for df in meta.get_fields_to_check_permissions(doctypes):
				user_permission_values = user_permissions.get(df.options, [])

				cond = 'ifnull(`tab{doctype}`.`{fieldname}`, "")=""'.format(doctype=self.doctype, fieldname=df.fieldname)
				if user_permission_values:
					if not cint(frappe.get_system_settings("apply_strict_user_permissions")):
						condition = cond + " or "
					else:
						condition = ""
					condition += """`tab{doctype}`.`{fieldname}` in ({values})""".format(
						doctype=self.doctype, fieldname=df.fieldname,
						values=", ".join([('"'+frappe.db.escape(v, percent=False)+'"') for v in user_permission_values]))
				else:
					condition = cond

				match_conditions.append("({condition})".format(condition=condition))

				match_filters[df.options] = user_permission_values

			if match_conditions:
				self.match_conditions.append(" and ".join(match_conditions))

			if match_filters:
				self.match_filters.append(match_filters)
Beispiel #4
0
	def add_code(self):
		path = os.path.join(get_module_path(self.module), 'doctype', scrub(self.name))
		def _get_path(fname):
			return os.path.join(path, scrub(fname))

		system_country = frappe.get_system_settings("country")

		self._add_code(_get_path(self.name + '.js'), '__js')
		if system_country:
			self._add_code(_get_path(os.path.join('regional', system_country + '.js')), '__js')
		self._add_code(_get_path(self.name + '.css'), "__css")
		self._add_code(_get_path(self.name + '_list.js'), '__list_js')
		self._add_code(_get_path(self.name + '_calendar.js'), '__calendar_js')
		self._add_code(_get_path(self.name + '_tree.js'), '__tree_js')

		listview_template = _get_path(self.name + '_list.html')
		if os.path.exists(listview_template):
			self.set("__listview_template", get_html_format(listview_template))

		self.add_code_via_hook("doctype_js", "__js")
		self.add_code_via_hook("doctype_list_js", "__list_js")
		self.add_code_via_hook("doctype_tree_js", "__tree_js")
		self.add_code_via_hook("doctype_calendar_js", "__calendar_js")
		self.add_custom_script()
		self.add_html_templates(path)
Beispiel #5
0
def get_region(company=None):
	'''Return the default country based on flag, company or global settings

	You can also set global company flag in `frappe.flags.company`
	'''
	if company or frappe.flags.company:
		return frappe.db.get_value('Company',
			company or frappe.flags.company, 'country')
	elif frappe.flags.country:
		return frappe.flags.country
	else:
		return frappe.get_system_settings('country')
Beispiel #6
0
def get_region(company=None):
    '''Return the default country based on flag, company or global settings

	You can also set global company flag in `frappe.flags.company`
	'''
    if company or frappe.flags.company:
        return frappe.db.get_value('Company', company or frappe.flags.company,
                                   'country')
    elif frappe.flags.country:
        return frappe.flags.country
    else:
        return frappe.get_system_settings('country')
Beispiel #7
0
	def validate_ip_address(self):
		"""check if IP Address is valid"""
		user = frappe.get_doc("User", self.user)
		ip_list = user.get_restricted_ip_list()
		if not ip_list:
			return

		bypass_restrict_ip_check = 0
		# check if two factor auth is enabled
		enabled = int(frappe.get_system_settings('enable_two_factor_auth') or 0)
		if enabled:
			#check if bypass restrict ip is enabled for all users
			bypass_restrict_ip_check = int(frappe.get_system_settings('bypass_restrict_ip_check_if_2fa_enabled') or 0)
			if not bypass_restrict_ip_check:
				#check if bypass restrict ip is enabled for login user
				bypass_restrict_ip_check = int(frappe.db.get_value('User', self.user, 'bypass_restrict_ip_check_if_2fa_enabled') or 0)
		for ip in ip_list:
			if frappe.local.request_ip.startswith(ip) or bypass_restrict_ip_check:
				return

		frappe.throw(_("Not allowed from this IP Address"), frappe.AuthenticationError)
Beispiel #8
0
def get_region(company=None):
    """Return the default country based on flag, company or global settings

	You can also set global company flag in `frappe.flags.company`
	"""
    if company or frappe.flags.company:
        return frappe.get_cached_value("Company", company
                                       or frappe.flags.company, "country")
    elif frappe.flags.country:
        return frappe.flags.country
    else:
        return frappe.get_system_settings("country")
Beispiel #9
0
	def save_file(self, content=None, decode=False, ignore_existing_file_check=False):
		file_exists = False
		self.content = content

		if decode:
			if isinstance(content, text_type):
				self.content = content.encode("utf-8")

			if b"," in self.content:
				self.content = self.content.split(b",")[1]
			self.content = base64.b64decode(self.content)

		if not self.is_private:
			self.is_private = 0

		self.content_type = mimetypes.guess_type(self.file_name)[0]

		self.file_size = self.check_max_file_size()

		if (
			self.content_type and "image" in self.content_type
			and frappe.get_system_settings("strip_exif_metadata_from_uploaded_images")
		):
			self.content = strip_exif_data(self.content, self.content_type)

		self.content_hash = get_content_hash(self.content)

		duplicate_file = None

		# check if a file exists with the same content hash and is also in the same folder (public or private)
		if not ignore_existing_file_check:
			duplicate_file = frappe.get_value("File", {
					"content_hash": self.content_hash,
					"is_private": self.is_private
				},
				["file_url", "name"], as_dict=True)

		if duplicate_file:
			file_doc = frappe.get_cached_doc('File', duplicate_file.name)
			if file_doc.exists_on_disk():
				self.file_url  = duplicate_file.file_url
				file_exists = True

		if os.path.exists(encode(get_files_path(self.file_name, is_private=self.is_private))):
			self.file_name = get_file_name(self.file_name, self.content_hash[-6:])

		if not file_exists:
			call_hook_method("before_write_file", file_size=self.file_size)
			write_file_method = get_hook_method('write_file')
			if write_file_method:
				return write_file_method(self)
			return self.save_file_on_filesystem()
Beispiel #10
0
def upload_file():
	if frappe.session.user == 'Guest':
		if frappe.get_system_settings('allow_guests_to_upload_files'):
			ignore_permissions = True
		else:
			return
	else:
		ignore_permissions = False

	files = frappe.request.files
	is_private = frappe.form_dict.is_private
	doctype = frappe.form_dict.doctype
	docname = frappe.form_dict.docname
	fieldname = frappe.form_dict.fieldname
	file_url = frappe.form_dict.file_url
	folder = frappe.form_dict.folder or 'Home'
	method = frappe.form_dict.method
	content = None
	filename = None

	if 'file' in files:
		file = files['file']
		content = file.stream.read()
		filename = file.filename

	frappe.local.uploaded_file = content
	frappe.local.uploaded_filename = filename

	if frappe.session.user == 'Guest':
		import mimetypes
		filetype = mimetypes.guess_type(filename)[0]
		if filetype not in ['image/png', 'image/jpeg', 'application/pdf']:
			frappe.throw("You can only upload JPG, PNG or PDF files.")

	if method:
		method = frappe.get_attr(method)
		is_whitelisted(method)
		return method()
	else:
		ret = frappe.get_doc({
			"doctype": "File",
			"attached_to_doctype": doctype,
			"attached_to_name": docname,
			"attached_to_field": fieldname,
			"folder": folder,
			"file_name": filename,
			"file_url": file_url,
			"is_private": cint(is_private),
			"content": content
		})
		ret.save(ignore_permissions=ignore_permissions)
		return ret
Beispiel #11
0
def get_context(context):
	if frappe.session.user != "Guest":
		frappe.local.flags.redirect_location = "/" if frappe.session.data.user_type=="Website User" else "/desk"
		raise frappe.Redirect

	# get settings from site config
	context.no_header = True
	context.for_test = 'login.html'
	context["title"] = "Login"
	context["provider_logins"] = []
	context["disable_signup"] = frappe.utils.cint(frappe.db.get_value("Website Settings", "Website Settings", "disable_signup"))
	providers = [i.name for i in frappe.get_all("Social Login Key", filters={"enable_social_login":1})]
	for provider in providers:
		client_id, base_url = frappe.get_value("Social Login Key", provider, ["client_id", "base_url"])
		client_secret = get_decrypted_password("Social Login Key", provider, "client_secret")
		icon = get_icon_html(frappe.get_value("Social Login Key", provider, "icon"), small=True)
		if (get_oauth_keys(provider) and client_secret and client_id and base_url):
			context.provider_logins.append({
				"name": provider,
				"provider_name": frappe.get_value("Social Login Key", provider, "provider_name"),
				"auth_url": get_oauth2_authorize_url(provider),
				"icon": icon
			})
			context["social_login"] = True

	ldap_settings = get_ldap_settings()
	context["ldap_settings"] = ldap_settings

	login_name_placeholder = [_("Email address")]

	if frappe.utils.cint(frappe.get_system_settings("allow_login_using_mobile_number")):
		login_name_placeholder.append(_("Mobile number"))

	if frappe.utils.cint(frappe.get_system_settings("allow_login_using_user_name")):
		login_name_placeholder.append(_("Username"))

	context['login_name_placeholder'] = ' {0} '.format(_('or')).join(login_name_placeholder)

	return context
Beispiel #12
0
def get_context(context):
	if frappe.session.user != "Guest":
		frappe.local.flags.redirect_location = "/dashboard" if frappe.session.data.user_type=="Website User" else "/desk"
		raise frappe.Redirect

	# get settings from site config
	context.no_header = True
	context.for_test = 'login.html'
	context["title"] = "Login"
	context["provider_logins"] = []
	context["disable_signup"] = frappe.utils.cint(frappe.db.get_value("Website Settings", "Website Settings", "disable_signup"))
	providers = [i.name for i in frappe.get_all("Social Login Key", filters={"enable_social_login":1})]
	for provider in providers:
		client_id, base_url = frappe.get_value("Social Login Key", provider, ["client_id", "base_url"])
		client_secret = get_decrypted_password("Social Login Key", provider, "client_secret")
		icon = get_icon_html(frappe.get_value("Social Login Key", provider, "icon"), small=True)
		if (get_oauth_keys(provider) and client_secret and client_id and base_url):
			context.provider_logins.append({
				"name": provider,
				"provider_name": frappe.get_value("Social Login Key", provider, "provider_name"),
				"auth_url": get_oauth2_authorize_url(provider),
				"icon": icon
			})
			context["social_login"] = True
	ldap_settings = LDAPSettings.get_ldap_client_settings()
	context["ldap_settings"] = ldap_settings

	login_name_placeholder = [_("Email Address")]

	if frappe.utils.cint(frappe.get_system_settings("allow_login_using_mobile_number")):
		login_name_placeholder.append(_("Mobile number"))

	if frappe.utils.cint(frappe.get_system_settings("allow_login_using_user_name")):
		login_name_placeholder.append(_("Username"))

	context['login_name_placeholder'] = ' {0} '.format(_('or')).join(login_name_placeholder)

	return context
Beispiel #13
0
def _get_amended_name(doc):
    if frappe.get_system_settings('use_original_name_for_amended_document',
                                  ignore_if_not_exists=True):
        name, _ = NameParser(doc).parse_amended_from()
    else:
        am_id = 1
        am_prefix = doc.amended_from
        if frappe.db.get_value(doc.doctype, doc.amended_from, "amended_from"):
            am_id = cint(doc.amended_from.split("-")[-1]) + 1
            am_prefix = "-".join(
                doc.amended_from.split("-")[:-1])  # except the last hyphen

        name = am_prefix + "-" + str(am_id)
    return name
Beispiel #14
0
def get_context(context):
    if frappe.session.user != "Guest" and frappe.session.data.user_type == "System User":
        frappe.local.flags.redirect_location = "/desk"
        raise frappe.Redirect

    # get settings from site config

    context.no_header = True
    context.for_test = 'login.html'
    context["title"] = "Login"
    context["disable_signup"] = frappe.utils.cint(
        frappe.db.get_value("Website Settings", "Website Settings",
                            "disable_signup"))

    for provider in ("google", "github", "facebook", "frappe"):
        if get_oauth_keys(provider):
            context["{provider}_login".format(
                provider=provider)] = get_oauth2_authorize_url(provider)
            context["social_login"] = True

    ldap_settings = get_ldap_settings()
    context["ldap_settings"] = ldap_settings

    login_name_placeholder = [_("Email address")]

    if frappe.utils.cint(
            frappe.get_system_settings("allow_login_using_mobile_number")):
        login_name_placeholder.append(_("Mobile number"))

    if frappe.utils.cint(
            frappe.get_system_settings("allow_login_using_user_name")):
        login_name_placeholder.append(_("Username"))

    context['login_name_placeholder'] = ' {0} '.format(
        _('or')).join(login_name_placeholder)

    return context
Beispiel #15
0
    def add_user_permissions(self, user_permissions):
        meta = frappe.get_meta(self.doctype)
        doctype_link_fields = []
        doctype_link_fields = meta.get_link_fields()
        doctype_link_fields.append(
            dict(
                options=self.doctype,
                fieldname='name',
            ))
        # appended current doctype with fieldname as 'name' to
        # and condition on doc name if user permission is found for current doctype

        match_filters = {}
        match_conditions = []
        for df in doctype_link_fields:
            user_permission_values = user_permissions.get(
                df.get('options'), {})
            if df.get('ignore_user_permissions'): continue

            empty_value_condition = "ifnull(`tab{doctype}`.`{fieldname}`, '')=''".format(
                doctype=self.doctype, fieldname=df.get('fieldname'))

            if (user_permission_values.get("docs", [])
                    and not self.doctype in user_permission_values.get(
                        "skip_for_doctype", [])):
                if frappe.get_system_settings("apply_strict_user_permissions"):
                    condition = ""
                else:
                    condition = empty_value_condition + " or "

                condition += """`tab{doctype}`.`{fieldname}` in ({values})""".format(
                    doctype=self.doctype,
                    fieldname=df.get('fieldname'),
                    values=", ".join([
                        (frappe.db.escape(v, percent=False))
                        for v in user_permission_values.get("docs")
                    ]))

                match_conditions.append(
                    "({condition})".format(condition=condition))
                match_filters[df.get('options')] = user_permission_values.get(
                    "docs")

        if match_conditions:
            self.match_conditions.append(" and ".join(match_conditions))

        if match_filters:
            self.match_filters.append(match_filters)
Beispiel #16
0
    def add_user_permissions(self,
                             user_permissions,
                             user_permission_doctypes=None):
        user_permission_doctypes = frappe.permissions.get_user_permission_doctypes(
            user_permission_doctypes, user_permissions)
        meta = frappe.get_meta(self.doctype)
        for doctypes in user_permission_doctypes:
            match_filters = {}
            match_conditions = []
            # check in links
            for df in meta.get_fields_to_check_permissions(doctypes):
                user_permission_values = user_permissions.get(df.options, [])

                cond = 'ifnull(`tab{doctype}`.`{fieldname}`, "")=""'.format(
                    doctype=self.doctype, fieldname=df.fieldname)
                if user_permission_values:
                    if not cint(
                            frappe.get_system_settings(
                                "apply_strict_user_permissions")):
                        condition = cond + " or "
                    else:
                        condition = ""
                    condition += """`tab{doctype}`.`{fieldname}` in ({values})""".format(
                        doctype=self.doctype,
                        fieldname=df.fieldname,
                        values=", ".join([
                            ('"' + frappe.db.escape(v, percent=False) + '"')
                            for v in user_permission_values
                        ]))
                else:
                    condition = cond

                match_conditions.append(
                    "({condition})".format(condition=condition))

                match_filters[df.options] = user_permission_values

            if match_conditions:
                self.match_conditions.append(" and ".join(match_conditions))

            if match_filters:
                self.match_filters.append(match_filters)
Beispiel #17
0
def make_file_document(
        file_key, doctype=None, docname=None, fieldname=None, is_private=None,
        ignore_permissions=False):
    user = None
    if not ignore_permissions and frappe.session.user == 'Guest':
        if frappe.get_system_settings('allow_guests_to_upload_files'):
            ignore_permissions = True
        else:
            raise frappe.PermissionError("Guest uploads are not allowed")
    else:
        user = frappe.get_doc("User", frappe.session.user)

    files = frappe.request.files
    content = None
    filename = None

    if file_key in files:
        file = files[file_key]
        content = file.stream.read()
        filename = file.filename

    frappe.local.uploaded_file = content
    frappe.local.uploaded_filename = filename

    if frappe.session.user == 'Guest' or (user and not user.has_desk_access()):
        import mimetypes
        filetype = mimetypes.guess_type(filename)[0]
        if filetype not in ALLOWED_MIMETYPES:
            frappe.throw(frappe._("You can only upload JPG, PNG, PDF, or Microsoft documents."))

    ret = frappe.get_doc({
        "doctype": "File",
        "attached_to_doctype": doctype,
        "attached_to_name": docname,
        "attached_to_field": fieldname,
        "file_name": filename,
        "is_private": cint(is_private),
        "content": content
    })
    ret.save(ignore_permissions=ignore_permissions)
    return ret
Beispiel #18
0
    def add_code(self):
        if self.custom:
            return

        path = os.path.join(get_module_path(self.module), "doctype",
                            scrub(self.name))

        def _get_path(fname):
            return os.path.join(path, scrub(fname))

        system_country = frappe.get_system_settings("country")

        self._add_code(_get_path(self.name + ".js"), "__js")
        if system_country:
            self._add_code(
                _get_path(os.path.join("regional", system_country + ".js")),
                "__js")

        self._add_code(_get_path(self.name + ".css"), "__css")
        self._add_code(_get_path(self.name + "_list.js"), "__list_js")
        if system_country:
            self._add_code(
                _get_path(os.path.join("regional",
                                       system_country + "_list.js")),
                "__list_js")

        self._add_code(_get_path(self.name + "_calendar.js"), "__calendar_js")
        self._add_code(_get_path(self.name + "_tree.js"), "__tree_js")

        listview_template = _get_path(self.name + "_list.html")
        if os.path.exists(listview_template):
            self.set("__listview_template", get_html_format(listview_template))

        self.add_code_via_hook("doctype_js", "__js")
        self.add_code_via_hook("doctype_list_js", "__list_js")
        self.add_code_via_hook("doctype_tree_js", "__tree_js")
        self.add_code_via_hook("doctype_calendar_js", "__calendar_js")
        self.add_html_templates(path)
Beispiel #19
0
	def get_onboarding_doc(self):
		# Check if onboarding is enabled
		if not frappe.get_system_settings("enable_onboarding"):
			return None

		if not self.doc.onboarding:
			return None

		if frappe.db.get_value("Module Onboarding", self.doc.onboarding, "is_complete"):
			return None

		doc = frappe.get_doc("Module Onboarding", self.doc.onboarding)

		# Check if user is allowed
		allowed_roles = set(doc.get_allowed_roles())
		user_roles = set(frappe.get_roles())
		if not allowed_roles & user_roles:
			return None

		# Check if already complete
		if doc.check_completion():
			return None

		return doc
def has_user_permission(doc, user=None, verbose=False):
    '''Returns True if User is allowed to view considering User Permissions'''
    from frappe.core.doctype.user_permission.user_permission import get_user_permissions
    user_permissions = get_user_permissions(user)

    if not user_permissions: return True

    # user can create own role permissions, so nothing applies
    if get_role_permissions('User Permission', user=user).get('write'):
        return True

    apply_strict_user_permissions = frappe.get_system_settings(
        'apply_strict_user_permissions')

    if doc.get('doctype') in user_permissions:
        if (doc.get('name') not in user_permissions[doc.get('doctype')].get(
                "docs", []) and not doc.get('doctype')
                in user_permissions[doc.get('doctype')].get(
                    "skip_for_doctype", [])):
            # don't have user permissions on the doc itself!
            if verbose:
                msgprint(
                    _('Not allowed for {0} = {1}').format(
                        _(doc.get('doctype')), doc.get('name')))
            return False

    def check_user_permission(d):
        meta = frappe.get_meta(d.get("doctype"))

        # check all link fields for user permissions
        for field in meta.get_link_fields():
            # if this type is restricted
            if field.ignore_user_permissions: continue

            if (field.options in user_permissions and not d.get("doctype")
                    in user_permissions[field.options].get(
                        "skip_for_doctype", [])):
                if not apply_strict_user_permissions:
                    # ignore if link is not set
                    if not d.get(field.fieldname):
                        continue

                if not d.get(field.fieldname) in user_permissions.get(
                        field.options, {}).get("docs", []):
                    if d.get('parentfield'):
                        # "Not allowed for Company = Restricted Company in Row 3"
                        msg = _('Not allowed for {0} = {1} in Row {2}').format(
                            _(field.options), d.get(field.fieldname), d.idx)
                    else:
                        # "Not allowed for Company = Restricted Company"
                        msg = _('Not allowed for {0} = {1}').format(
                            _(field.options), d.get(field.fieldname))

                    if verbose: msgprint(msg)

                    return False
        return True

    result = check_user_permission(doc)
    if not result:
        return False

    for d in doc.get_all_children():
        if not check_user_permission(d):
            return False

    return True
Beispiel #21
0
    def add_user_permissions(self, user_permissions):
        meta = frappe.get_meta(self.doctype)
        doctype_link_fields = []
        doctype_link_fields = meta.get_link_fields()

        # append current doctype with fieldname as 'name' as first link field
        doctype_link_fields.append(
            dict(
                options=self.doctype,
                fieldname="name",
            ))

        match_filters = {}
        match_conditions = []
        for df in doctype_link_fields:
            if df.get("ignore_user_permissions"):
                continue

            user_permission_values = user_permissions.get(
                df.get("options"), {})

            if user_permission_values:
                docs = []
                if frappe.get_system_settings("apply_strict_user_permissions"):
                    condition = ""
                else:
                    empty_value_condition = "ifnull(`tab{doctype}`.`{fieldname}`, '')=''".format(
                        doctype=self.doctype, fieldname=df.get("fieldname"))
                    condition = empty_value_condition + " or "

                for permission in user_permission_values:
                    if not permission.get("applicable_for"):
                        docs.append(permission.get("doc"))

                    # append docs based on user permission applicable on reference doctype

                    # this is useful when getting list of docs from a link field

                    # in this case parent doctype of the link
                    # will be the reference doctype

                    elif df.get(
                            "fieldname") == "name" and self.reference_doctype:
                        if permission.get(
                                "applicable_for") == self.reference_doctype:
                            docs.append(permission.get("doc"))

                    elif permission.get("applicable_for") == self.doctype:
                        docs.append(permission.get("doc"))

                if docs:
                    condition += "`tab{doctype}`.`{fieldname}` in ({values})".format(
                        doctype=self.doctype,
                        fieldname=df.get("fieldname"),
                        values=", ".join([(frappe.db.escape(doc,
                                                            percent=False))
                                          for doc in docs]),
                    )

                    match_conditions.append(
                        "({condition})".format(condition=condition))
                    match_filters[df.get("options")] = docs

        if match_conditions:
            self.match_conditions.append(" and ".join(match_conditions))

        if match_filters:
            self.match_filters.append(match_filters)
Beispiel #22
0
    def add_user_permissions(self, user_permissions):
        meta = frappe.get_meta(self.doctype)
        doctype_link_fields = []
        doctype_link_fields = meta.get_link_fields()
        doctype_link_fields.append(
            dict(
                options=self.doctype,
                fieldname='name',
            ))
        # appended current doctype with fieldname as 'name' to
        # and condition on doc name if user permission is found for current doctype

        match_filters = {}
        match_conditions = []
        for df in doctype_link_fields:
            user_permission_values = user_permissions.get(
                df.get('options'), {})

            if df.get('ignore_user_permissions'): continue

            empty_value_condition = 'ifnull(`tab{doctype}`.`{fieldname}`, "")=""'.format(
                doctype=self.doctype, fieldname=df.get('fieldname'))

            if user_permission_values:
                docs = []
                if frappe.get_system_settings("apply_strict_user_permissions"):
                    condition = ""
                else:
                    condition = empty_value_condition + " or "

                for permission in user_permission_values:
                    if not permission.get('applicable_for'):
                        docs.append(permission.get('doc'))

                    # append docs based on user permission applicable on reference doctype

                    # This is useful when getting list of doc from a link field
                    # in this case parent doctype of the link will be the
                    # will be the reference doctype

                    elif df.get(
                            'fieldname') == 'name' and self.reference_doctype:
                        if permission.get(
                                'applicable_for') == self.reference_doctype:
                            docs.append(permission.get('doc'))

                    elif permission.get('applicable_for') == self.doctype:
                        docs.append(permission.get('doc'))

                if docs:
                    condition += "`tab{doctype}`.`{fieldname}` in ({values})".format(
                        doctype=self.doctype,
                        fieldname=df.get('fieldname'),
                        values=", ".join([
                            ('"' + frappe.db.escape(doc, percent=False) + '"')
                            for doc in docs
                        ]))

                    match_conditions.append(
                        "({condition})".format(condition=condition))
                    match_filters[df.get('options')] = docs

        if match_conditions:
            self.match_conditions.append(" and ".join(match_conditions))

        if match_filters:
            self.match_filters.append(match_filters)
Beispiel #23
0
	def add_user_permissions(self, user_permissions):
		meta = frappe.get_meta(self.doctype)
		doctype_link_fields = []
		doctype_link_fields = meta.get_link_fields()
		doctype_link_fields.append(dict(
			options=self.doctype,
			fieldname='name',
		))
		# appended current doctype with fieldname as 'name' to
		# and condition on doc name if user permission is found for current doctype

		match_filters = {}
		match_conditions = []
		for df in doctype_link_fields:
			user_permission_values = user_permissions.get(df.get('options'), {})

			if df.get('ignore_user_permissions'): continue

			empty_value_condition = 'ifnull(`tab{doctype}`.`{fieldname}`, "")=""'.format(
				doctype=self.doctype, fieldname=df.get('fieldname')
			)

			if user_permission_values:
				docs = []
				if frappe.get_system_settings("apply_strict_user_permissions"):
					condition = ""
				else:
					condition = empty_value_condition + " or "

				for permission in user_permission_values:
					if not permission.get('applicable_for'):
						docs.append(permission.get('doc'))

					# append docs based on user permission applicable on reference doctype

					# This is useful when getting list of doc from a link field
						# in this case parent doctype of the link will be the
						# will be the reference doctype

					elif df.get('fieldname') == 'name' and self.reference_doctype:
						if permission.get('applicable_for') == self.reference_doctype:
							docs.append(permission.get('doc'))

					elif permission.get('applicable_for') == self.doctype:
						docs.append(permission.get('doc'))

				if docs:
					condition += "`tab{doctype}`.`{fieldname}` in ({values})".format(
						doctype=self.doctype,
						fieldname=df.get('fieldname'),
						values=", ".join(
							[('"' + frappe.db.escape(doc, percent=False) + '"') for doc in docs])
						)

					match_conditions.append("({condition})".format(condition=condition))
					match_filters[df.get('options')] = docs

		if match_conditions:
			self.match_conditions.append(" and ".join(match_conditions))

		if match_filters:
			self.match_filters.append(match_filters)
Beispiel #24
0
	context["title"] = "Login"
	context["disable_signup"] = frappe.utils.cint(frappe.db.get_value("Website Settings", "Website Settings", "disable_signup"))

	for provider in ("google", "github", "facebook", "frappe"):
		if get_oauth_keys(provider):
			context["{provider}_login".format(provider=provider)] = get_oauth2_authorize_url(provider)
			context["social_login"] = True

	ldap_settings = get_ldap_settings()
	context["ldap_settings"] = ldap_settings

<<<<<<< HEAD
=======
	login_name_placeholder = [_("Email address")]

	if frappe.utils.cint(frappe.get_system_settings("allow_login_using_mobile_number")):
		login_name_placeholder.append(_("Mobile number"))

	if frappe.utils.cint(frappe.get_system_settings("allow_login_using_user_name")):
		login_name_placeholder.append(_("Username"))

	context['login_name_placeholder'] = ' {0} '.format(_('or')).join(login_name_placeholder)

>>>>>>> 176d241496ede1357a309fa44a037b757a252581
	return context

@frappe.whitelist(allow_guest=True)
def login_via_google(code, state):
	login_via_oauth2("google", code, state, decoder=json.loads)

@frappe.whitelist(allow_guest=True)
Beispiel #25
0
def upload_file():
    user = None
    if frappe.session.user == 'Guest':
        if frappe.get_system_settings('allow_guests_to_upload_files'):
            ignore_permissions = True
        else:
            return
    else:
        user = frappe.get_doc("User", frappe.session.user)
        ignore_permissions = False

    files = frappe.request.files
    is_private = frappe.form_dict.is_private
    doctype = frappe.form_dict.doctype
    docname = frappe.form_dict.docname
    fieldname = frappe.form_dict.fieldname
    file_url = frappe.form_dict.file_url
    folder = frappe.form_dict.folder or 'Home'
    method = frappe.form_dict.method
    filename = frappe.form_dict.file_name
    optimize = frappe.form_dict.optimize
    content = None

    if 'file' in files:
        file = files['file']
        content = file.stream.read()
        filename = file.filename

        content_type = guess_type(filename)[0]
        if optimize and content_type.startswith("image/"):
            args = {"content": content, "content_type": content_type}
            if frappe.form_dict.max_width:
                args["max_width"] = int(frappe.form_dict.max_width)
            if frappe.form_dict.max_height:
                args["max_height"] = int(frappe.form_dict.max_height)
            content = optimize_image(**args)

    frappe.local.uploaded_file = content
    frappe.local.uploaded_filename = filename

    if not file_url and (frappe.session.user == "Guest" or
                         (user and not user.has_desk_access())):
        filetype = guess_type(filename)[0]
        if filetype not in ALLOWED_MIMETYPES:
            frappe.throw(
                _("You can only upload JPG, PNG, PDF, or Microsoft documents.")
            )

    if method:
        method = frappe.get_attr(method)
        is_whitelisted(method)
        return method()
    else:
        ret = frappe.get_doc({
            "doctype": "File",
            "attached_to_doctype": doctype,
            "attached_to_name": docname,
            "attached_to_field": fieldname,
            "folder": folder,
            "file_name": filename,
            "file_url": file_url,
            "is_private": cint(is_private),
            "content": content
        })
        ret.save(ignore_permissions=ignore_permissions)
        return ret
Beispiel #26
0
def get_context(context):
    redirect_to = frappe.local.request.args.get("redirect-to")

    if frappe.session.user != "Guest":
        if not redirect_to:
            if frappe.session.data.user_type == "Website User":
                redirect_to = get_home_page()
            else:
                redirect_to = "/app"

        if redirect_to != 'login':
            frappe.local.flags.redirect_location = redirect_to
            raise frappe.Redirect

    # get settings from site config
    context.no_header = True
    context.for_test = 'login.html'
    context["title"] = "Login"
    context["provider_logins"] = []
    context["disable_signup"] = frappe.utils.cint(
        frappe.db.get_single_value("Website Settings", "disable_signup"))
    context["logo"] = (frappe.db.get_single_value('Website Settings',
                                                  'app_logo')
                       or frappe.get_hooks("app_logo_url")[-1])
    context["app_name"] = (frappe.db.get_single_value('Website Settings',
                                                      'app_name')
                           or frappe.get_system_settings("app_name")
                           or _("Frappe"))
    providers = [
        i.name for i in frappe.get_all("Social Login Key",
                                       filters={"enable_social_login": 1},
                                       order_by="name")
    ]
    for provider in providers:
        client_id, base_url = frappe.get_value("Social Login Key", provider,
                                               ["client_id", "base_url"])
        client_secret = get_decrypted_password("Social Login Key", provider,
                                               "client_secret")
        provider_name = frappe.get_value("Social Login Key", provider,
                                         "provider_name")

        icon = None
        icon_url = frappe.get_value("Social Login Key", provider, "icon")
        if icon_url:
            if provider_name != "Custom":
                icon = "<img src='{0}' alt={1}>".format(
                    icon_url, provider_name)
            else:
                icon = get_icon_html(icon_url, small=True)

        if (get_oauth_keys(provider) and client_secret and client_id
                and base_url):
            context.provider_logins.append({
                "name":
                provider,
                "provider_name":
                provider_name,
                "auth_url":
                get_oauth2_authorize_url(provider, redirect_to),
                "icon":
                icon
            })
            context["social_login"] = True
    ldap_settings = LDAPSettings.get_ldap_client_settings()
    context["ldap_settings"] = ldap_settings

    login_label = [_("Email")]

    if frappe.utils.cint(
            frappe.get_system_settings("allow_login_using_mobile_number")):
        login_label.append(_("Mobile"))

    if frappe.utils.cint(
            frappe.get_system_settings("allow_login_using_user_name")):
        login_label.append(_("Username"))

    context['login_label'] = ' {0} '.format(_('or')).join(login_label)

    return context
Beispiel #27
0
def get_mapped_doc(from_doctype,
                   from_docname,
                   table_maps,
                   target_doc=None,
                   postprocess=None,
                   ignore_permissions=False,
                   ignore_child_tables=False):

    apply_strict_user_permissions = frappe.get_system_settings(
        "apply_strict_user_permissions")

    # main
    if not target_doc:
        target_doc = frappe.new_doc(table_maps[from_doctype]["doctype"])
    elif isinstance(target_doc, string_types):
        target_doc = frappe.get_doc(json.loads(target_doc))

    if (not apply_strict_user_permissions and not ignore_permissions
            and not target_doc.has_permission("create")):
        target_doc.raise_no_permission_to("create")

    source_doc = frappe.get_doc(from_doctype, from_docname)

    if not ignore_permissions:
        if not source_doc.has_permission("read"):
            source_doc.raise_no_permission_to("read")

    map_doc(source_doc, target_doc, table_maps[source_doc.doctype])

    row_exists_for_parentfield = {}

    # children
    if not ignore_child_tables:
        for df in source_doc.meta.get_table_fields():
            source_child_doctype = df.options
            table_map = table_maps.get(source_child_doctype)

            # if table_map isn't explicitly specified check if both source and target have the same fieldname and same table options and both of them don't have no_copy
            if not table_map:
                target_df = target_doc.meta.get_field(df.fieldname)
                if target_df:
                    target_child_doctype = target_df.options
                    if target_df and target_child_doctype == source_child_doctype and not df.no_copy and not target_df.no_copy:
                        table_map = {"doctype": target_child_doctype}

            if table_map:
                for source_d in source_doc.get(df.fieldname):
                    if "condition" in table_map:
                        if not table_map["condition"](source_d):
                            continue

                    # if children are selected (checked from UI) for this table type,
                    # and this record is not in the selected children, then continue
                    if (frappe.flags.selected_children and
                        (df.fieldname in frappe.flags.selected_children)
                            and source_d.name not in
                            frappe.flags.selected_children[df.fieldname]):
                        continue

                    target_child_doctype = table_map["doctype"]
                    target_parentfield = target_doc.get_parentfield_of_doctype(
                        target_child_doctype)

                    # does row exist for a parentfield?
                    if target_parentfield not in row_exists_for_parentfield:
                        row_exists_for_parentfield[target_parentfield] = (
                            True
                            if target_doc.get(target_parentfield) else False)

                    if table_map.get("add_if_empty") and \
                     row_exists_for_parentfield.get(target_parentfield):
                        continue

                    if table_map.get("filter") and table_map.get("filter")(
                            source_d):
                        continue

                    map_child_doc(source_d, target_doc, table_map, source_doc)

    if postprocess:
        postprocess(source_doc, target_doc)

    target_doc.set_onload("load_after_mapping", True)

    if (apply_strict_user_permissions and not ignore_permissions
            and not target_doc.has_permission("create")):
        target_doc.raise_no_permission_to("create")

    return target_doc
Beispiel #28
0
def has_user_permission(doc, user=None):
    '''Returns True if User is allowed to view considering User Permissions'''
    from frappe.core.doctype.user_permission.user_permission import get_user_permissions
    user_permissions = get_user_permissions(user)

    if not user_permissions:
        # no user permission rules specified for this doctype
        return True

    # user can create own role permissions, so nothing applies
    if get_role_permissions('User Permission', user=user).get('write'):
        return True

    apply_strict_user_permissions = frappe.get_system_settings(
        'apply_strict_user_permissions')

    doctype = doc.get('doctype')
    docname = doc.get('name')

    # STEP 1: ---------------------
    # check user permissions on self
    if doctype in user_permissions:
        allowed_docs = get_allowed_docs_for_doctype(
            user_permissions.get(doctype, []), doctype)

        # if allowed_docs is empty it states that there is no applicable permission under the current doctype

        # only check if allowed_docs is not empty
        if allowed_docs and docname not in allowed_docs:
            # no user permissions for this doc specified
            push_perm_check_log(
                _('Not allowed for {0}: {1}').format(_(doctype), docname))
            return False

    # STEP 2: ---------------------------------
    # check user permissions in all link fields

    def check_user_permission_on_link_fields(d):
        # check user permissions for all the link fields of the given
        # document object d
        #
        # called for both parent and child records

        meta = frappe.get_meta(d.get("doctype"))

        # check all link fields for user permissions
        for field in meta.get_link_fields():

            if field.ignore_user_permissions: continue

            # empty value, do you still want to apply user permissions?
            if not d.get(
                    field.fieldname) and not apply_strict_user_permissions:
                # nah, not strict
                continue

            if field.options not in user_permissions:
                continue

            # get the list of all allowed values for this link
            allowed_docs = get_allowed_docs_for_doctype(
                user_permissions.get(field.options, []), doctype)

            if allowed_docs and d.get(field.fieldname) not in allowed_docs:
                # restricted for this link field, and no matching values found
                # make the right message and exit
                if d.get('parentfield'):
                    # "Not allowed for Company = Restricted Company in Row 3. Restricted field: reference_type"
                    msg = _(
                        'Not allowed for {0}: {1} in Row {2}. Restricted field: {3}'
                    ).format(_(field.options), d.get(field.fieldname), d.idx,
                             field.fieldname)
                else:
                    # "Not allowed for Company = Restricted Company. Restricted field: reference_type"
                    msg = _('Not allowed for {0}: {1}. Restricted field: {2}'
                            ).format(_(field.options), d.get(field.fieldname),
                                     field.fieldname)

                push_perm_check_log(msg)

                return False

        return True

    if not check_user_permission_on_link_fields(doc):
        return False

    for d in doc.get_all_children():
        if not check_user_permission_on_link_fields(d):
            return False

    return True
Beispiel #29
0
def has_user_permission(doc, user=None):
	'''Returns True if User is allowed to view considering User Permissions'''
	from frappe.core.doctype.user_permission.user_permission import get_user_permissions
	user_permissions = get_user_permissions(user)

	if not user_permissions:
		# no user permission rules specified for this doctype
		return True

	# user can create own role permissions, so nothing applies
	if get_role_permissions('User Permission', user=user).get('write'):
		return True

	apply_strict_user_permissions = frappe.get_system_settings('apply_strict_user_permissions')

	doctype = doc.get('doctype')
	docname = doc.get('name')

	# STEP 1: ---------------------
	# check user permissions on self
	if doctype in user_permissions:
		allowed_docs = get_allowed_docs_for_doctype(user_permissions.get(doctype, []), doctype)

		# if allowed_docs is empty it states that there is no applicable permission under the current doctype

		# only check if allowed_docs is not empty
		if allowed_docs and docname not in allowed_docs:
			# no user permissions for this doc specified
			push_perm_check_log(_('Not allowed for {0}: {1}').format(_(doctype), docname))
			return False

	# STEP 2: ---------------------------------
	# check user permissions in all link fields

	def check_user_permission_on_link_fields(d):
		# check user permissions for all the link fields of the given
		# document object d
		#
		# called for both parent and child records

		meta = frappe.get_meta(d.get("doctype"))

		# check all link fields for user permissions
		for field in meta.get_link_fields():

			if field.ignore_user_permissions: continue

			# empty value, do you still want to apply user permissions?
			if not d.get(field.fieldname) and not apply_strict_user_permissions:
				# nah, not strict
				continue

			if field.options not in user_permissions:
				continue

			# get the list of all allowed values for this link
			allowed_docs = get_allowed_docs_for_doctype(user_permissions.get(field.options, []), doctype)

			if allowed_docs and d.get(field.fieldname) not in allowed_docs:
				# restricted for this link field, and no matching values found
				# make the right message and exit
				if d.get('parentfield'):
					# "Not allowed for Company = Restricted Company in Row 3. Restricted field: reference_type"
					msg = _('Not allowed for {0}: {1} in Row {2}. Restricted field: {3}').format(
						_(field.options), d.get(field.fieldname), d.idx, field.fieldname)
				else:
					# "Not allowed for Company = Restricted Company. Restricted field: reference_type"
					msg = _('Not allowed for {0}: {1}. Restricted field: {2}').format(
						_(field.options), d.get(field.fieldname), field.fieldname)

				push_perm_check_log(msg)

				return False

		return True

	if not check_user_permission_on_link_fields(doc):
		return False

	for d in doc.get_all_children():
		if not check_user_permission_on_link_fields(d):
			return False

	return True