您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

270 行
8.2 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. """
  24. Boot session from cache or build
  25. Session bootstraps info needed by common client side activities including
  26. permission, homepage, control panel variables, system defaults etc
  27. """
  28. import webnotes
  29. import conf
  30. import json
  31. from webnotes.utils import cint
  32. import webnotes.model.doctype
  33. import webnotes.defaults
  34. @webnotes.whitelist()
  35. def clear(user=None):
  36. clear_cache(webnotes.session.user)
  37. webnotes.response['message'] = "Cache Cleared"
  38. def clear_cache(user=None):
  39. cache = webnotes.cache()
  40. # clear doctype cache
  41. webnotes.model.doctype.clear_cache()
  42. if user:
  43. cache.delete_value("bootinfo:" + user)
  44. if webnotes.session and webnotes.session.sid:
  45. cache.delete_value("session:" + webnotes.session.sid)
  46. else:
  47. for sess in webnotes.conn.sql("""select user, sid from tabSessions""", as_dict=1):
  48. cache.delete_value("sesssion:" + sess.sid)
  49. cache.delete_value("bootinfo:" + sess.user)
  50. def clear_sessions(user=None, keep_current=False):
  51. if not user:
  52. user = webnotes.session.user
  53. for sid in webnotes.conn.sql("""select sid from tabSessions where user=%s""", user):
  54. if keep_current and webnotes.session.sid==sid[0]:
  55. pass
  56. else:
  57. webnotes.cache().delete_value("session:" + sid[0])
  58. webnotes.conn.sql("""delete from tabSessions where sid=%s""", sid[0])
  59. def get():
  60. """get session boot info"""
  61. # check if cache exists
  62. if not getattr(conf,'auto_cache_clear',None):
  63. cache = webnotes.cache().get_value('bootinfo:' + webnotes.session.user)
  64. if cache:
  65. cache['from_cache'] = 1
  66. return cache
  67. if not webnotes.cache().get_stats():
  68. webnotes.msgprint("memcached is not working / stopped. Please start memcached for best results.")
  69. # if not create it
  70. from webnotes.boot import get_bootinfo
  71. bootinfo = get_bootinfo()
  72. webnotes.cache().set_value('bootinfo:' + webnotes.session.user, bootinfo)
  73. return bootinfo
  74. class Session:
  75. def __init__(self, user=None):
  76. self.user = user
  77. self.sid = webnotes.form_dict.get('sid') or webnotes.incoming_cookies.get('sid', 'Guest')
  78. self.data = webnotes._dict({'user':user,'data': webnotes._dict({})})
  79. self.time_diff = None
  80. if webnotes.form_dict.get('cmd')=='login':
  81. self.start()
  82. return
  83. self.load()
  84. def start(self):
  85. """start a new session"""
  86. import os
  87. import webnotes
  88. import webnotes.utils
  89. # generate sid
  90. if webnotes.login_manager.user=='Guest':
  91. sid = 'Guest'
  92. else:
  93. sid = webnotes.generate_hash()
  94. self.data['user'] = webnotes.login_manager.user
  95. self.data['sid'] = sid
  96. self.data['data']['user'] = webnotes.login_manager.user
  97. self.data['data']['session_ip'] = os.environ.get('REMOTE_ADDR')
  98. self.data['data']['last_updated'] = webnotes.utils.now()
  99. self.data['data']['session_expiry'] = self.get_expiry_period()
  100. # get ipinfo
  101. if webnotes.conn.get_global('get_ip_info'):
  102. self.get_ipinfo()
  103. # insert session
  104. webnotes.conn.begin()
  105. self.insert_session_record()
  106. # update profile
  107. webnotes.conn.sql("""UPDATE tabProfile SET last_login = '%s', last_ip = '%s'
  108. where name='%s'""" % (webnotes.utils.now(), webnotes.remote_ip, self.data['user']))
  109. webnotes.conn.commit()
  110. # set cookies to write
  111. webnotes.session = self.data
  112. webnotes.cookie_manager.set_cookies()
  113. def insert_session_record(self):
  114. webnotes.conn.sql("""insert into tabSessions
  115. (sessiondata, user, lastupdate, sid, status)
  116. values (%s , %s, NOW(), %s, 'Active')""",
  117. (str(self.data['data']), self.data['user'], self.data['sid']))
  118. # also add to memcache
  119. webnotes.cache().set_value("session:" + self.data.sid, self.data)
  120. def load(self):
  121. """non-login request: load a session"""
  122. import webnotes
  123. data = self.get_session_record()
  124. if data:
  125. # set language
  126. if data.lang and self.user!="demo@erpnext.com":
  127. webnotes.lang = data.lang
  128. self.data = webnotes._dict({'data': data,
  129. 'user':data.user, 'sid': self.sid})
  130. else:
  131. self.start_as_guest()
  132. def get_session_record(self):
  133. """get session record, or return the standard Guest Record"""
  134. r = self.get_session_data()
  135. if not r:
  136. webnotes.response["session_expired"] = 1
  137. self.sid = "Guest"
  138. r = self.get_session_data()
  139. return r
  140. def get_session_data(self):
  141. data = self.get_session_data_from_cache()
  142. if not data:
  143. data = self.get_session_data_from_db()
  144. return data
  145. def get_session_data_from_cache(self):
  146. data = webnotes._dict(webnotes.cache().get_value("session:" + self.sid) or {})
  147. if data:
  148. session_data = data.get("data", {})
  149. self.time_diff = webnotes.utils.time_diff_in_seconds(webnotes.utils.now(),
  150. session_data.get("last_updated"))
  151. expiry = self.get_expiry_in_seconds(session_data.get("session_expiry"))
  152. if self.time_diff > expiry:
  153. self.delete_session()
  154. data = None
  155. return data and data.data
  156. def get_session_data_from_db(self):
  157. if self.sid=="Guest":
  158. rec = webnotes.conn.sql("""select user, sessiondata from
  159. tabSessions where sid='Guest' """)
  160. else:
  161. rec = webnotes.conn.sql("""select user, sessiondata
  162. from tabSessions where sid=%s and
  163. TIMEDIFF(NOW(), lastupdate) < TIME(%s)""", (self.sid,
  164. self.get_expiry_period()))
  165. if rec:
  166. data = webnotes._dict(eval(rec and rec[0][1] or '{}'))
  167. data.user = rec[0][0]
  168. else:
  169. self.delete_session()
  170. data = None
  171. return data
  172. def get_expiry_in_seconds(self, expiry):
  173. if not expiry: return 3600
  174. parts = expiry.split(":")
  175. return (cint(parts[0]) * 3600) + (cint(parts[1]) * 60) + cint(parts[2])
  176. def delete_session(self):
  177. webnotes.cache().delete_value("session:" + self.sid)
  178. r = webnotes.conn.sql("""delete from tabSessions where sid=%s""", self.sid)
  179. def start_as_guest(self):
  180. """all guests share the same 'Guest' session"""
  181. webnotes.login_manager.login_as_guest()
  182. self.start()
  183. def update(self):
  184. """extend session expiry"""
  185. self.data['data']['last_updated'] = webnotes.utils.now()
  186. if webnotes.user_lang:
  187. # user language
  188. self.data['data']['lang'] = webnotes.lang
  189. # update session in db
  190. time_diff = None
  191. last_updated = webnotes.cache().get_value("last_db_session_update:" + self.sid)
  192. if last_updated:
  193. time_diff = webnotes.utils.time_diff_in_seconds(webnotes.utils.now(),
  194. last_updated)
  195. if webnotes.session['user'] != 'Guest' and \
  196. ((time_diff==None) or (time_diff > 1800)):
  197. # database persistence is secondary, don't update it too often
  198. webnotes.conn.sql("""update tabSessions set sessiondata=%s,
  199. lastupdate=NOW() where sid=%s""" , (str(self.data['data']),
  200. self.data['sid']))
  201. if webnotes.request.cmd not in ("webnotes.sessions.clear", "logout"):
  202. webnotes.cache().set_value("last_db_session_update:" + self.sid,
  203. webnotes.utils.now())
  204. webnotes.cache().set_value("session:" + self.sid, self.data)
  205. def get_expiry_period(self):
  206. exp_sec = webnotes.defaults.get_global_default("session_expiry")
  207. # incase seconds is missing
  208. if exp_sec:
  209. if len(exp_sec.split(':')) == 2:
  210. exp_sec = exp_sec + ':00'
  211. else:
  212. exp_sec = "2:00:00"
  213. return exp_sec
  214. def get_ipinfo(self):
  215. import os
  216. try:
  217. import pygeoip
  218. except:
  219. return
  220. gi = pygeoip.GeoIP('data/GeoIP.dat')
  221. self.data['data']['ipinfo'] = {'countryName': gi.country_name_by_addr(os.environ.get('REMOTE_ADDR'))}