<commit_before># -*- coding: utf-8 -*-

## This file is part of Invenio.
## Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## Invenio is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""
Session management adapted from mod_python Session class.

Just use L{get_session} to obtain a session object (with a dictionary
interface, which will let you store permanent information).
"""

from invenio.webinterface_handler_wsgi_utils import add_cookies, Cookie, get_cookie

import cPickle
import time
import random
import re
import sys
import os
if sys.hexversion < 0x2060000:
    from md5 import md5
else:
    from hashlib import md5

from invenio.dateutils import convert_datestruct_to_datetext
from invenio.dbquery import run_sql, blob_to_string
from invenio.config import CFG_WEBSESSION_EXPIRY_LIMIT_REMEMBER, \
    CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT, CFG_SITE_URL, CFG_SITE_SECURE_URL
from invenio.websession_config import CFG_WEBSESSION_COOKIE_NAME, \
    CFG_WEBSESSION_ONE_DAY, CFG_WEBSESSION_CLEANUP_CHANCE, \
    CFG_WEBSESSION_ENABLE_LOCKING

CFG_FULL_HTTPS = CFG_SITE_URL.lower().startswith("https://")

def get_session(req, sid=None):
    """
    Obtain a session.

    If the session has already been created for the current request,
    returns the already existing session.

    @param req: the mod_python request object.
    @type req: mod_python request object
    @param sid: the session identifier of an already existing session.
    @type sid: 32 hexadecimal string
    @return: the session.
    @rtype: InvenioSession
    @raise ValueError: if C{sid} is provided and it doesn't correspond to a
        valid session.
    """
    if sid is not None:
        req._session = InvenioSession(req, sid)
        return req._session
    if not hasattr(req, '_session'):
        req._session = InvenioSession(req, sid)
    return req._session

class InvenioSession(dict):
    """
    This class implements a Session handling based on MySQL.

    @param req: the mod_python request object.
    @type req: mod_python request object
    @param sid: the session identifier if already known
    @type sid: 32 hexadecimal string
    @ivar _remember_me: if the session cookie should last one day or until
        the browser is closed.
    @type _remember_me: bool

    @note: The code is heavily based on ModPython 3.3.1 DBMSession
        implementation.
    @note: This class implements IP verification to prevent basic cookie
        stealing.
    @raise ValueError: if C{sid} is provided and correspond to a broken
        session.
    """

    def __init__(self, req, sid=None):
        self._remember_me = False
        self._req, self._sid, self._secret = req, sid, None
        self._lock = CFG_WEBSESSION_ENABLE_LOCKING
        self._new = 1
        self._created = 0
        self._accessed = 0
        self._timeout = 0
        self._locked = 0
        self._invalid = 0
        self._http_ip = None
        self._https_ip = None
        self.__need_https = False

        dict.__init__(self)

        if not self._sid:
            # check to see if cookie exists
            cookie = get_cookie(req, CFG_WEBSESSION_COOKIE_NAME)
            if cookie:
                self._sid = cookie.value
            else:
                stub_cookie = get_cookie(req, CFG_WEBSESSION_COOKIE_NAME + 'stub')
                self.__need_https = stub_cookie and stub_cookie.value == 'HTTPS'

        if self._sid:
            if not _check_sid(self._sid):
                if sid:
                    # Supplied explicitly by user of the class,
                    # raise an exception and make the user code
                    # deal with it.
                    raise ValueError("Invalid Session ID: sid=%s" % sid)
                else:
                    # Derived from the cookie sent by browser,
                    # wipe it out so it gets replaced with a
                    # correct value.
                    self._sid = None

        if self._sid:
            # attempt to load ourselves
            self.lock()
            if self.load():
                self._new = 0

        if self._new:
            # make a new session
            if self._sid:
                self.unlock() # unlock old sid
            self._sid = _new_sid(self._req)
            self.lock()                 # lock new sid
            remote_ip = self._req.remote_ip
            if self._req.is_https():
                self._https_ip = remote_ip
            else:
                self._http_ip = remote_ip
            self._created = time.time()
            self._timeout = CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT * \
                CFG_WEBSESSION_ONE_DAY
            add_cookies(self._req, self.make_cookies())

        self._accessed = time.time()

        # need cleanup?
        if random.randint(1, CFG_WEBSESSION_CLEANUP_CHANCE) == 1:
            self.cleanup()

    def set_remember_me(self, remember_me=True):
        """
        Set/Unset the L{_remember_me} flag.

        @param remember_me: True if the session cookie should last one day or
            until the browser is closed.
        @type remember_me: bool
        """
        self._remember_me = remember_me
        if remember_me:
            self.set_timeout(CFG_WEBSESSION_EXPIRY_LIMIT_REMEMBER *
                CFG_WEBSESSION_ONE_DAY)
        else:
            self.set_timeout(CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT *
                CFG_WEBSESSION_ONE_DAY)
        add_cookies(self._req, self.make_cookies())

    def load(self):<commit_msg>WebSession: hot fix for session handling<commit_after># -*- coding: utf-8 -*-

## This file is part of Invenio.
## Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## Invenio is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""
Session management adapted from mod_python Session class.

Just use L{get_session} to obtain a session object (with a dictionary
interface, which will let you store permanent information).
"""

