view_manager.py 5.7 KB

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