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

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