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.
 
 
 
 
 
 

251 lines
7.5 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. import webnotes
  5. import webnotes.db
  6. import webnotes.utils
  7. import webnotes.profile
  8. from webnotes import conf
  9. from webnotes.sessions import Session
  10. class HTTPRequest:
  11. def __init__(self):
  12. # Get Environment variables
  13. self.domain = webnotes.request.host
  14. if self.domain and self.domain.startswith('www.'):
  15. self.domain = self.domain[4:]
  16. # language
  17. self.set_lang(webnotes.get_request_header('HTTP_ACCEPT_LANGUAGE'))
  18. # load cookies
  19. webnotes.local.cookie_manager = CookieManager()
  20. # override request method. All request to be of type POST, but if _type == "POST" then commit
  21. if webnotes.form_dict.get("_type"):
  22. webnotes.local.request_method = webnotes.form_dict.get("_type")
  23. del webnotes.form_dict["_type"]
  24. # set db
  25. self.connect()
  26. # login
  27. webnotes.local.login_manager = LoginManager()
  28. # start session
  29. webnotes.local.session_obj = Session()
  30. webnotes.local.session = webnotes.local.session_obj.data
  31. # check status
  32. if webnotes.conn.get_global("__session_status")=='stop':
  33. webnotes.msgprint(webnotes.conn.get_global("__session_status_message"))
  34. raise webnotes.SessionStopped('Session Stopped')
  35. # load profile
  36. self.setup_profile()
  37. # run login triggers
  38. if webnotes.form_dict.get('cmd')=='login':
  39. webnotes.local.login_manager.run_trigger('on_session_creation')
  40. # write out cookies
  41. webnotes.local.cookie_manager.set_cookies()
  42. def set_lang(self, lang):
  43. import translate
  44. lang_list = translate.get_all_languages() or []
  45. if not lang:
  46. return
  47. if ";" in lang: # not considering weightage
  48. lang = lang.split(";")[0]
  49. if "," in lang:
  50. lang = lang.split(",")
  51. else:
  52. lang = [lang]
  53. for l in lang:
  54. code = l.strip()
  55. if code in lang_list:
  56. webnotes.local.lang = code
  57. return
  58. # check if parent language (pt) is setup, if variant (pt-BR)
  59. if "-" in code:
  60. code = code.split("-")[0]
  61. if code in lang_list:
  62. webnotes.local.lang = code
  63. return
  64. def setup_profile(self):
  65. webnotes.local.user = webnotes.profile.Profile()
  66. def get_db_name(self):
  67. """get database name from conf"""
  68. return conf.db_name
  69. def connect(self, ac_name = None):
  70. """connect to db, from ac_name or db_name"""
  71. webnotes.local.conn = webnotes.db.Database(user = self.get_db_name(), \
  72. password = getattr(conf,'db_password', ''))
  73. class LoginManager:
  74. def __init__(self):
  75. if webnotes.form_dict.get('cmd')=='login':
  76. # clear cache
  77. webnotes.clear_cache(user = webnotes.form_dict.get('usr'))
  78. self.authenticate()
  79. self.post_login()
  80. info = webnotes.conn.get_value("Profile", self.user, ["user_type", "first_name", "last_name"], as_dict=1)
  81. if info.user_type=="Website User":
  82. webnotes._response.set_cookie("system_user", "no")
  83. webnotes.response["message"] = "No App"
  84. else:
  85. webnotes._response.set_cookie("system_user", "yes")
  86. webnotes.response['message'] = 'Logged In'
  87. full_name = " ".join(filter(None, [info.first_name, info.last_name]))
  88. webnotes.response["full_name"] = full_name
  89. webnotes._response.set_cookie("full_name", full_name)
  90. webnotes._response.set_cookie("user_id", self.user)
  91. def post_login(self):
  92. self.run_trigger('on_login')
  93. self.validate_ip_address()
  94. self.validate_hour()
  95. def authenticate(self, user=None, pwd=None):
  96. if not (user and pwd):
  97. user, pwd = webnotes.form_dict.get('usr'), webnotes.form_dict.get('pwd')
  98. if not (user and pwd):
  99. self.fail('Incomplete login details')
  100. self.check_if_enabled(user)
  101. self.user = self.check_password(user, pwd)
  102. def check_if_enabled(self, user):
  103. """raise exception if user not enabled"""
  104. from webnotes.utils import cint
  105. if user=='Administrator': return
  106. if not cint(webnotes.conn.get_value('Profile', user, 'enabled')):
  107. self.fail('User disabled or missing')
  108. def check_password(self, user, pwd):
  109. """check password"""
  110. user = webnotes.conn.sql("""select `user` from __Auth where `user`=%s
  111. and `password`=password(%s)""", (user, pwd))
  112. if not user:
  113. self.fail('Incorrect password')
  114. else:
  115. return user[0][0] # in correct case
  116. def fail(self, message):
  117. webnotes.response['message'] = message
  118. raise webnotes.AuthenticationError
  119. def run_trigger(self, method='on_login'):
  120. for method in webnotes.get_hooks().get("method", []):
  121. webnotes.get_attr(method)(self)
  122. def validate_ip_address(self):
  123. """check if IP Address is valid"""
  124. ip_list = webnotes.conn.get_value('Profile', self.user, 'restrict_ip', ignore=True)
  125. if not ip_list:
  126. return
  127. ip_list = ip_list.replace(",", "\n").split('\n')
  128. ip_list = [i.strip() for i in ip_list]
  129. for ip in ip_list:
  130. if webnotes.get_request_header('REMOTE_ADDR', '').startswith(ip) or webnotes.get_request_header('X-Forwarded-For', '').startswith(ip):
  131. return
  132. webnotes.msgprint('Not allowed from this IP Address')
  133. raise webnotes.AuthenticationError
  134. def validate_hour(self):
  135. """check if user is logging in during restricted hours"""
  136. login_before = int(webnotes.conn.get_value('Profile', self.user, 'login_before', ignore=True) or 0)
  137. login_after = int(webnotes.conn.get_value('Profile', self.user, 'login_after', ignore=True) or 0)
  138. if not (login_before or login_after):
  139. return
  140. from webnotes.utils import now_datetime
  141. current_hour = int(now_datetime().strftime('%H'))
  142. if login_before and current_hour > login_before:
  143. webnotes.msgprint('Not allowed to login after restricted hour', raise_exception=1)
  144. if login_after and current_hour < login_after:
  145. webnotes.msgprint('Not allowed to login before restricted hour', raise_exception=1)
  146. def login_as_guest(self):
  147. """login as guest"""
  148. self.user = 'Guest'
  149. self.post_login()
  150. def logout(self, arg='', user=None):
  151. if not user: user = webnotes.session.user
  152. self.run_trigger('on_logout')
  153. if user in ['demo@erpnext.com', 'Administrator']:
  154. webnotes.conn.sql('delete from tabSessions where sid=%s', webnotes.session.get('sid'))
  155. webnotes.cache().delete_value("session:" + webnotes.session.get("sid"))
  156. else:
  157. from webnotes.sessions import clear_sessions
  158. clear_sessions(user)
  159. if user == webnotes.session.user:
  160. webnotes.session.sid = ""
  161. webnotes._response.delete_cookie("full_name")
  162. webnotes._response.delete_cookie("user_id")
  163. webnotes._response.delete_cookie("sid")
  164. webnotes._response.set_cookie("full_name", "")
  165. webnotes._response.set_cookie("user_id", "")
  166. webnotes._response.set_cookie("sid", "")
  167. class CookieManager:
  168. def __init__(self):
  169. pass
  170. def set_cookies(self):
  171. if not webnotes.session.get('sid'): return
  172. import datetime
  173. # sid expires in 3 days
  174. expires = datetime.datetime.now() + datetime.timedelta(days=3)
  175. if webnotes.session.sid:
  176. webnotes._response.set_cookie("sid", webnotes.session.sid, expires = expires)
  177. if webnotes.session.session_country:
  178. webnotes._response.set_cookie('country', webnotes.session.get("session_country"))
  179. def set_remember_me(self):
  180. from webnotes.utils import cint
  181. if not cint(webnotes.form_dict.get('remember_me')): return
  182. remember_days = webnotes.conn.get_value('Control Panel', None,
  183. 'remember_for_days') or 7
  184. import datetime
  185. expires = datetime.datetime.now() + \
  186. datetime.timedelta(days=remember_days)
  187. webnotes._response.set_cookie["remember_me"] = 1
  188. def _update_password(user, password):
  189. webnotes.conn.sql("""insert into __Auth (user, `password`)
  190. values (%s, password(%s))
  191. on duplicate key update `password`=password(%s)""", (user,
  192. password, password))
  193. @webnotes.whitelist()
  194. def get_logged_user():
  195. return webnotes.session.user