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.
 
 
 
 
 
 

374 lines
11 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. import webnotes
  24. import webnotes.db
  25. import webnotes.utils
  26. import webnotes.profile
  27. import conf
  28. # =================================================================================
  29. # HTTPRequest
  30. # =================================================================================
  31. class HTTPRequest:
  32. def __init__(self):
  33. # Get Environment variables
  34. self.domain = webnotes.get_env_vars('HTTP_HOST')
  35. if self.domain and self.domain.startswith('www.'):
  36. self.domain = self.domain[4:]
  37. webnotes.remote_ip = webnotes.get_env_vars('REMOTE_ADDR')
  38. # load cookies
  39. webnotes.cookie_manager = CookieManager()
  40. # set db
  41. self.set_db()
  42. # -----------------------------
  43. # start transaction
  44. webnotes.conn.begin()
  45. # login
  46. webnotes.login_manager = LoginManager()
  47. # start session
  48. webnotes.session_obj = Session()
  49. webnotes.session = webnotes.session_obj.data
  50. # check status
  51. if webnotes.conn.get_global("__session_status")=='stop':
  52. webnotes.msgprint(webnotes.conn.get_global("__session_status_message"))
  53. raise webnotes.SessionStopped('Session Stopped')
  54. # load profile
  55. self.setup_profile()
  56. # run login triggers
  57. if webnotes.form_dict.get('cmd')=='login':
  58. webnotes.login_manager.run_trigger('on_login_post_session')
  59. # write out cookies
  60. webnotes.cookie_manager.set_cookies()
  61. webnotes.conn.commit()
  62. # end transaction
  63. # -----------------------------
  64. # setup profile
  65. # -------------
  66. def setup_profile(self):
  67. webnotes.user = webnotes.profile.Profile()
  68. # load the profile data
  69. if not webnotes.session['data'].get('profile'):
  70. webnotes.session['data']['profile'] = webnotes.user.load_profile()
  71. webnotes.user.load_from_session(webnotes.session['data']['profile'])
  72. # set database login
  73. # ------------------
  74. def get_db_name(self):
  75. """get database name from conf"""
  76. return conf.db_name
  77. def set_db(self, ac_name = None):
  78. """connect to db, from ac_name or db_name"""
  79. webnotes.conn = webnotes.db.Database(user = self.get_db_name(), \
  80. password = getattr(conf,'db_password', ''))
  81. # =================================================================================
  82. # Login Manager
  83. # =================================================================================
  84. class LoginManager:
  85. def __init__(self):
  86. if webnotes.form_dict.get('cmd')=='login':
  87. # clear cache
  88. from webnotes.session_cache import clear_cache
  89. clear_cache(webnotes.form_dict.get('usr'))
  90. self.authenticate()
  91. self.post_login()
  92. webnotes.response['message'] = 'Logged In'
  93. # run triggers, write cookies
  94. # ---------------------------
  95. def post_login(self):
  96. self.run_trigger()
  97. self.validate_ip_address()
  98. self.validate_hour()
  99. # check password
  100. # --------------
  101. def authenticate(self, user=None, pwd=None):
  102. if not (user and pwd):
  103. user, pwd = webnotes.form_dict.get('usr'), webnotes.form_dict.get('pwd')
  104. if not (user and pwd):
  105. self.fail('Incomplete login details')
  106. self.check_if_enabled(user)
  107. self.user = self.check_password(user, pwd)
  108. def check_if_enabled(self, user):
  109. """raise exception if user not enabled"""
  110. if user=='Administrator': return
  111. if not int(webnotes.conn.get_value('Profile', user, 'enabled')):
  112. self.fail('User disabled or missing')
  113. def check_password(self, user, pwd):
  114. """check password"""
  115. user = webnotes.conn.sql("""select `user` from __Auth where `user`=%s
  116. and `password`=password(%s)""", (user, pwd))
  117. if not user:
  118. self.fail('Incorrect password')
  119. else:
  120. return user[0][0] # in correct case
  121. def fail(self, message):
  122. webnotes.response['message'] = message
  123. raise webnotes.AuthenticationError
  124. def run_trigger(self, method='on_login'):
  125. try:
  126. from startup import event_handlers
  127. if hasattr(event_handlers, method):
  128. getattr(event_handlers, method)(self)
  129. return
  130. except ImportError, e:
  131. pass
  132. def validate_ip_address(self):
  133. """check if IP Address is valid"""
  134. ip_list = webnotes.conn.get_value('Profile', self.user, 'restrict_ip', ignore=True)
  135. if not ip_list:
  136. return
  137. ip_list = ip_list.replace(",", "\n").split('\n')
  138. ip_list = [i.strip() for i in ip_list]
  139. for ip in ip_list:
  140. if webnotes.remote_ip.startswith(ip):
  141. return
  142. webnotes.msgprint('Not allowed from this IP Address')
  143. raise webnotes.AuthenticationError
  144. def validate_hour(self):
  145. """check if user is logging in during restricted hours"""
  146. login_before = int(webnotes.conn.get_value('Profile', self.user, 'login_before', ignore=True) or 0)
  147. login_after = int(webnotes.conn.get_value('Profile', self.user, 'login_after', ignore=True) or 0)
  148. if not (login_before or login_after):
  149. return
  150. from webnotes.utils import now_datetime
  151. current_hour = int(now_datetime().strftime('%H'))
  152. if login_before and current_hour > login_before:
  153. webnotes.msgprint('Not allowed to login after restricted hour', raise_exception=1)
  154. if login_after and current_hour < login_after:
  155. webnotes.msgprint('Not allowed to login before restricted hour', raise_exception=1)
  156. def login_as_guest(self):
  157. """login as guest"""
  158. self.user = 'Guest'
  159. self.post_login()
  160. def logout(self, arg='', user=None):
  161. if not user: user = webnotes.session.get('user')
  162. self.user = user
  163. self.run_trigger('on_logout')
  164. if user in ['demo@erpnext.com', 'Administrator']:
  165. webnotes.conn.sql('delete from tabSessions where sid=%s', webnotes.session.get('sid'))
  166. else:
  167. webnotes.conn.sql('delete from tabSessions where user=%s', user)
  168. # =================================================================================
  169. # Cookie Manager
  170. # =================================================================================
  171. class CookieManager:
  172. def __init__(self):
  173. import Cookie
  174. webnotes.cookies = Cookie.SimpleCookie()
  175. self.get_incoming_cookies()
  176. def get_incoming_cookies(self):
  177. import os
  178. cookies = {}
  179. if 'HTTP_COOKIE' in os.environ:
  180. c = os.environ['HTTP_COOKIE']
  181. webnotes.cookies.load(c)
  182. for c in webnotes.cookies.values():
  183. cookies[c.key] = c.value
  184. webnotes.incoming_cookies = cookies
  185. def set_cookies(self):
  186. if webnotes.session.get('sid'):
  187. webnotes.cookies['sid'] = webnotes.session['sid']
  188. # sid expires in 3 days
  189. import datetime
  190. expires = datetime.datetime.now() + datetime.timedelta(days=3)
  191. webnotes.cookies['sid']['expires'] = expires.strftime('%a, %d %b %Y %H:%M:%S')
  192. webnotes.cookies['sid']['path'] = '/'
  193. def set_remember_me(self):
  194. if webnotes.utils.cint(webnotes.form_dict.get('remember_me')):
  195. remember_days = webnotes.conn.get_value('Control Panel',None,'remember_for_days') or 7
  196. webnotes.cookies['remember_me'] = 1
  197. import datetime
  198. expires = datetime.datetime.now() + datetime.timedelta(days=remember_days)
  199. for k in webnotes.cookies.keys():
  200. webnotes.cookies[k]['expires'] = expires.strftime('%a, %d %b %Y %H:%M:%S')
  201. # =================================================================================
  202. # Session
  203. # =================================================================================
  204. class Session:
  205. def __init__(self, user=None):
  206. self.user = user
  207. self.sid = webnotes.form_dict.get('sid') or webnotes.incoming_cookies.get('sid', 'Guest')
  208. self.data = {'user':user,'data':{}}
  209. if webnotes.form_dict.get('cmd')=='login':
  210. self.start()
  211. return
  212. self.load()
  213. # start a session
  214. # ---------------
  215. def get_session_record(self):
  216. """get session record, or return the standard Guest Record"""
  217. r = webnotes.conn.sql("""select user, sessiondata, status from
  218. tabSessions where sid='%s'""" % self.sid)
  219. if not r:
  220. self.sid = 'Guest'
  221. r = webnotes.conn.sql("""select user, sessiondata, status from
  222. tabSessions where sid='%s'""" % self.sid)
  223. return r and r[0] or None
  224. def load(self):
  225. """non-login request: load a session"""
  226. import webnotes
  227. r = self.get_session_record()
  228. if r:
  229. self.data = {'data': (r[1] and eval(r[1]) or {}),
  230. 'user':r[0], 'sid': self.sid}
  231. else:
  232. self.start_as_guest()
  233. def start_as_guest(self):
  234. """all guests share the same 'Guest' session"""
  235. webnotes.login_manager.login_as_guest()
  236. self.start()
  237. def start(self):
  238. """start a new session"""
  239. import os
  240. import webnotes
  241. import webnotes.utils
  242. # generate sid
  243. if webnotes.login_manager.user=='Guest':
  244. sid = 'Guest'
  245. else:
  246. sid = webnotes.utils.generate_hash()
  247. self.data['user'] = webnotes.login_manager.user
  248. self.data['sid'] = sid
  249. self.data['data']['session_ip'] = os.environ.get('REMOTE_ADDR');
  250. self.data['data']['tenant_id'] = webnotes.form_dict.get('tenant_id', 0)
  251. # get ipinfo
  252. if webnotes.conn.get_global('get_ip_info'):
  253. self.get_ipinfo()
  254. # insert session
  255. self.insert_session_record()
  256. # update profile
  257. webnotes.conn.sql("""UPDATE tabProfile SET last_login = '%s', last_ip = '%s'
  258. where name='%s'""" % (webnotes.utils.now(), webnotes.remote_ip, self.data['user']))
  259. # set cookies to write
  260. webnotes.session = self.data
  261. webnotes.cookie_manager.set_cookies()
  262. def update(self):
  263. """extend session expiry"""
  264. if webnotes.session['user'] != 'Guest':
  265. self.check_expired()
  266. webnotes.conn.sql("""update tabSessions set sessiondata=%s, user=%s, lastupdate=NOW()
  267. where sid=%s""" , (str(self.data['data']), self.data['user'], self.data['sid']))
  268. # check expired
  269. # -------------
  270. def check_expired(self):
  271. """expire non-guest sessions"""
  272. exp_sec = webnotes.conn.get_value('Control Panel', None, 'session_expiry') or '06:00:00'
  273. # incase seconds is missing
  274. if len(exp_sec.split(':')) == 2:
  275. exp_sec = exp_sec + ':00'
  276. # set sessions as expired
  277. webnotes.conn.sql("""delete from tabSessions
  278. where TIMEDIFF(NOW(), lastupdate) > TIME(%s) and sid!='Guest'""", exp_sec)
  279. def get_ipinfo(self):
  280. import os
  281. try:
  282. import pygeoip
  283. except:
  284. return
  285. gi = pygeoip.GeoIP('data/GeoIP.dat')
  286. self.data['data']['ipinfo'] = {'countryName': gi.country_name_by_addr(os.environ.get('REMOTE_ADDR'))}
  287. def insert_session_record(self):
  288. webnotes.conn.sql("""insert into tabSessions
  289. (sessiondata, user, lastupdate, sid, status)
  290. values (%s , %s, NOW(), %s, 'Active')""",
  291. (str(self.data['data']), self.data['user'], self.data['sid']))