import random import threading csprng = random.SystemRandom() sessions_lock = threading.Lock() max_sessions = 1024 sessions = {} def new_session(userid): """Creates a new session and returns its ID""" with sessions_lock: while True: sessionid = csprng.randrange(2 << 256) # Check that the ID is unique if sessionid not in sessions: break # Do we have too many sessions? # TODO: Implement the limit per-user if len(sessions) >= max_sessions: # Yes, drop a random one # TODO: Have some LRU thing here delete_id = random.choice(list(sessions.keys())) del sessions[delete_id] sessions[sessionid] = userid return sessionid def get_userid(sessionid): """Returns the user associated with session ID Returns None if no user was found""" with sessions_lock: if sessionid in sessions: return sessions[sessionid] return None