Fix weakref for user session.

This commit is contained in:
sfigato 2019-09-05 19:50:33 +02:00
parent 0434d7ba58
commit 49fd5c3f8b
Signed by: blallo
GPG Key ID: 0CBE577C9B72DC3F

View File

@ -24,7 +24,8 @@ alog = logging.getLogger("api")
routes = web.RouteTableDef()
OPERATORS = weakref.WeakKeyDictionary(
{}
) # type: weakref.WeakKeyDictionary[T.Text, AsyncOperator]
) # type: weakref.WeakKeyDictionary[UserSession, AsyncOperator]
USERS = {} # type: T.Dict[T.Text, UserSession]
BASE_PATH = pkg_resources.resource_filename(__name__, "assets")
EXECUTOR = ProcessPoolExecutor()
# WARN: the default il 12 rounds; both the server and the client shall compute
@ -34,6 +35,15 @@ EXECUTOR = ProcessPoolExecutor()
ROUNDS = 6
class UserSession(object):
"""
Placeholder object to manipulate session life.
"""
def __init__(self, user):
self._user = user
def _reckon_token_response(base_uri: T.Text) -> T.Text:
return bcrypt.using(rounds=ROUNDS, truncate_error=True).hash(base_uri)
@ -56,7 +66,8 @@ async def get_set_operator(
session = await get_session(request)
op = None
if "async_operator" in session:
op = OPERATORS.get(session["async_operator"])
user_session = USERS.get(session["async_operator"])
op = OPERATORS.get(user_session)
else:
session = await new_session(request)
@ -65,8 +76,9 @@ async def get_set_operator(
debug = request.app["debug"]
headless = request.app["headless"]
op = AsyncOperator(base_uri, name=user, headless=headless, debug=debug)
USERS[user] = UserSession(user)
session["async_operator"] = user
OPERATORS[user] = op
OPERATORS[USERS[user]] = op
return op, session
@ -135,8 +147,8 @@ async def login_handler(request: web.Request) -> web.Response:
async def logout_handler(request: web.Request) -> web.Response:
alog.debug("logout")
session = await get_session(request)
op_key = session.get("async_operator")
op = OPERATORS.get(op_key)
user_session = USERS.get(session["async_operator"], UserSession("NOONE"))
op = OPERATORS.get(user_session)
if not op:
return web.json_response(
{"error": "No session", "logged_in": False}, status=401
@ -145,7 +157,7 @@ async def logout_handler(request: web.Request) -> web.Response:
session.invalidate()
alog.debug("logout result: %s", res)
# FIX: assess if better to invalidate session and dump the browser instance.
del OPERATORS[op_key]
del user_session
return web.json_response({"logged_in": res}, status=200)
@ -181,7 +193,8 @@ async def checkout_handler(request: web.Request) -> web.Response:
async def movements_handle(request: web.Request) -> web.Response:
alog.debug("movements")
session = await get_session(request)
op = OPERATORS.get(session.get("async_operator"))
user_session = USERS.get(session.get("async_operator"), UserSession("NOONE"))
op = OPERATORS.get(user_session)
if not op:
alog.debug("Missing session")
return web.json_response(