Update StartSession and begin updating KeepSessionAlive

This commit is contained in:
KoaCWells 2023-02-20 22:10:09 -05:00
parent e17da5b265
commit 901fcd461c
3 changed files with 79 additions and 53 deletions

View File

@ -5,6 +5,8 @@ Copyright © 2023 Project Peter Yefi peteryefi@gmail.com
""" """
from hub.exports.db_factory import DBFactory as CityExportFactory from hub.exports.db_factory import DBFactory as CityExportFactory
from hub.imports.db_factory import DBFactory from hub.imports.db_factory import DBFactory
from hub.imports.user_factory import UserFactory
from hub.exports.user_factory import UserFactory as ExUserFactory
import os import os
import pickle import pickle
@ -12,10 +14,25 @@ import pickle
class Config: class Config:
def __init__(self): def __init__(self):
self.export_db_factory = CityExportFactory(db_name='hub_prod', app_env='PROD', db_name = None
app_env = None
if os.getenv("FLASK_DEBUG") == 'production':
db_name = 'hub_prod'
app_env = 'PROD'
elif os.getenv("FLASK_DEBUG") == 'testing':
db_name = 'persistence_test'
app_env = 'TEST'
db_name = 'persistence_test'
app_env = 'TEST'
self.export_db_factory = CityExportFactory(db_name=db_name, app_env=app_env,
dotenv_path="{}/.env".format(os.path.expanduser('~'))) dotenv_path="{}/.env".format(os.path.expanduser('~')))
self.import_db_factory = DBFactory(db_name='hub_prod', app_env='PROD', self.import_db_factory = DBFactory(db_name=db_name, app_env=app_env,
dotenv_path="{}/.env".format(os.path.expanduser('~'))) dotenv_path="{}/.env".format(os.path.expanduser('~')))
self.user_factory = UserFactory(db_name=db_name, app_env=app_env,
dotenv_path="{}/.env".format(os.path.expanduser('~')))
self.ex_user_factory = ExUserFactory(db_name=db_name, app_env=app_env,
dotenv_path="{}/.env".format(os.path.expanduser('~')))
def get_city(self, city_id): def get_city(self, city_id):
city_obj = self.export_db_factory.get_city(city_id) city_obj = self.export_db_factory.get_city(city_id)

View File

@ -6,7 +6,7 @@ Copyright © 2022 Project Author name guillermo.gutierrezmorote@concordia.ca
import uuid import uuid
import datetime import datetime
sessions = [] sessions = {}
begin_time = None begin_time = None
swagger_data = None swagger_data = None
city = None city = None
@ -14,7 +14,6 @@ greenery_catalog = None
construction_catalog = None construction_catalog = None
usage_catalog = None usage_catalog = None
class SessionData: class SessionData:
def __init__(self, session): def __init__(self, session):
self._session = session self._session = session
@ -56,25 +55,25 @@ class SessionData:
return usage_catalog return usage_catalog
def active_session(session_id): def clear_old_sessions():
for i in range(len(sessions)): #loop through all sessions and remove expired sessions
_session = sessions[i] if bool(sessions):
_expire = datetime.datetime.strptime(_session['expire'], '%Y-%m-%d %H:%M:%S.%f') for session in list(sessions):
if _session['session_id'] == session_id: _expire = datetime.datetime.strptime(sessions[session]['expire'], '%Y-%m-%d %H:%M:%S.%f')
if _expire > datetime.datetime.now():
return True, i if _expire < datetime.datetime.now():
else: del sessions[session]
# Ensure remove old sessions
del sessions[i]
return False, -1
return False, -1
def _valid_session(session_id, ip, token): def _validate_session(session_id, token, application_id):
active, i = active_session(session_id) print(sessions)
if active: print(session_id)
return sessions[i]['token'] == token and sessions[i]['ip'] == ip, i print(token)
return False, -1 print(application_id)
if bool(sessions[session_id]) and sessions[session_id]['token'] == token and \
sessions[session_id]['application_id'] == application_id:
return True
return False
def remove_session(request): def remove_session(request):
@ -96,7 +95,19 @@ def refresh_session(request):
Validate and extend current session Validate and extend current session
:return: valid, token, city :return: valid, token, city
""" """
session_id = request.headers.get('session_id', None)
token = request.headers.get('token', None)
application_id = request.headers.get('application_id', None)
if _validate_session(session_id, token, application_id):
sessions[session_id]['expire'] = str(datetime.datetime.now() + datetime.timedelta(minutes=5))
sessions[session_id]['token'] = uuid.uuid4()
return sessions[session_id]
return None
'''
session_header = request.headers.get('session') session_header = request.headers.get('session')
print(session_header)
if session_header is None: if session_header is None:
return None return None
session = eval(session_header) session = eval(session_header)
@ -115,3 +126,4 @@ def refresh_session(request):
return SessionData(sessions[i]) return SessionData(sessions[i])
else: else:
return None return None
'''

