view_manager.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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. logger = logging.getLogger(logger_name + ".VIEW")
  16. __app__ = Flask("OpenIsp")
  17. __app__.secret_key = "aseqzdwxc"
  18. __app__.permanent_session_lifetime = timedelta(minutes=2)
  19. __resource_array__ : array
  20. __id_counter__ : int = 1
  21. from werkzeug.serving import make_server
  22. class ServerThread(threading.Thread):
  23. def __init__(self, app,ip,port):
  24. threading.Thread.__init__(self)
  25. self.server = make_server(ip, port, app)
  26. self.ctx = app.app_context()
  27. self.ctx.push()
  28. def run(self):
  29. logger.info('starting server')
  30. self.server.serve_forever()
  31. def shutdown(self):
  32. self.server.shutdown()
  33. __server_process__ : ServerThread
  34. def get_roles_ids() :
  35. return session["roles_ids"]
  36. def init() :
  37. @__app__.before_request
  38. def before_request_func():
  39. print(request.headers.__dict__)
  40. global __id_counter__
  41. logger.debug("before_request is running!")
  42. if not "client_id" in session :
  43. session["client_id"] = str(__id_counter__)
  44. logger.debug("client_id is " + session["client_id"])
  45. __id_counter__ = __id_counter__ + 1
  46. if not request.path == "/api/login" and not "username" in session :
  47. logger.warning("Unauthorized client with id " + session["client_id"] + " try to access application")
  48. resp = jsonify({'message' : 'Unauthorized'})
  49. resp.status_code = 401
  50. return resp
  51. if "username" in session :
  52. logger.debug("request from " + session["username"])
  53. privileges.init()
  54. view_error_management.define_error_management(__app__)
  55. from flask.logging import default_handler
  56. __app__.logger.removeHandler(default_handler)
  57. for hand in logger.handlers :
  58. __app__.logger.addHandler(hand)
  59. @__app__.route('/api/login',methods = ['POST'])
  60. def login():
  61. _json = request.json
  62. _username = _json['username']
  63. _password = _json['password']
  64. with persistence.get_Session_Instance() as sess :
  65. Item = sess.query(isp_model.user_account).filter(isp_model.user_account.nickname == _username).first()
  66. if not isinstance(Item,isp_model.user_account) :
  67. logger.warning("user tried to login with unknown account name : " + _username)
  68. resp = jsonify({'message' : 'Bad Request - user account not found'})
  69. resp.status_code = 400
  70. return resp
  71. if not check_password_hash(Item.password,_password) :
  72. logger.warning("user with account name '" + _username + "' tried to login with invalid password")
  73. resp = jsonify({'message' : 'Bad Request - invalid password for this account'})
  74. resp.status_code = 400
  75. return resp
  76. session["username"] = _username
  77. session["account_data"] = model_manager.ModelObjectToJsonString(Item)
  78. session["roles_ids"] = [inventory_view.inventory_read_only_role.id]
  79. logger.info("account " + _username + " logged IN successfully with id : " + session["client_id"])
  80. resp = jsonify({'message' : 'login successful'})
  81. resp.status_code = 200
  82. return resp
  83. @__app__.route('/api/logout',methods = ['POST'])
  84. def logout():
  85. logger.info("account " + session["username"] + " logged OUT with id : " + session["client_id"])
  86. session.clear()
  87. return jsonify('logout')
  88. @__app__.route('/routes',methods = ['GET'])
  89. @privileges.manager.require_authorization(required_role=inventory_view.inventory_admin_role,ids_getter=get_roles_ids)
  90. def routes():
  91. routes = []
  92. for route in __app__.url_map.iter_rules():
  93. routes.append('%s' % route)
  94. return jsonify(routes)
  95. def run() :
  96. global __server_process__
  97. __server_process__ = ServerThread(__app__,"0.0.0.0",8000)
  98. __server_process__.start()
  99. logger.info('View server started')
  100. def stop() :
  101. global __server_process__
  102. __server_process__.shutdown()
  103. logger.info('View server stopped')
  104. def add_blueprint(blueprint : flask.Blueprint) :
  105. __app__.register_blueprint(blueprint)
  106. @privileges.manager.require_authorization(required_role=inventory_view.inventory_read_only_role,ids_getter=get_roles_ids)
  107. def tab():
  108. return jsonify([2,5,7])
  109. __app__.add_url_rule("/tab","/tab",tab)