25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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