View File

@ -8,43 +8,39 @@ import json
import uuid import uuid
import datetime import datetime
from hub_api.helpers.session_helper import remove_session, active_session, sessions, refresh_session from hub_api.helpers.session_helper import remove_session, clear_old_sessions, sessions, refresh_session
import hub_api.helpers.session_helper as sh import hub_api.helpers.session_helper as sh
from flask import request, Response from flask import request, Response
from flask_restful import Resource from flask_restful import Resource
from hub.exports.db_factory import DBFactory
from hub_api.config import Config
class SessionStart(Resource, Config):
class SessionStart(Resource):
def __init__(self): def __init__(self):
pass super().__init__()
@staticmethod def put(self):
def put(): username = request.headers.get('username', None)
ip = request.remote_addr password = request.headers.get('password', None)
session = eval(request.headers.get('Session', None)) application_id = request.headers.get('application_id', None)
session_id = session['session_id'] ip = request.headers.get('ip', None)
active, i = active_session(session_id)
if active:
return Response(json.dumps({'error': 'invalid session'}), status=401)
if session_id == 'debug':
token = 'debug'
else:
token = str(uuid.uuid4())
expire = str(datetime.datetime.now() + datetime.timedelta(minutes=5))
session = {'session_id': session_id,
'token': token,
'expire': expire,
'ip': ip,
'city': sh.city.copy,
'greenery_catalog': sh.greenery_catalog,
'construction_catalog': sh.construction_catalog,
'usage_catalog': sh.usage_catalog,
'greenery_percentage': 0
}
response = {'session_id': session_id, 'token': token}
sessions.append(session)
return Response(json.dumps(response))
if(self.export_db_factory.user_info(name=username, password=password, application_id=application_id)):
session_id = str(uuid.uuid4())
session = {
'username': username,
'token': str(uuid.uuid4()),
'expire': str(datetime.datetime.now() + datetime.timedelta(minutes=5)),
'application_id': application_id,
'ip': ip
#'city': sh.city.copy,
}
sessions[session_id] = session
clear_old_sessions()
print(sessions)
return Response(json.dumps({'session_id': session_id, 'session': session}), status=200)
return Response(json.dumps({'message': 'invalid credentials'}), status=401)
class SessionEnd(Resource): class SessionEnd(Resource):
def __init__(self): def __init__(self):
@ -59,12 +55,13 @@ class SessionEnd(Resource):
class KeepSessionAlive(Resource): class KeepSessionAlive(Resource):
def __init__(self): def __init__(self):
pass pass
#todo : finish implementing KeepSessionAlive and include error handling for missing invalid session_id or
# empty sessions
@staticmethod @staticmethod
def put(): def put():
session = refresh_session(request) session = refresh_session(request)
if session is None: if session is None:
return Response(json.dumps({'error': 'unauthorized'}), status=403) return Response(json.dumps({'error': 'unauthorized'}), status=403)
headers = session.headers
response = {'result': 'succeed'} response = {'result': 'succeed'}
return Response(json.dumps(response), headers=headers) return Response(json.dumps(response), headers=headers)