from invenio.webinterface_handler_wsgi_utils import add_cookies, Cookie, get_cookie

import cPickle
import time
import random
import re
import sys
import os
if sys.hexversion < 0x2060000:
    from md5 import md5
else:
    from hashlib import md5

from invenio.dateutils import convert_datestruct_to_datetext
from invenio.dbquery import run_sql, blob_to_string
from invenio.config import CFG_WEBSESSION_EXPIRY_LIMIT_REMEMBER, \
    CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT, CFG_SITE_URL, CFG_SITE_SECURE_URL
from invenio.websession_config import CFG_WEBSESSION_COOKIE_NAME, \
    CFG_WEBSESSION_ONE_DAY, CFG_WEBSESSION_CLEANUP_CHANCE, \
    CFG_WEBSESSION_ENABLE_LOCKING

CFG_FULL_HTTPS = CFG_SITE_URL.lower().startswith("https://")

def get_session(req, sid=None):
    """
    Obtain a session.

    If the session has already been created for the current request,
    returns the already existing session.

    @param req: the mod_python request object.
    @type req: mod_python request object
    @param sid: the session identifier of an already existing session.
    @type sid: 32 hexadecimal string
    @return: the session.
    @rtype: InvenioSession
    @raise ValueError: if C{sid} is provided and it doesn't correspond to a
        valid session.
    """
    if sid is not None:
        req._session = InvenioSession(req, sid)
        return req._session
    if not hasattr(req, '_session'):
        req._session = InvenioSession(req, sid)
    return req._session

class InvenioSession(dict):
    """
    This class implements a Session handling based on MySQL.

    @param req: the mod_python request object.
    @type req: mod_python request object
    @param sid: the session identifier if already known
    @type sid: 32 hexadecimal string
    @ivar _remember_me: if the session cookie should last one day or until
        the browser is closed.
    @type _remember_me: bool

    @note: The code is heavily based on ModPython 3.3.1 DBMSession
        implementation.
    @note: This class implements IP verification to prevent basic cookie
        stealing.
    @raise ValueError: if C{sid} is provided and correspond to a broken
        session.
    """

    def __init__(self, req, sid=None):
        self._remember_me = False
        self._req, self._sid, self._secret = req, sid, None
        self._lock = CFG_WEBSESSION_ENABLE_LOCKING
        self._new = 1
        self._created = 0
        self._accessed = 0
        self._timeout = 0
        self._locked = 0
        self._invalid = 0
        self._http_ip = None
        self._https_ip = None
        self.__need_https = False

        dict.__init__(self)

        if not self._sid:
            # check to see if cookie exists
            cookie = get_cookie(req, CFG_WEBSESSION_COOKIE_NAME)
            if cookie:
                self._sid = cookie.value
            else:
                stub_cookie = get_cookie(req, CFG_WEBSESSION_COOKIE_NAME + 'stub')
                self.__need_https = stub_cookie and stub_cookie.value == 'HTTPS'

        if self._sid:
            if not _check_sid(self._sid):
                if sid:
                    # Supplied explicitly by user of the class,
                    # raise an exception and make the user code
                    # deal with it.
                    raise ValueError("Invalid Session ID: sid=%s" % sid)
                else:
                    # Derived from the cookie sent by browser,
                    # wipe it out so it gets replaced with a
                    # correct value.
                    self._sid = None

        if self._sid:
            # attempt to load ourselves
            self.lock()
            if self.load():
                self._new = 0

        if self._new:
            # make a new session
            if self._sid:
                self.unlock() # unlock old sid
            self._sid = _new_sid(self._req)
            self.lock()                 # lock new sid
            remote_ip = self._req.remote_ip
            if self._req.is_https():
                self._https_ip = remote_ip
            else:
                self._http_ip = remote_ip
            self._created = time.time()
            self._timeout = CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT * \
                CFG_WEBSESSION_ONE_DAY

        self._accessed = time.time()

        # need cleanup?
        if random.randint(1, CFG_WEBSESSION_CLEANUP_CHANCE) == 1:
            self.cleanup()

    def set_remember_me(self, remember_me=True):
        """
        Set/Unset the L{_remember_me} flag.

        @param remember_me: True if the session cookie should last one day or
            until the browser is closed.
        @type remember_me: bool
        """
        self._remember_me = remember_me
        if remember_me:
            self.set_timeout(CFG_WEBSESSION_EXPIRY_LIMIT_REMEMBER *
                CFG_WEBSESSION_ONE_DAY)
        else:
            self.set_timeout(CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT *
                CFG_WEBSESSION_ONE_DAY)
        add_cookies(self._req, self.make_cookies())

    def load(self):
{'fraction_non_alphanumeric': 0.06885619055361353, 'fraction_numerical': 0.013169661003170473, 'mean_word_length': 2.3007781057150525, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3896157', 'n_tokens_mistral': 3692, 'n_tokens_neox': 3455, 'n_words': 1185}