view_manager.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. logger = logging.getLogger(logger_name + ".VIEW")
  18. __app__ = Flask("OpenIsp")
  19. __app__.secret_key = "aseqzdwxc"
  20. __app__.permanent_session_lifetime = timedelta(minutes=2)
  21. __resource_array__ : array
  22. __id_counter__ : int = 1
  23. limiter = Limiter(__app__,key_func=get_remote_address,default_limits=["500 per minute"])
  24. limiter.logger = logger
  25. from werkzeug.serving import make_server
  26. class ServerThread(threading.Thread):
  27. def __init__(self, app,ip,port):
  28. threading.Thread.__init__(self)
  29. self.server = make_server(ip, port, app)
  30. self.ctx = app.app_context()
  31. self.ctx.push()
  32. def run(self):
  33. logger.info('starting server')
  34. self.server.serve_forever()
  35. def shutdown(self):
  36. self.server.shutdown()
  37. __server_process__ : ServerThread
  38. def get_user_privilege() :
  39. return privileges.get_privileges_from_user(session["user_account_id"])
  40. def init() :
  41. @__app__.before_request
  42. def before_request_func():
  43. global __id_counter__
  44. logger.debug("before_request processing")
  45. logger.debug("request from " + request.remote_addr)
  46. logger.debug("request header" + str(request.headers.__dict__))
  47. logger.debug("request body" + request.json)
  48. if not "client_id" in session :
  49. session["client_id"] = str(__id_counter__)
  50. logger.debug("client_id is " + session["client_id"])
  51. __id_counter__ = __id_counter__ + 1
  52. if not request.path == "/api/login" and not "username" in session :
  53. logger.warning("Unauthorized client with id " + session["client_id"] + " try to access application")
  54. resp = jsonify({'message' : 'Unauthorized'})
  55. resp.status_code = 401
  56. return resp
  57. if "username" in session :
  58. logger.debug("request from " + session["username"])
  59. privileges.init()
  60. view_error_management.define_error_management(__app__)
  61. from flask.logging import default_handler
  62. __app__.logger.removeHandler(default_handler)
  63. for hand in logger.handlers :
  64. __app__.logger.addHandler(hand)
  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. def run() :
  101. global __server_process__
  102. __server_process__ = ServerThread(__app__,"0.0.0.0",8000)
  103. __server_process__.start()
  104. logger.info('View server started')
  105. def stop() :
  106. global __server_process__
  107. __server_process__.shutdown()
  108. logger.info('View server stopped')
  109. def add_blueprint(blueprint : flask.Blueprint) :
  110. __app__.register_blueprint(blueprint)
  111. @privileges.manager.require_authorization(required_role=inventory_view.inventory_read_only_role,get_privilege_func=get_user_privilege)
  112. def tab():
  113. return jsonify([2,5,7])
  114. __app__.add_url_rule("/tab","/tab",tab)