Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

pirms 13 gadiem
pirms 12 gadiem
pirms 13 gadiem
pirms 13 gadiem
pirms 12 gadiem
pirms 12 gadiem
pirms 12 gadiem
pirms 12 gadiem
pirms 12 gadiem
pirms 12 gadiem
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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 all cache"""
  36. clear_cache(webnotes.session.user)
  37. webnotes.response['message'] = "Cache Cleared"
  38. def clear_cache(user=None):
  39. """clear cache"""
  40. cache = webnotes.cache()
  41. # clear doctype cache
  42. webnotes.model.doctype.clear_cache()
  43. if user:
  44. cache.delete_value("bootinfo:" + user)
  45. if webnotes.session and webnotes.session.sid:
  46. cache.delete_value("session:" + webnotes.session.sid)
  47. else:
  48. for sess in webnotes.conn.sql("""select user, sid from tabSessions""", as_dict=1):
  49. cache.delete_value("sesssion:" + sess.sid)
  50. cache.delete_value("bootinfo:" + sess.user)
  51. def clear_sessions(user=None, keep_current=False):
  52. if not user:
  53. user = webnotes.session.user
  54. for sid in webnotes.conn.sql("""select sid from tabSessions where user=%s""", user):
  55. if not (keep_current and webnotes.session.sid == sid[0]):
  56. webnotes.cache().delete_value("session:" + sid[0])
  57. if keep_current:
  58. webnotes.conn.sql('delete from tabSessions where user=%s and sid!=%s', (user,
  59. webnotes.session.sid))
  60. else:
  61. webnotes.conn.sql('delete from tabSessions where user=%s', user)
  62. def get():
  63. """get session boot info"""
  64. # check if cache exists
  65. if not getattr(conf,'auto_cache_clear',None):
  66. cache = webnotes.cache().get_value('bootinfo:' + webnotes.session.user)
  67. if cache:
  68. cache['from_cache'] = 1
  69. return cache
  70. if not webnotes.cache().get_stats():
  71. webnotes.msgprint("memcached is not working / stopped. Please start memcached for best results.")
  72. # if not create it
  73. from webnotes.boot import get_bootinfo
  74. bootinfo = get_bootinfo()
  75. webnotes.cache().set_value('bootinfo:' + webnotes.session.user, bootinfo)
  76. return bootinfo
  77. class Session:
  78. def __init__(self, user=None):
  79. self.user = user
  80. self.sid = webnotes.form_dict.get('sid') or webnotes.incoming_cookies.get('sid', 'Guest')
  81. self.data = webnotes._dict({'user':user,'data': webnotes._dict({})})
  82. self.time_diff = None
  83. if webnotes.form_dict.get('cmd')=='login':
  84. self.start()
  85. return
  86. self.load()
  87. def start(self):
  88. """start a new session"""
  89. import os
  90. import webnotes
  91. import webnotes.utils
  92. # generate sid
  93. if webnotes.login_manager.user=='Guest':
  94. sid = 'Guest'
  95. else:
  96. sid = webnotes.generate_hash()
  97. self.data['user'] = webnotes.login_manager.user
  98. self.data['sid'] = sid
  99. self.data['data']['user'] = webnotes.login_manager.user
  100. self.data['data']['session_ip'] = os.environ.get('REMOTE_ADDR')
  101. self.data['data']['last_updated'] = webnotes.utils.now()
  102. self.data['data']['session_expiry'] = self.get_expiry_period()
  103. # get ipinfo
  104. if webnotes.conn.get_global('get_ip_info'):
  105. self.get_ipinfo()
  106. # insert session
  107. self.insert_session_record()
  108. # update profile
  109. webnotes.conn.sql("""UPDATE tabProfile SET last_login = '%s', last_ip = '%s'
  110. where name='%s'""" % (webnotes.utils.now(), webnotes.remote_ip, self.data['user']))
  111. # set cookies to write
  112. webnotes.session = self.data
  113. webnotes.cookie_manager.set_cookies()
  114. def insert_session_record(self):
  115. webnotes.conn.sql("""insert into tabSessions
  116. (sessiondata, user, lastupdate, sid, status)
  117. values (%s , %s, NOW(), %s, 'Active')""",
  118. (str(self.data['data']), self.data['user'], self.data['sid']))
  119. # also add to memcache
  120. webnotes.cache().set_value("session:" + self.data.sid, self.data)
  121. def load(self):
  122. """non-login request: load a session"""
  123. import webnotes
  124. data = self.get_session_record()
  125. if data:
  126. self.data = webnotes._dict({'data': data,
  127. 'user':data.user, 'sid': self.sid})
  128. else:
  129. self.start_as_guest()
  130. def get_session_record(self):
  131. """get session record, or return the standard Guest Record"""
  132. # check in memcache
  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. # check if expired
  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. # update session in db
  187. time_diff = None
  188. last_updated = webnotes.cache().get_value("last_db_session_update:" + self.sid)
  189. if last_updated:
  190. time_diff = webnotes.utils.time_diff_in_seconds(webnotes.utils.now(),
  191. last_updated)
  192. if webnotes.session['user'] != 'Guest' and \
  193. ((not time_diff) or (time_diff > 1800)):
  194. # database persistence is secondary, don't update it too often
  195. webnotes.conn.sql("""update tabSessions set sessiondata=%s,
  196. lastupdate=NOW() where sid=%s""" , (str(self.data['data']),
  197. self.data['sid']))
  198. # update timestamp of update
  199. webnotes.cache().set_value("last_db_session_update:" + self.sid,
  200. webnotes.utils.now())
  201. if webnotes.request.cmd!="webnotes.sessions.clear":
  202. webnotes.cache().set_value("session:" + self.sid, self.data)
  203. def get_expiry_period(self):
  204. exp_sec = webnotes.conn.get_default("session_expiry") or \
  205. webnotes.conn.get_value('Control Panel', None, 'session_expiry') or '06:00:00'
  206. # incase seconds is missing
  207. if len(exp_sec.split(':')) == 2:
  208. exp_sec = exp_sec + ':00'
  209. return exp_sec
  210. def get_ipinfo(self):
  211. import os
  212. try:
  213. import pygeoip
  214. except:
  215. return
  216. gi = pygeoip.GeoIP('data/GeoIP.dat')
  217. self.data['data']['ipinfo'] = {'countryName': gi.country_name_by_addr(os.environ.get('REMOTE_ADDR'))}