Prechádzať zdrojové kódy

jwt authentification implemented

ash 2 rokov pred
rodič
commit
0d76981cf9

+ 41 - 14
Backend/Sources/View/view_basics_api.py

@@ -7,6 +7,11 @@ import json
 import View.view_privilege as privileges
 import logging
 from utility.app_logging import logger_name
+import jwt
+import time
+
+
+
 logger = logging.getLogger(logger_name + ".VIEW")
 
 __api_login_url__ = "/api/login"
@@ -14,6 +19,19 @@ __id_counter__ : int = 1
 
 def define_basic_api(app) :
 
+    def generate_auth_token(user_id, expires_in = 600):
+        return jwt.encode({ 'id': user_id, 'exp': time.time() + expires_in },
+                   key="caca", algorithm='HS256')
+
+
+    def verify_auth_token(token):
+
+        data = jwt.decode(token, key="caca", algorithms=['HS256'])
+
+
+        with persistence.get_Session_Instance() as sess :
+            user = sess.query(isp_model.user_account).filter(isp_model.user_account.id == data['id']).first()
+            return user
 
     @app.before_request
     def before_request_func():
@@ -27,20 +45,29 @@ def define_basic_api(app) :
             logger.debug("request json body : " + str(request.json))
 
 
-        if not "client_id" in session :
-            session["client_id"] = str(__id_counter__)
-        logger.debug("client_id is " + session["client_id"])
-        __id_counter__ = __id_counter__ + 1
+        if not request.path == __api_login_url__ :
 
 
-        if not request.path == __api_login_url__ and not "username" in session :
-            logger.warning("Unauthorized client with id " + session["client_id"] + " try to access application")
-            resp = jsonify({'message' : 'Unauthorized access, request is not from and authentificated user.'})
-            resp.status_code = 401
-            return resp
+            auth_header_value = request.headers.get('Authorization', None)
+
+            if not auth_header_value:
+                raise Exception("request does not have a authentification token")
+
+            logger.debug("authorization token : " + auth_header_value)
+
+            user : isp_model.user_account = verify_auth_token(auth_header_value)
+
+
+            logger.debug("user authenficated by token : " + user.nickname + " with id " + str(user.id))
+            session["user_id"] = user.id
+
+
+                #logger.warning("Unauthorized client with ip " + str(request.origin) + " try to access application")
+                #resp = jsonify({'message' : 'Unauthorized access, request is not from and authentificated user.'})
+                #resp.status_code = 401
+                #return resp
+
 
-        if "username" in session :
-            logger.debug("request from  " + session["username"])
 
 
     @app.route(__api_login_url__,methods = ['POST'])
@@ -69,8 +96,8 @@ def define_basic_api(app) :
 
             session["username"] = _username
             session["user_account_id"] = Item.id
-            logger.info("account " + _username + " logged IN successfully with id : " + session["client_id"])
-            resp = jsonify({'message' : 'login successful'})
+            logger.info("account " + _username + " logged IN successfully with origin : " + str(request.origin))
+            resp = jsonify({'message' : 'login successful', "token" : generate_auth_token(Item.id) })
             resp.status_code = 200
             return resp
 
@@ -79,7 +106,7 @@ def define_basic_api(app) :
 
     @app.route('/api/logout',methods = ['DELETE'])
     def logout():
-        logger.info("account " + session["username"] + " logged OUT with id : " + session["client_id"])
+        logger.info("account " + session["username"] + " logged OUT with id : " + session["user_id"])
         session.clear()
         return jsonify('logout')
 

+ 9 - 9
Backend/Sources/View/view_manager.py

@@ -16,7 +16,7 @@ from flask_limiter import Limiter
 from flask_limiter.util import get_remote_address
 import json
 import View.view_basics_api as view_basic_api
-
+import jwt
 
 import logging
 from utility.app_logging import logger_name
@@ -27,8 +27,8 @@ __app__.secret_key = "aseqzdwxc"
 __app__.permanent_session_lifetime = timedelta(minutes=2)
 __app__.logger = logger
 __app__.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
-#flask_cors.CORS(__app__)
-#logging.getLogger('flask_cors').level = logging.DEBUG
+flask_cors.CORS(__app__)
+logging.getLogger('flask_cors').level = logging.DEBUG
 
 limiter = Limiter(__app__,key_func=get_remote_address,default_limits=["100 per minute"])
 limiter.logger = logger
@@ -52,7 +52,7 @@ class ServerThread(threading.Thread):
 __server_process__ : ServerThread
 
 def get_user_privilege() :
-    return privileges.get_privileges_from_user(session["user_account_id"])
+    return privileges.get_privileges_from_user(session["user_id"])
 
 
 def init() :
@@ -68,11 +68,11 @@ def after_request(response : flask.Response):
     # adding this to the header to allow cross origin
     # for exemple origin cross origin is when website with javascript has it's server (origin 1)
     # and the javascript call some request on another server (origin 2), typically our API.
-    header['Access-Control-Allow-Credentials'] =  'true'
-    header['Access-Control-Allow-Origin']  = '*'
-    header['Access-Control-Allow-Methods'] = 'GET,DELETE,UPDATE,HEAD,OPTIONS,POST,PUT,PATCH'
-    header['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
-    header['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
+    #header['Access-Control-Allow-Credentials'] =  'true'
+    #header['Access-Control-Allow-Origin']  = '*'
+    #header['Access-Control-Allow-Methods'] = 'GET,DELETE,UPDATE,HEAD,OPTIONS,POST,PUT,PATCH'
+    #header['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
+    #header['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
 
     logger.debug(response.__dict__)