api_v1.4/hub_api/session.py

68 lines
2.1 KiB
Python

"""
Session
SPDX - License - Identifier: LGPL - 3.0 - or -later
Copyright © 2022 Project Author name guillermo.gutierrezmorote@concordia.ca
"""
import json
import uuid
import datetime
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, Config):
def __init__(self):
super().__init__()
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):
pass
@staticmethod
def put():
if remove_session(request):
return Response(json.dumps({'result': 'succeed'}))
return Response(json.dumps({'error': 'unauthorized'}), status=403)
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)
response = {'result': 'succeed'}
return Response(json.dumps(response), headers=headers)