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.
 
 
 
 
 
 

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