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.
 
 
 
 
 
 

308 rivejä
8.8 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')) and \
  100. not dtp.get('read_only'):
  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'):
  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_home_page(self):
  112. """
  113. Get the name of the user's home page from the `Control Panel`
  114. """
  115. hpl = webnotes.conn.sql("""select home_page from `tabDefault Home Page`
  116. where parent='Control Panel'
  117. and role in ('%s') order by idx asc limit 1""" % "', '".join(self.get_roles()))
  118. if hpl:
  119. return hpl[0][0]
  120. else:
  121. return webnotes.conn.get_value('Control Panel',None,'home_page') or 'Login Page'
  122. def get_defaults(self):
  123. """
  124. Get the user's default values based on user and role profile
  125. """
  126. roles = self.get_roles() + [self.name]
  127. res = webnotes.conn.sql("""select defkey, defvalue
  128. from `tabDefaultValue` where parent in ("%s")""" % '", "'.join(roles))
  129. self.defaults = {'owner': [self.name,]}
  130. for rec in res:
  131. if not self.defaults.has_key(rec[0]):
  132. self.defaults[rec[0]] = []
  133. self.defaults[rec[0]].append(rec[1] or '')
  134. return self.defaults
  135. def get_hide_tips(self):
  136. try:
  137. return webnotes.conn.sql("select hide_tips from tabProfile where name=%s", self.name)[0][0] or 0
  138. except:
  139. return 0
  140. # update recent documents
  141. def update_recent(self, dt, dn):
  142. """
  143. Update the user's `Recent` list with the given `dt` and `dn`
  144. """
  145. conn = webnotes.conn
  146. from webnotes.utils import cstr
  147. import json
  148. # get list of child tables, so we know what not to add in the recent list
  149. child_tables = [t[0] for t in conn.sql('select name from tabDocType where ifnull(istable,0) = 1')]
  150. if not (dt in ['Print Format', 'Start Page', 'Event', 'ToDo Item', 'Search Criteria']) \
  151. and not (dt in child_tables):
  152. r = webnotes.conn.sql("select recent_documents from tabProfile where name=%s", \
  153. self.name)[0][0] or ''
  154. if '~~~' in r:
  155. r = '[]'
  156. rdl = json.loads(r or '[]')
  157. new_rd = [dt, dn]
  158. # clear if exists
  159. for i in range(len(rdl)):
  160. rd = rdl[i]
  161. if rd==new_rd:
  162. del rdl[i]
  163. break
  164. if len(rdl) > 19:
  165. rdl = rdl[:19]
  166. rdl = [new_rd] + rdl
  167. self.recent = json.dumps(rdl)
  168. webnotes.conn.sql("""update tabProfile set
  169. recent_documents=%s where name=%s""", (self.recent, self.name))
  170. def load_profile(self):
  171. """
  172. Return a dictionary of user properites to be stored in the session
  173. """
  174. t = webnotes.conn.sql("""select email, first_name, last_name,
  175. recent_documents from tabProfile where name = %s""", self.name)[0]
  176. if not self.can_read:
  177. self.build_permissions()
  178. d = {}
  179. d['name'] = self.name
  180. d['email'] = t[0] or ''
  181. d['first_name'] = t[1] or ''
  182. d['last_name'] = t[2] or ''
  183. d['recent'] = t[3] or ''
  184. d['hide_tips'] = self.get_hide_tips()
  185. d['roles'] = self.roles
  186. d['defaults'] = self.get_defaults()
  187. d['can_create'] = self.can_create
  188. d['can_write'] = self.can_write
  189. d['can_read'] = list(set(self.can_read))
  190. d['can_cancel'] = list(set(self.can_cancel))
  191. d['can_get_report'] = list(set(self.can_get_report))
  192. d['allow_modules'] = self.allow_modules
  193. d['all_read'] = self.all_read
  194. d['can_search'] = list(set(self.can_search))
  195. return d
  196. def load_from_session(self, d):
  197. """
  198. Setup the user profile from the dictionary saved in the session (generated by `load_profile`)
  199. """
  200. self.can_create = d['can_create']
  201. self.can_read = d['can_read']
  202. self.can_write = d['can_write']
  203. self.can_get_report = d['can_get_report']
  204. self.allow_modules = d['allow_modules']
  205. self.all_read = d['all_read']
  206. self.roles = d['roles']
  207. self.defaults = d['defaults']
  208. def reset_password(self):
  209. """reset password"""
  210. from webnotes.utils import random_string, now
  211. pwd = random_string(8)
  212. # update tab Profile
  213. webnotes.conn.sql("""UPDATE tabProfile SET password=password(%s), modified=%s
  214. WHERE name=%s""", (pwd, now(), self.name))
  215. return pwd
  216. def send_new_pwd(self, pwd):
  217. """
  218. Send new password to user
  219. """
  220. import os
  221. # send email
  222. with open(os.path.join(os.path.dirname(__file__), 'password_reset.txt'), 'r') as f:
  223. reset_password_mail = f.read()
  224. from webnotes.utils.email_lib import sendmail_md
  225. sendmail_md(recipients= self.name, \
  226. msg = reset_password_mail % {"user": get_user_fullname(self.name), "password": pwd}, \
  227. subject = 'Password Reset', from_defs=1)
  228. @webnotes.whitelist()
  229. def get_user_img():
  230. if not webnotes.form.getvalue('username'):
  231. webnotes.response['message'] = 'no_img_m'
  232. return
  233. f = webnotes.conn.sql("select file_list from tabProfile where name=%s", webnotes.form.getvalue('username',''))
  234. if f:
  235. if f[0][0]:
  236. lst = f[0][0].split('\n')
  237. webnotes.response['message'] = lst[0].split(',')[1]
  238. else:
  239. webnotes.response['message'] = 'no_img_m'
  240. else:
  241. webnotes.response['message'] = 'no_img_m'
  242. def get_user_fullname(user):
  243. fullname = webnotes.conn.sql("SELECT CONCAT_WS(' ', first_name, last_name) FROM `tabProfile` WHERE name=%s", user)
  244. return fullname and fullname[0][0] or ''