view_basics_api.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. import Model.isp_model as isp_model
  2. from flask import session,request,jsonify
  3. import Model.model_manager as model_manager
  4. from werkzeug.security import check_password_hash,generate_password_hash
  5. import persistence
  6. import json
  7. import View.view_privilege as privileges
  8. import logging
  9. from utility.app_logging import logger_name
  10. import jwt
  11. import time
  12. logger = logging.getLogger(logger_name + ".VIEW")
  13. __api_login_url__ = "/api/login"
  14. __id_counter__ : int = 1
  15. def define_basic_api(app) :
  16. def generate_auth_token(user_id, expires_in = 600):
  17. return jwt.encode({ 'id': user_id, 'exp': time.time() + expires_in },
  18. key="caca", algorithm='HS256')
  19. def verify_auth_token(token):
  20. data = jwt.decode(token, key="caca", algorithms=['HS256'])
  21. with persistence.get_Session_Instance() as sess :
  22. user = sess.query(isp_model.user_account).filter(isp_model.user_account.id == data['id']).first()
  23. return user
  24. @app.before_request
  25. def before_request_func():
  26. global __id_counter__
  27. logger.debug("before_request processing")
  28. logger.debug("request from " + request.remote_addr)
  29. logger.debug("request header" + str(request.headers.__dict__))
  30. if request.json :
  31. logger.debug("request json body : " + str(request.json))
  32. if not request.path == __api_login_url__ :
  33. auth_header_value = request.headers.get('x-Auth-Token', None)
  34. if not auth_header_value:
  35. raise Exception("request does not have a authentification token")
  36. logger.debug("authorization token : " + auth_header_value)
  37. user : isp_model.user_account = verify_auth_token(auth_header_value)
  38. logger.debug("user authenficated by token : " + user.nickname + " with id " + str(user.id))
  39. session["user_id"] = user.id
  40. #logger.warning("Unauthorized client with ip " + str(request.origin) + " try to access application")
  41. #resp = jsonify({'message' : 'Unauthorized access, request is not from and authentificated user.'})
  42. #resp.status_code = 401
  43. #return resp
  44. @app.route(__api_login_url__,methods = ['POST'])
  45. def login():
  46. _json = request.json
  47. _username = _json['username']
  48. _password = _json['password']
  49. with persistence.get_Session_Instance() as sess :
  50. Item = sess.query(isp_model.user_account).filter(isp_model.user_account.nickname == _username).first()
  51. if not isinstance(Item,isp_model.user_account) :
  52. logger.warning("user tried to login with unknown account name : " + _username)
  53. resp = jsonify({'message' : 'Bad Request - user account not found'})
  54. resp.status_code = 400
  55. return resp
  56. if not check_password_hash(Item.password,_password) :
  57. logger.warning("user with account name '" + _username + "' tried to login with invalid password")
  58. resp = jsonify({'message' : 'Bad Request - invalid password for this account'})
  59. resp.status_code = 400
  60. return resp
  61. session["username"] = _username
  62. session["user_account_id"] = Item.id
  63. logger.info("account " + _username + " logged IN successfully with origin : " + str(request.origin))
  64. resp = jsonify({'message' : 'login successful', "token" : generate_auth_token(Item.id) })
  65. resp.status_code = 200
  66. return resp
  67. @app.route('/api/logout',methods = ['DELETE'])
  68. def logout():
  69. logger.info("account " + session["username"] + " logged OUT with id : " + session["user_id"])
  70. session.clear()
  71. return jsonify('logout')
  72. @app.route('/api/me',methods = ['GET'])
  73. def user_description():
  74. with persistence.get_Session_Instance() as sess :
  75. item : isp_model.user_account = sess.query(isp_model.user_account).filter(isp_model.user_account.id == session["client_id"]).first()
  76. json_string = model_manager.ModelObjectToJsonString(item)
  77. json_dict : dict = json.loads(json_string)
  78. json_dict.pop("password") # removing the password item for security
  79. json_string = json.dumps(json_dict)
  80. return jsonify(json_dict)
  81. @app.route('/api/password',methods = ['POST'])
  82. def change_password():
  83. _json = request.json
  84. _old_password = _json['old_password']
  85. _password = _json['new_password']
  86. with persistence.get_Session_Instance() as sess :
  87. Item : isp_model.user_account = sess.query(isp_model.user_account).filter(isp_model.user_account.id == session["user_account_id"]).first()
  88. if not check_password_hash(Item.password,_password) :
  89. raise Exception("old password is incorrect")
  90. Item.password = generate_password_hash(_password)
  91. sess.commit()
  92. return jsonify('password changed')
  93. @app.route('/routes',methods = ['GET'])
  94. def routes():
  95. routes = []
  96. for route in app.url_map.iter_rules():
  97. routes.append('%s' % route)
  98. return jsonify(routes)