view_manager.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. @__app__.before_request
  45. def before_request_func():
  46. global __id_counter__
  47. logger.debug("before_request processing")
  48. logger.debug("request from " + request.remote_addr)
  49. logger.debug("request header" + str(request.headers.__dict__))
  50. if request.json :
  51. logger.debug("request json body : " + str(request.json))
  52. if not "client_id" in session :
  53. session["client_id"] = str(__id_counter__)
  54. logger.debug("client_id is " + session["client_id"])
  55. __id_counter__ = __id_counter__ + 1
  56. if not request.path == "/api/login" and not "username" in session :
  57. logger.warning("Unauthorized client with id " + session["client_id"] + " try to access application")
  58. resp = jsonify({'message' : 'Unauthorized'})
  59. resp.status_code = 401
  60. return resp
  61. if "username" in session :
  62. logger.debug("request from " + session["username"])
  63. privileges.init()
  64. view_error_management.define_error_management(__app__)
  65. @__app__.route('/api/login',methods = ['POST'])
  66. def login():
  67. _json = request.json
  68. _username = _json['username']
  69. _password = _json['password']
  70. with persistence.get_Session_Instance() as sess :
  71. Item = sess.query(isp_model.user_account).filter(isp_model.user_account.nickname == _username).first()
  72. if not isinstance(Item,isp_model.user_account) :
  73. logger.warning("user tried to login with unknown account name : " + _username)
  74. resp = jsonify({'message' : 'Bad Request - user account not found'})
  75. resp.status_code = 400
  76. return resp
  77. if not check_password_hash(Item.password,_password) :
  78. logger.warning("user with account name '" + _username + "' tried to login with invalid password")
  79. resp = jsonify({'message' : 'Bad Request - invalid password for this account'})
  80. resp.status_code = 400
  81. return resp
  82. session["username"] = _username
  83. session["user_account_id"] = Item.id
  84. logger.info("account " + _username + " logged IN successfully with id : " + session["client_id"])
  85. resp = jsonify({'message' : 'login successful'})
  86. resp.status_code = 200
  87. return resp
  88. @__app__.route('/api/logout',methods = ['POST'])
  89. def logout():
  90. logger.info("account " + session["username"] + " logged OUT with id : " + session["client_id"])
  91. session.clear()
  92. return jsonify('logout')
  93. @__app__.route('/routes',methods = ['GET'])
  94. @privileges.manager.require_authorization(required_role=inventory_view.inventory_admin_role,get_privilege_func=get_user_privilege)
  95. def routes():
  96. routes = []
  97. for route in __app__.url_map.iter_rules():
  98. routes.append('%s' % route)
  99. return jsonify(routes)
  100. @__app__.after_request
  101. def after_request(response):
  102. header = response.headers
  103. header['Access-Control-Allow-Origin'] = '*'
  104. header['Access-Control-Allow-Methods'] = 'GET,HEAD,OPTIONS,POST,PUT'
  105. header['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  106. return response
  107. def run() :
  108. global __server_process__
  109. __server_process__ = ServerThread(__app__,"0.0.0.0",8000)
  110. __server_process__.start()
  111. logger.info('View server started')
  112. def stop() :
  113. global __server_process__
  114. __server_process__.shutdown()
  115. logger.info('View server stopped')
  116. def add_blueprint(blueprint : flask.Blueprint) :
  117. __app__.register_blueprint(blueprint)
  118. @privileges.manager.require_authorization(required_role=inventory_view.inventory_read_only_role,get_privilege_func=get_user_privilege)
  119. def tab():
  120. return jsonify([2,5,7])
  121. __app__.add_url_rule("/tab","/tab",tab)