""" 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, active_session, sessions, refresh_session import hub_api.helpers.session_helper as sh from flask import request, Response from flask_restful import Resource class SessionStart(Resource): def __init__(self): pass @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)) 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': 'invalid session'}), status=401) class KeepSessionAlive(Resource): def __init__(self): pass @staticmethod def put(): session = refresh_session(request) if session is None: return Response(json.dumps({'error': 'invalid session'}), status=401) headers = session.headers response = {'result': 'succeed'} return Response(json.dumps(response), headers=headers)