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.
 
 
 
 
 
 

427 lines
12 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. import webnotes.db
  24. import webnotes.utils
  25. import webnotes.profile
  26. import conf
  27. # =================================================================================
  28. # HTTPRequest
  29. # =================================================================================
  30. class HTTPRequest:
  31. def __init__(self):
  32. # Get Environment variables
  33. self.domain = webnotes.get_env_vars('HTTP_HOST')
  34. if self.domain and self.domain.startswith('www.'):
  35. self.domain = self.domain[4:]
  36. webnotes.remote_ip = webnotes.get_env_vars('REMOTE_ADDR')
  37. # load cookies
  38. webnotes.cookie_manager = CookieManager()
  39. # set db
  40. self.set_db()
  41. # -----------------------------
  42. # start transaction
  43. webnotes.conn.begin()
  44. # login
  45. webnotes.login_manager = LoginManager()
  46. # start session
  47. webnotes.session_obj = Session()
  48. webnotes.session = webnotes.session_obj.data
  49. # check status
  50. if webnotes.conn.get_global("__session_status")=='stop':
  51. webnotes.msgprint(webnotes.conn.get_global("__session_status_message"))
  52. raise webnotes.SessionStopped('Session Stopped')
  53. # run login triggers
  54. if webnotes.form_dict.get('cmd')=='login':
  55. webnotes.login_manager.run_trigger('on_login_post_session')
  56. # load profile
  57. self.setup_profile()
  58. # write out cookies
  59. webnotes.cookie_manager.set_cookies()
  60. webnotes.conn.commit()
  61. # end transaction
  62. # -----------------------------
  63. # setup profile
  64. # -------------
  65. def setup_profile(self):
  66. webnotes.user = webnotes.profile.Profile()
  67. # load the profile data
  68. if webnotes.session['data'].get('profile'):
  69. webnotes.user.load_from_session(webnotes.session['data']['profile'])
  70. else:
  71. webnotes.user.load_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. self.cp = None
  87. if webnotes.form_dict.get('cmd')=='login':
  88. # clear cache
  89. from webnotes.session_cache import clear_cache
  90. clear_cache(webnotes.form_dict.get('usr'))
  91. self.authenticate()
  92. self.post_login()
  93. webnotes.response['message'] = 'Logged In'
  94. # run triggers, write cookies
  95. # ---------------------------
  96. def post_login(self):
  97. self.run_trigger()
  98. self.validate_ip_address()
  99. self.validate_hour()
  100. # check password
  101. # --------------
  102. def authenticate(self, user=None, pwd=None):
  103. if not (user and pwd):
  104. user, pwd = webnotes.form_dict.get('usr'), webnotes.form_dict.get('pwd')
  105. if not (user and pwd):
  106. webnotes.response['message'] = 'Incomplete Login Details'
  107. raise webnotes.AuthenticationError
  108. # custom authentication (for single-sign on)
  109. self.load_control_panel()
  110. if hasattr(self.cp, 'authenticate'):
  111. self.user = self.cp.authenticate()
  112. # check the password
  113. if user=='Administrator':
  114. p = webnotes.conn.sql("""select name, first_name, last_name
  115. from tabProfile where name=%s
  116. and (`password`=%s OR `password`=PASSWORD(%s))""", (user, pwd, pwd), as_dict=1)
  117. else:
  118. p = webnotes.conn.sql("""select name, first_name, last_name
  119. from tabProfile where name=%s
  120. and (`password`=%s OR `password`=PASSWORD(%s))
  121. and IFNULL(enabled,0)=1""", (user, pwd, pwd), as_dict=1)
  122. if not p:
  123. webnotes.response['message'] = 'Authentication Failed'
  124. raise webnotes.AuthenticationError
  125. #webnotes.msgprint('Authentication Failed',raise_exception=1)
  126. p = p[0]
  127. self.user = p['name']
  128. self.user_fullname = (p.get('first_name') and (p.get('first_name') + ' ') or '') \
  129. + (p.get('last_name') or '')
  130. # triggers
  131. # --------
  132. def load_control_panel(self):
  133. import webnotes.model.code
  134. try:
  135. if not self.cp:
  136. self.cp = webnotes.model.code.get_obj('Control Panel')
  137. except Exception, e:
  138. webnotes.response['Control Panel Exception'] = webnotes.utils.getTraceback()
  139. # --------
  140. def run_trigger(self, method='on_login'):
  141. try:
  142. from startup import event_handlers
  143. if hasattr(event_handlers, method):
  144. getattr(event_handlers, method)(self)
  145. return
  146. except ImportError, e:
  147. pass
  148. # deprecated
  149. self.load_control_panel()
  150. if self.cp and hasattr(self.cp, method):
  151. getattr(self.cp, method)(self)
  152. # ip validation
  153. # -------------
  154. def validate_ip_address(self):
  155. ip_list = webnotes.conn.get_value('Profile', self.user, 'restrict_ip', ignore=True)
  156. if not ip_list:
  157. return
  158. ip_list = ip_list.replace(",", "\n").split('\n')
  159. ip_list = [i.strip() for i in ip_list]
  160. for ip in ip_list:
  161. if webnotes.remote_ip.startswith(ip):
  162. return
  163. webnotes.msgprint('Not allowed from this IP Address')
  164. raise webnotes.AuthenticationError
  165. def validate_hour(self):
  166. """
  167. check if user is logging in during restricted hours
  168. """
  169. login_before = int(webnotes.conn.get_value('Profile', self.user, 'login_before', ignore=True) or 0)
  170. login_after = int(webnotes.conn.get_value('Profile', self.user, 'login_after', ignore=True) or 0)
  171. if not (login_before or login_after):
  172. return
  173. from webnotes.utils import now_datetime
  174. current_hour = int(now_datetime().strftime('%H'))
  175. if login_before and current_hour > login_before:
  176. webnotes.msgprint('Not allowed to login after restricted hour', raise_exception=1)
  177. if login_after and current_hour < login_after:
  178. webnotes.msgprint('Not allowed to login before restricted hour', raise_exception=1)
  179. # login as guest
  180. # --------------
  181. def login_as_guest(self):
  182. self.user = 'Guest'
  183. self.post_login()
  184. # Logout
  185. # ------
  186. def call_on_logout_event(self):
  187. import webnotes.model.code
  188. cp = webnotes.model.code.get_obj('Control Panel', 'Control Panel')
  189. if hasattr(cp, 'on_logout'):
  190. cp.on_logout(self)
  191. def logout(self, arg='', user=None):
  192. if not user: user = webnotes.session.get('user')
  193. self.user = user
  194. self.run_trigger('on_logout')
  195. webnotes.conn.sql('delete from tabSessions where user=%s', user)
  196. # =================================================================================
  197. # Cookie Manager
  198. # =================================================================================
  199. class CookieManager:
  200. def __init__(self):
  201. import Cookie
  202. webnotes.cookies = Cookie.SimpleCookie()
  203. self.get_incoming_cookies()
  204. # get incoming cookies
  205. # --------------------
  206. def get_incoming_cookies(self):
  207. import os
  208. cookies = {}
  209. if 'HTTP_COOKIE' in os.environ:
  210. c = os.environ['HTTP_COOKIE']
  211. webnotes.cookies.load(c)
  212. for c in webnotes.cookies.values():
  213. cookies[c.key] = c.value
  214. webnotes.incoming_cookies = cookies
  215. # Set cookies
  216. # -----------
  217. def set_cookies(self):
  218. if webnotes.form_dict.get('cmd')=='logout':
  219. webnotes.cookies['account_id'] = ''
  220. else:
  221. webnotes.cookies['account_id'] = webnotes.conn.cur_db_name
  222. if webnotes.session.get('sid'):
  223. webnotes.cookies['sid'] = webnotes.session['sid']
  224. # sid expires in 3 days
  225. import datetime
  226. expires = datetime.datetime.now() + datetime.timedelta(days=3)
  227. webnotes.cookies['sid']['expires'] = expires.strftime('%a, %d %b %Y %H:%M:%S')
  228. # Set Remember Me
  229. # ---------------
  230. def set_remember_me(self):
  231. if webnotes.utils.cint(webnotes.form_dict.get('remember_me')):
  232. remember_days = webnotes.conn.get_value('Control Panel',None,'remember_for_days') or 7
  233. webnotes.cookies['remember_me'] = 1
  234. import datetime
  235. expires = datetime.datetime.now() + datetime.timedelta(days=remember_days)
  236. for k in webnotes.cookies.keys():
  237. webnotes.cookies[k]['expires'] = expires.strftime('%a, %d %b %Y %H:%M:%S')
  238. # =================================================================================
  239. # Session
  240. # =================================================================================
  241. class Session:
  242. def __init__(self, user=None):
  243. self.user = user
  244. self.sid = webnotes.form_dict.get('sid') or webnotes.incoming_cookies.get('sid')
  245. self.data = {'user':user,'data':{}}
  246. if webnotes.form_dict.get('cmd')=='login':
  247. self.start()
  248. return
  249. self.load()
  250. # start a session
  251. # ---------------
  252. def get_session_record(self):
  253. """get session record, or return the standard Guest Record"""
  254. r = webnotes.conn.sql("""select user, sessiondata, status from
  255. tabSessions where sid='%s'""" % self.sid)
  256. if not r:
  257. self.sid = 'Guest'
  258. r = webnotes.conn.sql("""select user, sessiondata, status from
  259. tabSessions where sid='%s'""" % self.sid)
  260. return r and r[0] or None
  261. def load(self):
  262. """non-login request: load a session"""
  263. import webnotes
  264. r = self.get_session_record()
  265. if r:
  266. self.data = {'data': (r[1] and eval(r[1]) or {}),
  267. 'user':r[0], 'sid': self.sid}
  268. else:
  269. self.start_as_guest()
  270. def start_as_guest(self):
  271. """all guests share the same 'Guest' session"""
  272. webnotes.login_manager.login_as_guest()
  273. self.start()
  274. def start(self):
  275. """start a new session"""
  276. import os
  277. import webnotes
  278. import webnotes.utils
  279. # generate sid
  280. if webnotes.login_manager.user=='Guest':
  281. sid = 'Guest'
  282. else:
  283. sid = webnotes.utils.generate_hash()
  284. self.data['user'] = webnotes.login_manager.user
  285. self.data['sid'] = sid
  286. self.data['data']['session_ip'] = os.environ.get('REMOTE_ADDR');
  287. self.data['data']['tenant_id'] = webnotes.form_dict.get('tenant_id', 0)
  288. # get ipinfo
  289. if webnotes.conn.get_global('get_ip_info'):
  290. self.get_ipinfo()
  291. # insert session
  292. try:
  293. self.insert_session_record()
  294. except Exception, e:
  295. if e.args[0]==1054:
  296. self.add_status_column()
  297. self.insert_session_record()
  298. else:
  299. raise e
  300. # update profile
  301. webnotes.conn.sql("""UPDATE tabProfile SET last_login = '%s', last_ip = '%s'
  302. where name='%s'""" % (webnotes.utils.now(), webnotes.remote_ip, self.data['user']))
  303. # set cookies to write
  304. webnotes.session = self.data
  305. webnotes.cookie_manager.set_cookies()
  306. def update(self):
  307. """extend session expiry"""
  308. if webnotes.session['user'] != 'Guest':
  309. self.check_expired()
  310. webnotes.conn.sql("""update tabSessions set sessiondata=%s, user=%s, lastupdate=NOW()
  311. where sid=%s""" , (str(self.data['data']), self.data['user'], self.data['sid']))
  312. # check expired
  313. # -------------
  314. def check_expired(self):
  315. """expire non-guest sessions"""
  316. exp_sec = webnotes.conn.get_value('Control Panel', None, 'session_expiry') or '6:00:00'
  317. # set sessions as expired
  318. try:
  319. webnotes.conn.sql("""delete from tabSessions
  320. where TIMEDIFF(NOW(), lastupdate) > TIME(%s) and sid!='Guest'""", exp_sec)
  321. except Exception, e:
  322. if e.args[0]==1054:
  323. self.add_status_column()
  324. # clear out old sessions
  325. webnotes.conn.sql("""delete from tabSessions where TIMEDIFF(NOW(), lastupdate)
  326. > TIME('72:00:00') and sid!='Guest'""")
  327. def get_ipinfo(self):
  328. import os
  329. try:
  330. import pygeoip
  331. except:
  332. return
  333. gi = pygeoip.GeoIP('data/GeoIP.dat')
  334. self.data['data']['ipinfo'] = {'countryName': gi.country_name_by_addr(os.environ.get('REMOTE_ADDR'))}
  335. def insert_session_record(self):
  336. webnotes.conn.sql("""insert into tabSessions
  337. (sessiondata, user, lastupdate, sid, status)
  338. values (%s , %s, NOW(), %s, 'Active')""",
  339. (str(self.data['data']), self.data['user'], self.data['sid']))