api_v1.4/hub_api/control/session.py

89 lines
2.9 KiB
Python

"""
Session
SPDX - License - Identifier: LGPL - 3.0 - or -later
Copyright © 2022 Project Author name guillermo.gutierrezmorote@concordia.ca
"""
import datetime
import json
import uuid
from sqlalchemy.exc import SQLAlchemyError
from flask import request, Response
from flask_restful import Resource
from hub_api.config import Config
from hub_api.helpers.session_helper import remove_session, sessions, refresh_session
class SessionStart(Resource, Config):
def __init__(self):
super().__init__()
def put(self):
username = request.headers.get('username', None)
password = request.headers.get('password', None)
try:
application_uuid = uuid.UUID(request.headers.get('application-uuid', None))
user_info = self.database.user_login(name=username, password=password, application_uuid=application_uuid)
except (ValueError, SQLAlchemyError, TypeError):
return Response(json.dumps({'error': 'unauthorized'}), status=403)
ip = request.remote_addr
if user_info:
session_id = str(uuid.uuid4())
token = str(uuid.uuid4())
session = {
'user_id': user_info.id,
'user': username,
'token': token,
'expire': str(datetime.datetime.now() + datetime.timedelta(minutes=5)),
'application_id': user_info.application_id,
'application_uuid': application_uuid,
'ip': ip,
'scenarios': []
}
cities = self.database.cities_by_user_and_application(user_info.id, user_info.application_id)
for city in cities:
if city.scenario not in session['scenarios']:
session['scenarios'].append(city.scenario)
sessions[session_id] = session
response = Response(json.dumps({'scenarios': session['scenarios'], 'result': 'OK'}), status=200)
response.headers['session_id'] = session_id
response.headers['token'] = token
return response
return Response(json.dumps({'error': 'unauthorized'}), status=403)
class SessionEnd(Resource):
def __init__(self):
pass
@staticmethod
def put():
session_id = request.headers.get('session-id', None)
token = request.headers.get('token', None)
application_uuid = request.headers.get('application-uuid', None)
if remove_session(session_id, token, application_uuid):
return Response(json.dumps({'result': 'succeed'}), status=200)
return Response(json.dumps({'error': 'unauthorized'}), status=403)
class KeepSessionAlive(Resource):
def __init__(self):
pass
@staticmethod
def put():
session_id = request.headers.get('session-id', None)
token = request.headers.get('token', None)
application_uuid = request.headers.get('application-uuid', None)
_session = refresh_session(session_id, token, application_uuid)
if _session is None:
return Response(json.dumps({'error': 'unauthorized'}), status=403)
response = Response(json.dumps({'result': 'succeed'}), status=200)
response.headers['token'] = _session['token']
return response