Esempio n. 1
0
def new_session(db, username):
    """
    Generate new session and a cookie to the request.
    User must exist in the database, otherwise return None.
    There should only be one active session per user at any point,
    if there is already a session active, use the existing
    session id from the cookie
    """
    # Check for valid user
    cursor = db.cursor()
    query = "SELECT username FROM users WHERE username = ?"
    cursor.execute(query, (username,))
    user = cursor.fetchone()
    if not user:
        return None
    # Check for existing session from user, otherwise generate new session
    query = "SELECT sessionid FROM sessions WHERE username = ?"
    cursor.execute(query, (username,))
    session = cursor.fetchone()
    if session:
        session_id = session[0]
    else:
        session_id = str(uuid.uuid4())
        query = "INSERT INTO sessions (sessionid, username) VALUES (?, ?)"
        cursor.execute(query, (session_id, user[0]))
        db.commit()
    response.set_cookie(COOKIE, session_id)
    return session_id
Esempio n. 2
0
def delete_session(db, username):
    """
    Remove all sessions for a user
    """
    cursor = db.cursor()
    query = "DELETE FROM sessions WHERE username = ?"
    cursor.execute(query, (username,))
    db.commit()
    session_id = request.get_cookie(COOKIE)
    response.set_cookie(COOKIE, session_id, expires=0)