Update StartSession and begin updating KeepSessionAlive
This commit is contained in:
parent
e17da5b265
commit
901fcd461c
|
@ -5,6 +5,8 @@ Copyright © 2023 Project Peter Yefi peteryefi@gmail.com
|
|||
"""
|
||||
from hub.exports.db_factory import DBFactory as CityExportFactory
|
||||
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 pickle
|
||||
|
||||
|
@ -12,10 +14,25 @@ import pickle
|
|||
class Config:
|
||||
|
||||
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('~')))
|
||||
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('~')))
|
||||
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):
|
||||
city_obj = self.export_db_factory.get_city(city_id)
|
||||
|
|
|
@ -6,7 +6,7 @@ Copyright © 2022 Project Author name guillermo.gutierrezmorote@concordia.ca
|
|||
import uuid
|
||||
import datetime
|
||||
|
||||
sessions = []
|
||||
sessions = {}
|
||||
begin_time = None
|
||||
swagger_data = None
|
||||
city = None
|
||||
|
@ -14,7 +14,6 @@ greenery_catalog = None
|
|||
construction_catalog = None
|
||||
usage_catalog = None
|
||||
|
||||
|
||||
class SessionData:
|
||||
def __init__(self, session):
|
||||
self._session = session
|
||||
|
@ -56,25 +55,25 @@ class SessionData:
|
|||
return usage_catalog
|
||||
|
||||
|
||||
def active_session(session_id):
|
||||
for i in range(len(sessions)):
|
||||
_session = sessions[i]
|
||||
_expire = datetime.datetime.strptime(_session['expire'], '%Y-%m-%d %H:%M:%S.%f')
|
||||
if _session['session_id'] == session_id:
|
||||
if _expire > datetime.datetime.now():
|
||||
return True, i
|
||||
else:
|
||||
# Ensure remove old sessions
|
||||
del sessions[i]
|
||||
return False, -1
|
||||
return False, -1
|
||||
def clear_old_sessions():
|
||||
#loop through all sessions and remove expired sessions
|
||||
if bool(sessions):
|
||||
for session in list(sessions):
|
||||
_expire = datetime.datetime.strptime(sessions[session]['expire'], '%Y-%m-%d %H:%M:%S.%f')
|
||||
|
||||
if _expire < datetime.datetime.now():
|
||||
del sessions[session]
|
||||
|
||||
|
||||
def _valid_session(session_id, ip, token):
|
||||
active, i = active_session(session_id)
|
||||
if active:
|
||||
return sessions[i]['token'] == token and sessions[i]['ip'] == ip, i
|
||||
return False, -1
|
||||
def _validate_session(session_id, token, application_id):
|
||||
print(sessions)
|
||||
print(session_id)
|
||||
print(token)
|
||||
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):
|
||||
|
@ -96,7 +95,19 @@ def refresh_session(request):
|
|||
Validate and extend current session
|
||||
: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')
|
||||
print(session_header)
|
||||
if session_header is None:
|
||||
return None
|
||||
session = eval(session_header)
|
||||
|
@ -115,3 +126,4 @@ def refresh_session(request):
|
|||
return SessionData(sessions[i])
|
||||
else:
|
||||
return None
|
||||
'''
|
||||
|
|
|
@ -8,43 +8,39 @@ import json
|
|||
import uuid
|
||||
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
|
||||
from flask import request, Response
|
||||
from flask_restful import Resource
|
||||
from hub.exports.db_factory import DBFactory
|
||||
from hub_api.config import Config
|
||||
|
||||
|
||||
class SessionStart(Resource):
|
||||
class SessionStart(Resource, Config):
|
||||
def __init__(self):
|
||||
pass
|
||||
super().__init__()
|
||||
|
||||
@staticmethod
|
||||
def put():
|
||||
ip = request.remote_addr
|
||||
session = eval(request.headers.get('Session', None))
|
||||
session_id = session['session_id']
|
||||
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))
|
||||
def put(self):
|
||||
username = request.headers.get('username', None)
|
||||
password = request.headers.get('password', None)
|
||||
application_id = request.headers.get('application_id', None)
|
||||
ip = request.headers.get('ip', None)
|
||||
|
||||
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):
|
||||
def __init__(self):
|
||||
|
@ -59,12 +55,13 @@ class SessionEnd(Resource):
|
|||
class KeepSessionAlive(Resource):
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
#todo : finish implementing KeepSessionAlive and include error handling for missing invalid session_id or
|
||||
# empty sessions
|
||||
@staticmethod
|
||||
def put():
|
||||
session = refresh_session(request)
|
||||
if session is None:
|
||||
return Response(json.dumps({'error': 'unauthorized'}), status=403)
|
||||
headers = session.headers
|
||||
|
||||
response = {'result': 'succeed'}
|
||||
return Response(json.dumps(response), headers=headers)
|
||||
|
|
Loading…
Reference in New Issue
Block a user