Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

291 rinda
8.1 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. import frappe, json
  5. from frappe import _dict
  6. import frappe.share
  7. class User:
  8. """
  9. A user permission object can be accessed as `frappe.get_user()`
  10. """
  11. def __init__(self, name=''):
  12. self.defaults = None
  13. self.name = name or frappe.session.get('user')
  14. self.roles = []
  15. self.all_read = []
  16. self.can_create = []
  17. self.can_read = []
  18. self.can_write = []
  19. self.can_cancel = []
  20. self.can_delete = []
  21. self.can_search = []
  22. self.can_get_report = []
  23. self.can_import = []
  24. self.can_export = []
  25. self.can_print = []
  26. self.can_email = []
  27. self.can_set_user_permissions = []
  28. self.allow_modules = []
  29. self.in_create = []
  30. self.setup_user()
  31. def setup_user(self):
  32. def get_user_doc():
  33. user = None
  34. try:
  35. user = frappe.get_doc("User", self.name).as_dict()
  36. except frappe.DoesNotExistError:
  37. pass
  38. except Exception, e:
  39. # install boo-boo
  40. if e.args[0] != 1146: raise
  41. return user
  42. if not frappe.flags.in_install_db and not frappe.flags.in_test:
  43. user_doc = frappe.cache().hget("user_doc", self.name, get_user_doc)
  44. if user_doc:
  45. self.doc = frappe.get_doc(user_doc)
  46. def get_roles(self):
  47. """get list of roles"""
  48. if not self.roles:
  49. self.roles = get_roles(self.name)
  50. return self.roles
  51. def get_block_modules(self):
  52. """Returns list of blocked modules"""
  53. return [d.module for d in self.doc.block_modules] if self.doc.block_modules else []
  54. def build_doctype_map(self):
  55. """build map of special doctype properties"""
  56. self.doctype_map = {}
  57. for r in frappe.db.sql("""select name, in_create, issingle, istable,
  58. read_only, module from tabDocType""", as_dict=1):
  59. self.doctype_map[r['name']] = r
  60. def build_perm_map(self):
  61. """build map of permissions at level 0"""
  62. self.perm_map = {}
  63. roles = self.get_roles()
  64. for r in frappe.db.sql("""select * from tabDocPerm where docstatus=0
  65. and ifnull(permlevel,0)=0
  66. and role in ({roles})""".format(roles=", ".join(["%s"]*len(roles))), tuple(roles), as_dict=1):
  67. dt = r['parent']
  68. if not dt in self.perm_map:
  69. self.perm_map[dt] = {}
  70. for k in frappe.permissions.rights:
  71. if not self.perm_map[dt].get(k):
  72. self.perm_map[dt][k] = r.get(k)
  73. def build_permissions(self):
  74. """build lists of what the user can read / write / create
  75. quirks:
  76. read_only => Not in Search
  77. in_create => Not in create
  78. """
  79. self.build_doctype_map()
  80. self.build_perm_map()
  81. user_shared = frappe.share.get_shared_doctypes()
  82. for dt in self.doctype_map:
  83. dtp = self.doctype_map[dt]
  84. p = self.perm_map.get(dt, {})
  85. if not p.get("read") and (dt in user_shared):
  86. p["read"] = 1
  87. if not dtp.get('istable'):
  88. if p.get('create') and not dtp.get('issingle'):
  89. if dtp.get('in_create'):
  90. self.in_create.append(dt)
  91. else:
  92. self.can_create.append(dt)
  93. elif p.get('write'):
  94. self.can_write.append(dt)
  95. elif p.get('read'):
  96. if dtp.get('read_only'):
  97. self.all_read.append(dt)
  98. else:
  99. self.can_read.append(dt)
  100. if p.get('cancel'):
  101. self.can_cancel.append(dt)
  102. if p.get('delete'):
  103. self.can_delete.append(dt)
  104. if (p.get('read') or p.get('write') or p.get('create')):
  105. if p.get('report'):
  106. self.can_get_report.append(dt)
  107. for key in ("import", "export", "print", "email", "set_user_permissions"):
  108. if p.get(key):
  109. getattr(self, "can_" + key).append(dt)
  110. if not dtp.get('istable'):
  111. if not dtp.get('issingle') and not dtp.get('read_only'):
  112. self.can_search.append(dt)
  113. if not dtp.get('module') in self.allow_modules:
  114. self.allow_modules.append(dtp.get('module'))
  115. self.can_write += self.can_create
  116. self.can_write += self.in_create
  117. self.can_read += self.can_write
  118. self.shared = frappe.db.sql_list("""select distinct share_doctype from `tabDocShare`
  119. where `user`=%s and `read`=1""", self.name)
  120. self.can_read = list(set(self.can_read + self.shared))
  121. self.all_read += self.can_read
  122. if "System Manager" in self.roles:
  123. self.can_import = frappe.db.sql_list("""select name from `tabDocType`
  124. where allow_import = 1""")
  125. def get_defaults(self):
  126. import frappe.defaults
  127. self.defaults = frappe.defaults.get_defaults(self.name)
  128. return self.defaults
  129. # update recent documents
  130. def update_recent(self, dt, dn):
  131. rdl = frappe.cache().hget("user_recent", self.name) or []
  132. new_rd = [dt, dn]
  133. # clear if exists
  134. for i in range(len(rdl)):
  135. rd = rdl[i]
  136. if rd==new_rd:
  137. del rdl[i]
  138. break
  139. if len(rdl) > 19:
  140. rdl = rdl[:19]
  141. rdl = [new_rd] + rdl
  142. frappe.cache().hset("user_recent", self.name, rdl)
  143. def _get(self, key):
  144. if not self.can_read:
  145. self.build_permissions()
  146. return getattr(self, key)
  147. def get_can_read(self):
  148. """return list of doctypes that the user can read"""
  149. if not self.can_read:
  150. self.build_permissions()
  151. return self.can_read
  152. def load_user(self):
  153. d = frappe.db.sql("""select email, first_name, last_name,
  154. email_signature, user_type, language, background_image, background_style
  155. from tabUser where name = %s""", (self.name,), as_dict=1)[0]
  156. if not self.can_read:
  157. self.build_permissions()
  158. d.name = self.name
  159. d.recent = json.dumps(frappe.cache().hget("user_recent", self.name) or [])
  160. d.roles = self.get_roles()
  161. d.defaults = self.get_defaults()
  162. d.block_modules = self.get_block_modules()
  163. for key in ("can_create", "can_write", "can_read", "can_cancel", "can_delete",
  164. "can_get_report", "allow_modules", "all_read", "can_search",
  165. "in_create", "can_export", "can_import", "can_print", "can_email",
  166. "can_set_user_permissions"):
  167. d[key] = list(set(getattr(self, key)))
  168. return d
  169. def get_user_fullname(user):
  170. fullname = frappe.db.sql("SELECT CONCAT_WS(' ', first_name, last_name) FROM `tabUser` WHERE name=%s", (user,))
  171. return fullname and fullname[0][0] or ''
  172. def get_fullname_and_avatar(user):
  173. first_name, last_name, avatar = frappe.db.get_value("User",
  174. user, ["first_name", "last_name", "user_image"])
  175. return _dict({
  176. "fullname": " ".join(filter(None, [first_name, last_name])),
  177. "avatar": avatar
  178. })
  179. def get_system_managers(only_name=False):
  180. """returns all system manager's user details"""
  181. import email.utils
  182. from frappe.core.doctype.user.user import STANDARD_USERS
  183. system_managers = frappe.db.sql("""select distinct name,
  184. concat_ws(" ", if(first_name="", null, first_name), if(last_name="", null, last_name))
  185. as fullname from tabUser p
  186. where docstatus < 2 and enabled = 1
  187. and name not in ({})
  188. and exists (select * from tabUserRole ur
  189. where ur.parent = p.name and ur.role="System Manager")""".format(", ".join(["%s"]*len(STANDARD_USERS))),
  190. STANDARD_USERS, as_dict=True)
  191. if only_name:
  192. return [p.name for p in system_managers]
  193. else:
  194. return [email.utils.formataddr((p.fullname, p.name)) for p in system_managers]
  195. def add_role(user, role):
  196. frappe.get_doc("User", user).add_roles(role)
  197. def add_system_manager(email, first_name=None, last_name=None):
  198. # add user
  199. user = frappe.new_doc("User")
  200. user.update({
  201. "name": email,
  202. "email": email,
  203. "enabled": 1,
  204. "first_name": first_name or email,
  205. "last_name": last_name,
  206. "user_type": "System User"
  207. })
  208. user.insert()
  209. # add roles
  210. roles = frappe.db.sql_list("""select name from `tabRole`
  211. where name not in ("Administrator", "Guest", "All")""")
  212. user.add_roles(*roles)
  213. def get_roles(user=None, with_standard=True):
  214. """get roles of current user"""
  215. if not user:
  216. user = frappe.session.user
  217. if user=='Guest':
  218. return ['Guest']
  219. def get():
  220. return [r[0] for r in frappe.db.sql("""select role from tabUserRole
  221. where parent=%s and role not in ('All', 'Guest')""", (user,))] + ['All', 'Guest']
  222. roles = frappe.cache().hget("roles", user, get)
  223. # filter standard if required
  224. if not with_standard:
  225. roles = filter(lambda x: x not in ['All', 'Guest', 'Administrator'], roles)
  226. return roles
  227. def get_enabled_system_users():
  228. return frappe.db.sql("""select * from tabUser where
  229. user_type='System User' and enabled=1 and name not in ('Administrator', 'Guest')""", as_dict=1)
  230. def is_website_user():
  231. return frappe.get_user().doc.user_type == "Website User"
  232. def is_system_user(username):
  233. return frappe.db.get_value("User", {"name": username, "enabled": 1, "user_type": "System User"})