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

242 рядки
7.3 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. from webnotes.sessions import Session
  29. class HTTPRequest:
  30. def __init__(self):
  31. # Get Environment variables
  32. self.domain = webnotes.get_env_vars('HTTP_HOST')
  33. if self.domain and self.domain.startswith('www.'):
  34. self.domain = self.domain[4:]
  35. webnotes.remote_ip = webnotes.get_env_vars('REMOTE_ADDR')
  36. # load cookies
  37. webnotes.cookie_manager = CookieManager()
  38. # set db
  39. self.connect()
  40. webnotes.conn.begin()
  41. # login
  42. webnotes.login_manager = LoginManager()
  43. # start session
  44. webnotes.session_obj = Session()
  45. webnotes.session = webnotes.session_obj.data
  46. # check status
  47. if webnotes.conn.get_global("__session_status")=='stop':
  48. webnotes.msgprint(webnotes.conn.get_global("__session_status_message"))
  49. raise webnotes.SessionStopped('Session Stopped')
  50. # load profile
  51. self.setup_profile()
  52. # run login triggers
  53. if webnotes.form_dict.get('cmd')=='login':
  54. webnotes.login_manager.run_trigger('on_login_post_session')
  55. # write out cookies
  56. webnotes.cookie_manager.set_cookies()
  57. webnotes.conn.commit()
  58. def setup_profile(self):
  59. webnotes.user = webnotes.profile.Profile()
  60. def get_db_name(self):
  61. """get database name from conf"""
  62. return conf.db_name
  63. def connect(self, ac_name = None):
  64. """connect to db, from ac_name or db_name"""
  65. webnotes.conn = webnotes.db.Database(user = self.get_db_name(), \
  66. password = getattr(conf,'db_password', ''))
  67. class LoginManager:
  68. def __init__(self):
  69. if webnotes.form_dict.get('cmd')=='login':
  70. # clear cache
  71. from webnotes.sessions import clear_cache
  72. clear_cache(webnotes.form_dict.get('usr'))
  73. self.authenticate()
  74. self.post_login()
  75. webnotes.response['message'] = 'Logged In'
  76. def post_login(self):
  77. self.run_trigger()
  78. self.validate_ip_address()
  79. self.validate_hour()
  80. def authenticate(self, user=None, pwd=None):
  81. if not (user and pwd):
  82. user, pwd = webnotes.form_dict.get('usr'), webnotes.form_dict.get('pwd')
  83. if not (user and pwd):
  84. self.fail('Incomplete login details')
  85. self.check_if_enabled(user)
  86. self.user = self.check_password(user, pwd)
  87. def check_if_enabled(self, user):
  88. """raise exception if user not enabled"""
  89. from webnotes.utils import cint
  90. if user=='Administrator': return
  91. if not cint(webnotes.conn.get_value('Profile', user, 'enabled')):
  92. self.fail('User disabled or missing')
  93. def check_password(self, user, pwd):
  94. """check password"""
  95. user = webnotes.conn.sql("""select `user` from __Auth where `user`=%s
  96. and `password`=password(%s)""", (user, pwd))
  97. if not user:
  98. self.fail('Incorrect password')
  99. else:
  100. return user[0][0] # in correct case
  101. def fail(self, message):
  102. webnotes.response['message'] = message
  103. raise webnotes.AuthenticationError
  104. def run_trigger(self, method='on_login'):
  105. try:
  106. from startup import event_handlers
  107. if hasattr(event_handlers, method):
  108. getattr(event_handlers, method)(self)
  109. return
  110. except ImportError, e:
  111. pass
  112. def validate_ip_address(self):
  113. """check if IP Address is valid"""
  114. ip_list = webnotes.conn.get_value('Profile', self.user, 'restrict_ip', ignore=True)
  115. if not ip_list:
  116. return
  117. ip_list = ip_list.replace(",", "\n").split('\n')
  118. ip_list = [i.strip() for i in ip_list]
  119. for ip in ip_list:
  120. if webnotes.remote_ip.startswith(ip):
  121. return
  122. webnotes.msgprint('Not allowed from this IP Address')
  123. raise webnotes.AuthenticationError
  124. def validate_hour(self):
  125. """check if user is logging in during restricted hours"""
  126. login_before = int(webnotes.conn.get_value('Profile', self.user, 'login_before', ignore=True) or 0)
  127. login_after = int(webnotes.conn.get_value('Profile', self.user, 'login_after', ignore=True) or 0)
  128. if not (login_before or login_after):
  129. return
  130. from webnotes.utils import now_datetime
  131. current_hour = int(now_datetime().strftime('%H'))
  132. if login_before and current_hour > login_before:
  133. webnotes.msgprint('Not allowed to login after restricted hour', raise_exception=1)
  134. if login_after and current_hour < login_after:
  135. webnotes.msgprint('Not allowed to login before restricted hour', raise_exception=1)
  136. def login_as_guest(self):
  137. """login as guest"""
  138. self.user = 'Guest'
  139. self.post_login()
  140. def logout(self, arg='', user=None):
  141. if not user: user = webnotes.session.user
  142. self.user = user
  143. self.run_trigger('on_logout')
  144. if user in ['demo@erpnext.com', 'Administrator']:
  145. webnotes.conn.sql('delete from tabSessions where sid=%s', webnotes.session.get('sid'))
  146. webnotes.cache().delete_value("session:" + webnotes.session.get("sid"))
  147. else:
  148. from webnotes.sessions import clear_sessions
  149. clear_sessions(user)
  150. class CookieManager:
  151. def __init__(self):
  152. import Cookie
  153. webnotes.cookies = Cookie.SimpleCookie()
  154. self.get_incoming_cookies()
  155. def get_incoming_cookies(self):
  156. import os
  157. cookies = {}
  158. if 'HTTP_COOKIE' in os.environ:
  159. c = os.environ['HTTP_COOKIE']
  160. webnotes.cookies.load(c)
  161. for c in webnotes.cookies.values():
  162. cookies[c.key] = c.value
  163. webnotes.incoming_cookies = cookies
  164. def set_cookies(self):
  165. if not webnotes.session.get('sid'): return
  166. import datetime
  167. # sid expires in 3 days
  168. expires = datetime.datetime.now() + datetime.timedelta(days=3)
  169. expires = expires.strftime('%a, %d %b %Y %H:%M:%S')
  170. webnotes.cookies[b'sid'] = webnotes.session['sid'].encode('utf-8')
  171. webnotes.cookies[b'sid'][b'expires'] = expires.encode('utf-8')
  172. webnotes.cookies[b'sid'][b'path'] = b'/'
  173. def set_remember_me(self):
  174. from webnotes.utils import cint
  175. if not cint(webnotes.form_dict.get('remember_me')): return
  176. remember_days = webnotes.conn.get_value('Control Panel', None,
  177. 'remember_for_days') or 7
  178. import datetime
  179. expires = datetime.datetime.now() + \
  180. datetime.timedelta(days=remember_days)
  181. expires = expires.strftime('%a, %d %b %Y %H:%M:%S')
  182. webnotes.cookies[b'remember_me'] = 1
  183. for k in webnotes.cookies.keys():
  184. webnotes.cookies[k][b'expires'] = expires.encode('utf-8')
  185. def update_password(user, password):
  186. webnotes.conn.sql("""insert into __Auth (user, `password`)
  187. values (%s, password(%s))
  188. on duplicate key update `password`=password(%s)""", (user,
  189. password, password))