Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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