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.
 
 
 
 
 
 

297 regels
8.5 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. from __future__ import unicode_literals
  23. import webnotes
  24. class Profile:
  25. """
  26. A profile object is created at the beginning of every request with details of the use.
  27. The global profile object is `webnotes.user`
  28. """
  29. def __init__(self, name=''):
  30. self.name = name or webnotes.session.get('user')
  31. self.roles = []
  32. self.all_read = []
  33. self.can_create = []
  34. self.can_read = []
  35. self.can_write = []
  36. self.can_cancel = []
  37. self.can_search = []
  38. self.can_get_report = []
  39. self.allow_modules = []
  40. def _load_roles(self):
  41. self.roles = webnotes.get_roles()
  42. return self.roles
  43. def get_roles(self):
  44. """get list of roles"""
  45. if self.roles:
  46. return self.roles
  47. return self._load_roles()
  48. def build_doctype_map(self):
  49. """build map of special doctype properties"""
  50. self.doctype_map = {}
  51. for r in webnotes.conn.sql("""select name, in_create, issingle, istable,
  52. read_only, module from tabDocType""", as_dict=1):
  53. r['child_tables'] = []
  54. self.doctype_map[r['name']] = r
  55. for r in webnotes.conn.sql("""select parent, options from tabDocField
  56. where fieldtype="Table"
  57. and parent not like "old_parent:%%"
  58. and ifnull(docstatus,0)=0
  59. """):
  60. if r[0] in self.doctype_map:
  61. self.doctype_map[r[0]]['child_tables'].append(r[1])
  62. def build_perm_map(self):
  63. """build map of permissions at level 0"""
  64. self.perm_map = {}
  65. for r in webnotes.conn.sql("""select parent, `read`, `write`, `create`, `submit`, `cancel`
  66. from tabDocPerm where docstatus=0
  67. and ifnull(permlevel,0)=0
  68. and parent not like "old_parent:%%"
  69. and role in ('%s')""" % "','".join(self.get_roles()), as_dict=1):
  70. dt = r['parent']
  71. if not dt in self.perm_map:
  72. self.perm_map[dt] = {}
  73. for k in ('read', 'write', 'create', 'submit', 'cancel'):
  74. if not self.perm_map[dt].get(k):
  75. self.perm_map[dt][k] = r.get(k)
  76. def build_permissions(self):
  77. """build lists of what the user can read / write / create
  78. quirks:
  79. read_only => Not in Search
  80. in_create => Not in create
  81. """
  82. self.build_doctype_map()
  83. self.build_perm_map()
  84. for dt in self.doctype_map:
  85. dtp = self.doctype_map[dt]
  86. p = self.perm_map.get(dt, {})
  87. if not dtp.get('istable'):
  88. if p.get('create') and not dtp.get('in_create') and \
  89. not dtp.get('issingle'):
  90. self.can_create.append(dt)
  91. elif p.get('write'):
  92. self.can_write.append(dt)
  93. elif p.get('read'):
  94. if dtp.get('read_only'):
  95. self.all_read.append(dt)
  96. else:
  97. self.can_read.append(dt)
  98. if p.get('cancel'):
  99. self.can_cancel.append(dt)
  100. if (p.get('read') or p.get('write') or p.get('create')):
  101. self.can_get_report.append(dt)
  102. self.can_get_report += dtp['child_tables']
  103. if not dtp.get('istable'):
  104. if not dtp.get('issingle') and not dtp.get('read_only'):
  105. self.can_search.append(dt)
  106. if not dtp.get('module') in self.allow_modules:
  107. self.allow_modules.append(dtp.get('module'))
  108. self.can_write += self.can_create
  109. self.can_read += self.can_write
  110. self.all_read += self.can_read
  111. def get_defaults(self):
  112. """
  113. Get the user's default values based on user and role profile
  114. """
  115. roles = self.get_roles() + [self.name]
  116. res = webnotes.conn.sql("""select defkey, defvalue
  117. from `tabDefaultValue` where parent in ("%s") order by idx""" % '", "'.join(roles))
  118. self.defaults = {'owner': [self.name,]}
  119. for rec in res:
  120. if not self.defaults.has_key(rec[0]):
  121. self.defaults[rec[0]] = []
  122. self.defaults[rec[0]].append(rec[1] or '')
  123. return self.defaults
  124. def get_hide_tips(self):
  125. try:
  126. return webnotes.conn.sql("select hide_tips from tabProfile where name=%s", self.name)[0][0] or 0
  127. except:
  128. return 0
  129. # update recent documents
  130. def update_recent(self, dt, dn):
  131. """
  132. Update the user's `Recent` list with the given `dt` and `dn`
  133. """
  134. conn = webnotes.conn
  135. from webnotes.utils import cstr
  136. import json
  137. # get list of child tables, so we know what not to add in the recent list
  138. child_tables = [t[0] for t in conn.sql('select name from tabDocType where ifnull(istable,0) = 1')]
  139. if not (dt in ['Print Format', 'Start Page', 'Event', 'ToDo', 'Search Criteria']) \
  140. and not (dt in child_tables):
  141. r = webnotes.conn.sql("select recent_documents from tabProfile where name=%s", \
  142. self.name)[0][0] or ''
  143. if '~~~' in r:
  144. r = '[]'
  145. rdl = json.loads(r or '[]')
  146. new_rd = [dt, dn]
  147. # clear if exists
  148. for i in range(len(rdl)):
  149. rd = rdl[i]
  150. if rd==new_rd:
  151. del rdl[i]
  152. break
  153. if len(rdl) > 19:
  154. rdl = rdl[:19]
  155. rdl = [new_rd] + rdl
  156. self.recent = json.dumps(rdl)
  157. webnotes.conn.sql("""update tabProfile set
  158. recent_documents=%s where name=%s""", (self.recent, self.name))
  159. def load_profile(self):
  160. """
  161. Return a dictionary of user properites to be stored in the session
  162. """
  163. t = webnotes.conn.sql("""select email, first_name, last_name,
  164. recent_documents from tabProfile where name = %s""", self.name)[0]
  165. if not self.can_read:
  166. self.build_permissions()
  167. d = {}
  168. d['name'] = self.name
  169. d['email'] = t[0] or ''
  170. d['first_name'] = t[1] or ''
  171. d['last_name'] = t[2] or ''
  172. d['recent'] = t[3] or ''
  173. d['hide_tips'] = self.get_hide_tips()
  174. d['roles'] = self.roles
  175. d['defaults'] = self.get_defaults()
  176. d['can_create'] = self.can_create
  177. d['can_write'] = self.can_write
  178. d['can_read'] = list(set(self.can_read))
  179. d['can_cancel'] = list(set(self.can_cancel))
  180. d['can_get_report'] = list(set(self.can_get_report))
  181. d['allow_modules'] = self.allow_modules
  182. d['all_read'] = self.all_read
  183. d['can_search'] = list(set(self.can_search))
  184. return d
  185. def load_from_session(self, d):
  186. """
  187. Setup the user profile from the dictionary saved in the session (generated by `load_profile`)
  188. """
  189. self.can_create = d['can_create']
  190. self.can_read = d['can_read']
  191. self.can_write = d['can_write']
  192. self.can_search = d['can_search']
  193. self.can_cancel = d['can_cancel']
  194. self.can_get_report = d['can_get_report']
  195. self.allow_modules = d['allow_modules']
  196. self.all_read = d['all_read']
  197. self.roles = d['roles']
  198. self.defaults = d['defaults']
  199. def reset_password(self):
  200. """reset password"""
  201. from webnotes.utils import random_string, now
  202. pwd = random_string(8)
  203. # update tab Profile
  204. webnotes.conn.sql("""UPDATE tabProfile SET password=password(%s), modified=%s
  205. WHERE name=%s""", (pwd, now(), self.name))
  206. return pwd
  207. def send_new_pwd(self, pwd):
  208. """
  209. Send new password to user
  210. """
  211. import os
  212. # send email
  213. with open(os.path.join(os.path.dirname(__file__), 'password_reset.txt'), 'r') as f:
  214. reset_password_mail = f.read()
  215. from webnotes.utils.email_lib import sendmail_md
  216. sendmail_md(recipients= self.name, \
  217. msg = reset_password_mail % {"user": get_user_fullname(self.name), "password": pwd}, \
  218. subject = 'Password Reset')
  219. @webnotes.whitelist()
  220. def get_user_img():
  221. if not webnotes.form.getvalue('username'):
  222. webnotes.response['message'] = 'no_img_m'
  223. return
  224. f = webnotes.conn.sql("select file_list from tabProfile where name=%s", webnotes.form.getvalue('username',''))
  225. if f:
  226. if f[0][0]:
  227. lst = f[0][0].split('\n')
  228. webnotes.response['message'] = lst[0].split(',')[1]
  229. else:
  230. webnotes.response['message'] = 'no_img_m'
  231. else:
  232. webnotes.response['message'] = 'no_img_m'
  233. def get_user_fullname(user):
  234. fullname = webnotes.conn.sql("SELECT CONCAT_WS(' ', first_name, last_name) FROM `tabProfile` WHERE name=%s", user)
  235. return fullname and fullname[0][0] or ''