view_manager.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. from array import array
  2. import threading
  3. from flask import session,Flask,request, jsonify
  4. import flask
  5. from utility.app_logging import logger_name
  6. import logging
  7. import persistence
  8. import Model.isp_model as isp_model
  9. import Model.model_manager as model_manager
  10. from werkzeug.security import check_password_hash,generate_password_hash
  11. import View.view_privilege as privileges
  12. import Modules.Inventory.inventory_view as inventory_view
  13. from datetime import timedelta
  14. import View.view_error_management as view_error_management
  15. from flask_limiter import Limiter
  16. from flask_limiter.util import get_remote_address
  17. logger = logging.getLogger(logger_name + ".VIEW")
  18. __app__ = Flask("OpenIsp")
  19. __app__.secret_key = "aseqzdwxc"
  20. __app__.permanent_session_lifetime = timedelta(minutes=2)
  21. __app__.logger = logger
  22. #CORS(__app__)
  23. __resource_array__ : array
  24. __id_counter__ : int = 1
  25. limiter = Limiter(__app__,key_func=get_remote_address,default_limits=["500 per minute"])
  26. limiter.logger = logger
  27. from werkzeug.serving import make_server
  28. class ServerThread(threading.Thread):
  29. def __init__(self, app,ip,port):
  30. threading.Thread.__init__(self)
  31. self.server = make_server(ip, port, app)
  32. self.ctx = app.app_context()
  33. self.ctx.push()
  34. def run(self):
  35. logger.info('starting server')
  36. self.server.serve_forever()
  37. def shutdown(self):
  38. self.server.shutdown()
  39. __server_process__ : ServerThread
  40. def get_user_privilege() :
  41. return privileges.get_privileges_from_user(session["user_account_id"])
  42. def init() :
  43. privileges.init()
  44. view_error_management.define_error_management(__app__)
  45. @__app__.before_request
  46. def before_request_func():
  47. global __id_counter__
  48. logger.debug("before_request processing")
  49. logger.debug("request from " + request.remote_addr)
  50. logger.debug("request header" + str(request.headers.__dict__))
  51. if request.json :
  52. logger.debug("request json body : " + str(request.json))
  53. if not "client_id" in session :
  54. session["client_id"] = str(__id_counter__)
  55. logger.debug("client_id is " + session["client_id"])
  56. __id_counter__ = __id_counter__ + 1
  57. if not request.path == "/api/login" and not "username" in session :
  58. logger.warning("Unauthorized client with id " + session["client_id"] + " try to access application")
  59. resp = jsonify({'message' : 'Unauthorized'})
  60. resp.status_code = 401
  61. return resp
  62. if "username" in session :
  63. logger.debug("request from " + session["username"])
  64. @__app__.after_request
  65. def after_request(response):
  66. header = response.headers
  67. # adding this to the header to allow cross origin
  68. # for exemple origin cross origin is when website with javascript has it's server (origin 1)
  69. # and the javascript call some request on another server (origin 2), typically our API.
  70. header['Access-Control-Allow-Origin'] = '*'
  71. header['Access-Control-Allow-Methods'] = 'GET,DELETE,UPDATE,HEAD,OPTIONS,POST,PUT'
  72. header['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  73. return response
  74. @__app__.route('/api/login',methods = ['POST'])
  75. def login():
  76. _json = request.json
  77. _username = _json['username']
  78. _password = _json['password']
  79. with persistence.get_Session_Instance() as sess :
  80. Item = sess.query(isp_model.user_account).filter(isp_model.user_account.nickname == _username).first()
  81. if not isinstance(Item,isp_model.user_account) :
  82. logger.warning("user tried to login with unknown account name : " + _username)
  83. resp = jsonify({'message' : 'Bad Request - user account not found'})
  84. resp.status_code = 400
  85. return resp
  86. if not check_password_hash(Item.password,_password) :
  87. logger.warning("user with account name '" + _username + "' tried to login with invalid password")
  88. resp = jsonify({'message' : 'Bad Request - invalid password for this account'})
  89. resp.status_code = 400
  90. return resp
  91. session["username"] = _username
  92. session["user_account_id"] = Item.id
  93. logger.info("account " + _username + " logged IN successfully with id : " + session["client_id"])
  94. resp = jsonify({'message' : 'login successful'})
  95. resp.status_code = 200
  96. return resp
  97. @__app__.route('/api/logout',methods = ['DELETE'])
  98. def logout():
  99. logger.info("account " + session["username"] + " logged OUT with id : " + session["client_id"])
  100. session.clear()
  101. return jsonify('logout')
  102. @__app__.route('/api/password',methods = ['POST'])
  103. def change_password():
  104. _json = request.json
  105. _old_password = _json['old_password']
  106. _password = _json['new_password']
  107. with persistence.get_Session_Instance() as sess :
  108. Item : isp_model.user_account = sess.query(isp_model.user_account).filter(isp_model.user_account.id == session["user_account_id"]).first()
  109. if not check_password_hash(Item.password,_password) :
  110. raise Exception("old password is incorrect")
  111. Item.password = generate_password_hash(_password)
  112. sess.commit()
  113. return jsonify('password changed')
  114. @__app__.route('/routes',methods = ['GET'])
  115. @privileges.manager.require_authorization(required_role=inventory_view.inventory_admin_role,get_privilege_func=get_user_privilege)
  116. def routes():
  117. routes = []
  118. for route in __app__.url_map.iter_rules():
  119. routes.append('%s' % route)
  120. return jsonify(routes)
  121. def run() :
  122. global __server_process__
  123. __server_process__ = ServerThread(__app__,"0.0.0.0",8000)
  124. __server_process__.start()
  125. logger.info('View server started')
  126. def stop() :
  127. global __server_process__
  128. __server_process__.shutdown()
  129. logger.info('View server stopped')
  130. def register_blueprint(blueprint : flask.Blueprint) :
  131. logger.info("registering view (blueprint) : '" + blueprint.name + "' with prefix '" + blueprint.url_prefix +"'")
  132. __app__.register_blueprint(blueprint)
  133. @privileges.manager.require_authorization(required_role=inventory_view.inventory_read_only_role,get_privilege_func=get_user_privilege)
  134. def tab():
  135. return jsonify([2,5,7])
  136. __app__.add_url_rule("/tab","/tab",tab)