You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

295 regels
8.4 KiB

  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. import webnotes
  23. class Profile:
  24. """
  25. A profile object is created at the beginning of every request with details of the use.
  26. The global profile object is `webnotes.user`
  27. """
  28. def __init__(self, name=''):
  29. self.name = name or webnotes.session.get('user')
  30. self.roles = []
  31. self.all_read = []
  32. self.can_create = []
  33. self.can_read = []
  34. self.can_write = []
  35. self.can_cancel = []
  36. self.can_search = []
  37. self.can_get_report = []
  38. self.allow_modules = []
  39. def _load_roles(self):
  40. self.roles = webnotes.get_roles()
  41. return self.roles
  42. def get_roles(self):
  43. """get list of roles"""
  44. if self.roles:
  45. return self.roles
  46. return self._load_roles()
  47. def build_doctype_map(self):
  48. """build map of special doctype properties"""
  49. self.doctype_map = {}
  50. for r in webnotes.conn.sql("""select name, in_create, issingle, istable,
  51. read_only, module from tabDocType""", as_dict=1):
  52. r['child_tables'] = []
  53. self.doctype_map[r['name']] = r
  54. for r in webnotes.conn.sql("""select parent, options from tabDocField
  55. where fieldtype="Table"
  56. and parent not like "old_parent:%%"
  57. and ifnull(docstatus,0)=0
  58. """):
  59. if r[0] in self.doctype_map:
  60. self.doctype_map[r[0]]['child_tables'].append(r[1])
  61. def build_perm_map(self):
  62. """build map of permissions at level 0"""
  63. self.perm_map = {}
  64. for r in webnotes.conn.sql("""select parent, `read`, `write`, `create`, `submit`, `cancel`
  65. from tabDocPerm where docstatus=0
  66. and ifnull(permlevel,0)=0
  67. and parent not like "old_parent:%%"
  68. and role in ('%s')""" % "','".join(self.get_roles()), as_dict=1):
  69. dt = r['parent']
  70. if not dt in self.perm_map:
  71. self.perm_map[dt] = {}
  72. for k in ('read', 'write', 'create', 'submit', 'cancel'):
  73. if not self.perm_map[dt].get(k):
  74. self.perm_map[dt][k] = r.get(k)
  75. def build_permissions(self):
  76. """build lists of what the user can read / write / create
  77. quirks:
  78. read_only => Not in Search
  79. in_create => Not in create
  80. """
  81. self.build_doctype_map()
  82. self.build_perm_map()
  83. for dt in self.doctype_map:
  84. dtp = self.doctype_map[dt]
  85. p = self.perm_map.get(dt, {})
  86. if not dtp.get('istable'):
  87. if p.get('create') and not dtp.get('in_create') and \
  88. not dtp.get('issingle'):
  89. self.can_create.append(dt)
  90. elif p.get('write'):
  91. self.can_write.append(dt)
  92. elif p.get('read'):
  93. if dtp.get('read_only'):
  94. self.all_read.append(dt)
  95. else:
  96. self.can_read.append(dt)
  97. if p.get('cancel'):
  98. self.can_cancel.append(dt)
  99. if (p.get('read') or p.get('write') or p.get('create')):
  100. self.can_get_report.append(dt)
  101. self.can_get_report += dtp['child_tables']
  102. if not dtp.get('istable'):
  103. if not dtp.get('issingle') and not dtp.get('read_only'):
  104. self.can_search.append(dt)
  105. if not dtp.get('module') in self.allow_modules:
  106. self.allow_modules.append(dtp.get('module'))
  107. self.can_write += self.can_create
  108. self.can_read += self.can_write
  109. self.all_read += self.can_read
  110. def get_defaults(self):
  111. """
  112. Get the user's default values based on user and role profile
  113. """
  114. roles = self.get_roles() + [self.name]
  115. res = webnotes.conn.sql("""select defkey, defvalue
  116. from `tabDefaultValue` where parent in ("%s")""" % '", "'.join(roles))
  117. self.defaults = {'owner': [self.name,]}
  118. for rec in res:
  119. if not self.defaults.has_key(rec[0]):
  120. self.defaults[rec[0]] = []
  121. self.defaults[rec[0]].append(rec[1] or '')
  122. return self.defaults
  123. def get_hide_tips(self):
  124. try:
  125. return webnotes.conn.sql("select hide_tips from tabProfile where name=%s", self.name)[0][0] or 0
  126. except:
  127. return 0
  128. # update recent documents
  129. def update_recent(self, dt, dn):
  130. """
  131. Update the user's `Recent` list with the given `dt` and `dn`
  132. """
  133. conn = webnotes.conn
  134. from webnotes.utils import cstr
  135. import json
  136. # get list of child tables, so we know what not to add in the recent list
  137. child_tables = [t[0] for t in conn.sql('select name from tabDocType where ifnull(istable,0) = 1')]
  138. if not (dt in ['Print Format', 'Start Page', 'Event', 'ToDo', 'Search Criteria']) \
  139. and not (dt in child_tables):
  140. r = webnotes.conn.sql("select recent_documents from tabProfile where name=%s", \
  141. self.name)[0][0] or ''
  142. if '~~~' in r:
  143. r = '[]'
  144. rdl = json.loads(r or '[]')
  145. new_rd = [dt, dn]
  146. # clear if exists
  147. for i in range(len(rdl)):
  148. rd = rdl[i]
  149. if rd==new_rd:
  150. del rdl[i]
  151. break
  152. if len(rdl) > 19:
  153. rdl = rdl[:19]
  154. rdl = [new_rd] + rdl
  155. self.recent = json.dumps(rdl)
  156. webnotes.conn.sql("""update tabProfile set
  157. recent_documents=%s where name=%s""", (self.recent, self.name))
  158. def load_profile(self):
  159. """
  160. Return a dictionary of user properites to be stored in the session
  161. """
  162. t = webnotes.conn.sql("""select email, first_name, last_name,
  163. recent_documents from tabProfile where name = %s""", self.name)[0]
  164. if not self.can_read:
  165. self.build_permissions()
  166. d = {}
  167. d['name'] = self.name
  168. d['email'] = t[0] or ''
  169. d['first_name'] = t[1] or ''
  170. d['last_name'] = t[2] or ''
  171. d['recent'] = t[3] or ''
  172. d['hide_tips'] = self.get_hide_tips()
  173. d['roles'] = self.roles
  174. d['defaults'] = self.get_defaults()
  175. d['can_create'] = self.can_create
  176. d['can_write'] = self.can_write
  177. d['can_read'] = list(set(self.can_read))
  178. d['can_cancel'] = list(set(self.can_cancel))
  179. d['can_get_report'] = list(set(self.can_get_report))
  180. d['allow_modules'] = self.allow_modules
  181. d['all_read'] = self.all_read
  182. d['can_search'] = list(set(self.can_search))
  183. return d
  184. def load_from_session(self, d):
  185. """
  186. Setup the user profile from the dictionary saved in the session (generated by `load_profile`)
  187. """
  188. self.can_create = d['can_create']
  189. self.can_read = d['can_read']
  190. self.can_write = d['can_write']
  191. self.can_search = d['can_search']
  192. self.can_get_report = d['can_get_report']
  193. self.allow_modules = d['allow_modules']
  194. self.all_read = d['all_read']
  195. self.roles = d['roles']
  196. self.defaults = d['defaults']
  197. def reset_password(self):
  198. """reset password"""
  199. from webnotes.utils import random_string, now
  200. pwd = random_string(8)
  201. # update tab Profile
  202. webnotes.conn.sql("""UPDATE tabProfile SET password=password(%s), modified=%s
  203. WHERE name=%s""", (pwd, now(), self.name))
  204. return pwd
  205. def send_new_pwd(self, pwd):
  206. """
  207. Send new password to user
  208. """
  209. import os
  210. # send email
  211. with open(os.path.join(os.path.dirname(__file__), 'password_reset.txt'), 'r') as f:
  212. reset_password_mail = f.read()
  213. from webnotes.utils.email_lib import sendmail_md
  214. sendmail_md(recipients= self.name, \
  215. msg = reset_password_mail % {"user": get_user_fullname(self.name), "password": pwd}, \
  216. subject = 'Password Reset')
  217. @webnotes.whitelist()
  218. def get_user_img():
  219. if not webnotes.form.getvalue('username'):
  220. webnotes.response['message'] = 'no_img_m'
  221. return
  222. f = webnotes.conn.sql("select file_list from tabProfile where name=%s", webnotes.form.getvalue('username',''))
  223. if f:
  224. if f[0][0]:
  225. lst = f[0][0].split('\n')
  226. webnotes.response['message'] = lst[0].split(',')[1]
  227. else:
  228. webnotes.response['message'] = 'no_img_m'
  229. else:
  230. webnotes.response['message'] = 'no_img_m'
  231. def get_user_fullname(user):
  232. fullname = webnotes.conn.sql("SELECT CONCAT_WS(' ', first_name, last_name) FROM `tabProfile` WHERE name=%s", user)
  233. return fullname and fullname[0][0] or ''