Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

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