Exemple #1
0
def getItem(context, request):

    response = Response(content_type='application/json')

    json_files = [
        '/q1/item.json', '/q2/item.json', '/q3/item.json', '/q4/item.json',
        '/q5/item.json'
    ]

    try:
        # get cookies
        cookieval = request.cookies['signed_cookie']
        cookies = signed_deserialize(cookieval, 'secret')
        count = cookies['c']

        # set next one
        next_count = count + 1
        cookieval = signed_serialize({'c': next_count}, 'secret')
        response.set_cookie('signed_cookie', cookieval)

    except KeyError:
        cookieval = signed_serialize({'c': 0}, 'secret')
        response.set_cookie('signed_cookie', cookieval)
        count = 0

    json_file = item_path + json_files[count]

    with open(json_file, 'r') as myfile:
        json_data = myfile.read()

    response.charset = 'utf8'
    response.text = json_data
    return response
    def _get_cookie(self, cookie_name, secret):
        cookie = self.request.cookies.get(cookie_name)

        try:
            myval = signed_deserialize(cookie, secret)
            return myval
        except (ValueError, AttributeError):
            return None
    def _get_cookie(self, cookie_name, secret):
        cookie = self.request.cookies.get(cookie_name)

        try:
            myval = signed_deserialize(cookie, secret)
            return myval
        except (ValueError, AttributeError):
            return None
def get_secure_cookie(request, key):
    """Gets the value of a secure/signed cookie."""
    signed_value = request.cookies.get(key)

    if signed_value:
        try:
            return signed_deserialize(signed_value, SETTINGS['cookie.secret'])
        except:
            pass
Exemple #5
0
 def test_ctor_with_bad_cookie(self):
     from pyramid.session import signed_deserialize
     request = self._make_request()
     session_id = self._get_session_id(request)
     invalid_secret = 'aaaaaa'
     cookieval = self._serialize(session_id, secret=invalid_secret)
     request.cookies['session'] = cookieval
     session = self._makeOne(request)
     deserialized_cookie = signed_deserialize(cookieval, invalid_secret)
     self.assertNotEqual(deserialized_cookie, session.session_id)
Exemple #6
0
    def _handle_view(self, request):
        if request.path == '/admin/login':
            return True
        fail = HTTPFound(request.route_url('admin.login', url=request.path))
        request_cookie = request.cookies.get('signed')
        if not request_cookie:
            return fail

        cookie = signed_deserialize(request_cookie, SECRET)
        login = cookie.get('time')
        return True if login else fail
Exemple #7
0
def get_session_id(request, cookie_name, secret):
    """
    Gets the session id from the request.
    :param request:
    :param cookie_name:
    :param secret:
    :return:
    """
    session_id = request.cookies.get(cookie_name, None)

    if session_id is not None:
        return signed_deserialize(session_id, secret)
Exemple #8
0
 def logout(self, request):
     request_cookie = request.cookies.get('signed')
     if not request_cookie:
         return {}
     cookie = signed_deserialize(request_cookie, SECRET)
     cookie_csrf = cookie.get('csrf')
     if request.method == 'POST':
         csrf = request.POST.get('csrf')
         if csrf == cookie_csrf:
             response = HTTPFound(request.route_url('admin.index'))
             response.delete_cookie('signed')
             return response
     return dict(csrf=cookie_csrf)
Exemple #9
0
        def __init__(self, request):
            self.request = request
            self.collection = request.registry.settings.get(
                "lumin.session.collection",
                "lumin.sessions")
            self.db = self.request.db
            ## These should be run manually in an entry point or by a
            ## sysadm so they don't get called on a fresh db wiht 10000
            ## sessions
            # self.db[self.collection].ensure_index(
            #     "atime",
            #     expireAfterSeconds=self._timeout
            #     )
            # self.db[self.collection].ensure_index(
            #     "ctime",
            #     expireAfterSeconds=self._cookie_max_age
            #     )
            now = time.time()
            created = accessed = now
            new = True
            value = None
            state = {}  # self._new_session()
            cookieval = request.cookies.get(self._cookie_name)

            if cookieval is not None:
                try:
                    value = signed_deserialize(cookieval, self._secret)

                except ValueError:
                    value = None

            if value is not None:
                accessed, created, oid = value
                new = False
                state = self.db[self.collection].find_one({'_id': oid})
                if state:
                    if now - accessed > self._timeout:
                        ## Belt and braces check for expired cookie,
                        ## but this should occur in a TTL collection in
                        ## which case there **should** be
                        ## no state
                        self.invalidate({'_id': state['_id']})
                        state = self._new_session()
                else:
                    state = self._new_session()

            self.created = created
            self.accessed = accessed
            self.new = new
            dict.__init__(self, state if state else self._new_session())
Exemple #10
0
def getUserName(request):
    result = None
    if('sessionData' in request.cookies):
        encryptedSessionData = request.cookies['sessionData']

        try:
            sessionData = signed_deserialize(encryptedSessionData, COOKIE_SECRET_KEY)
        except ValueError:
            log.error('Seems like the signature has change. Most likely this server was rebooted since the log in.')
            return None

        if('userName' in sessionData):
            result = sessionData['userName']

    return result
def _session_id_from_cookie(request, cookie_name, secret):
    """
    Attempts to retrieve and return a session ID from a session cookie in the
    current request. Returns None if the cookie isn't found or the signed secret
    is bad.
    """
    cookieval = request.cookies.get(cookie_name)

    if cookieval is not None:
        try:
            session_id = signed_deserialize(cookieval, secret)
            return session_id
        except ValueError:
            pass

    return None
Exemple #12
0
def _get_session_id_from_cookie(request, cookie_name, secret):
    """
    Attempts to retrieve and return a session ID from a session cookie in the
    current request. Returns None if the cookie isn't found or the value cannot
    be deserialized for any reason.
    """
    cookieval = request.cookies.get(cookie_name)

    if cookieval is not None:
        try:
            session_id = signed_deserialize(cookieval, secret)
            return session_id
        except ValueError:
            pass

    return None
Exemple #13
0
 def test_cookieval_callback_no_cookie_set(self):
     factory = self._makeOne('secret')
     request = testing.DummyRequest()
     connection = DummyConnection()
     def get_connection(request, dbname):
         self.assertEqual(dbname, None)
         return connection
     def new_session_id():
         return '1'
     factory(request, get_connection=get_connection, 
             new_session_id=new_session_id)
     self.assertEqual(len(request.response_callbacks), 1)
     response = DummyResponse()
     request.response_callbacks[0](request, response)
     self.assertEqual(response.name, 'session_id')
     self.assertEqual(
         signed_deserialize(response.kw['value'], 'secret'), '1')
Exemple #14
0
    def authenticate(self, cookie, csrf_token, session_secret):
        session_id = cookie.replace('session=', '')
        try:
            session_id = signed_deserialize(session_id, session_secret)
        except ValueError:
            raise errors.NotAuthorizedError('Invalid session token')

        session_data = yield from self.redis.get(session_id)
        session = pickle.loads(session_data)['managed_dict']

        if session['_csrft_'] != csrf_token:
            raise errors.NotAuthorizedError('Invalid CSRF token')

        user_id = session.get('user_id')
        if user_id:
            self.user = '******'.format(user_id)
        else:
            self.user = '******'
        self.session = session
Exemple #15
0
        def __init__(self, request):
            self.request = request
            self.collection = request.registry.settings.get(
                "lumin.session.collection",
                "lumin.sessions")
            self.db = self.request.db

            now = time.time()
            created = accessed = now
            new = True
            value = None
            state = self._new_session()
            cookieval = request.cookies.get(self._cookie_name)

            if cookieval is not None:
                try:
                    value = signed_deserialize(cookieval, self._secret)

                except ValueError:
                    value = None

            if value is not None:
                accessed, created, oid = value
                new = False
                state = self.db[self.collection].find_one({'_id': oid})
                if not state:  # pragma: no cover
                    state = self._new_session()
                if now - accessed > self._timeout:
                    if state:
                        self.invalidate({'_id': state['_id']})
                    state = self._new_session()

            self.created = created
            self.accessed = accessed
            self.new = new
            dict.__init__(self, state)
Exemple #16
0
def get_session_from_webdriver(driver: WebDriver, registry: Registry) -> RedisSession:
    """Extract session cookie from a Selenium driver and fetch a matching pyramid_redis_sesssion data.

    Example::

        def test_newsletter_referral(dbsession, web_server, browser, init):
            '''Referral is tracker for the newsletter subscription.'''

            b = browser
            b.visit(web_server + "/newsletter")

            with transaction.manager:
                r = ReferralProgram()
                r.name = "Foobar program"
                dbsession.add(r)
                dbsession.flush()
                ref_id, slug = r.id, r.slug

            # Inject referral data to the active session. We do this because it is very hard to spoof external links pointing to localhost test web server.
            session = get_session_from_webdriver(b.driver, init.config.registry)
            session["referral"] = {
                "ref": slug,
                "referrer": "http://example.com"
            }
            session.to_redis()

            b.fill("email", "*****@*****.**")
            b.find_by_name("subscribe").click()

            # Displayed as a message after succesful form subscription
            assert b.is_text_present("Thank you!")

            # Check we get an entry
            with transaction.manager:
                assert dbsession.query(NewsletterSubscriber).count() == 1
                subscription = dbsession.query(NewsletterSubscriber).first()
                assert subscription.email == "*****@*****.**"
                assert subscription.ip == "127.0.0.1"
                assert subscription.referral_program_id == ref_id
                assert subscription.referrer == "http://example.com"

    :param driver: The active WebDriver (usually ``browser.driver``)

    :param registry: The Pyramid registry (usually ``init.config.registry``)
    """

    # Decode the session our test browser is associated with by reading the raw session cookie value and fetching the session object from Redis
    secret = registry.settings["redis.sessions.secret"]

    session_cookie = driver.get_cookie("session")["value"]
    session_id = signed_deserialize(session_cookie, secret)

    class MockRequest:
        def __init__(self, registry):
            self.registry = registry

    # Use pyramid_redis_session to get a connection to the Redis database
    redis = get_default_connection(MockRequest(registry))

    session = RedisSession(redis, session_id, new=False, new_session=None)

    return session
Exemple #17
0
 def _callFUT(self, serialized, secret, hmac=None):
     if hmac is None:
         import hmac
     from pyramid.session import signed_deserialize
     return signed_deserialize(serialized, secret, hmac=hmac)
Exemple #18
0
def get_session_from_webdriver(driver: WebDriver,
                               registry: Registry) -> RedisSession:
    """Extract session cookie from a Selenium driver and fetch a matching pyramid_redis_sesssion data.

    Example::

        def test_newsletter_referral(dbsession, web_server, browser, init):
            '''Referral is tracker for the newsletter subscription.'''

            b = browser
            b.visit(web_server + "/newsletter")

            with transaction.manager:
                r = ReferralProgram()
                r.name = "Foobar program"
                dbsession.add(r)
                dbsession.flush()
                ref_id, slug = r.id, r.slug

            # Inject referral data to the active session. We do this because it is very hard to spoof external links pointing to localhost test web server.
            session = get_session_from_webdriver(b.driver, init.config.registry)
            session["referral"] = {
                "ref": slug,
                "referrer": "http://example.com"
            }
            session.to_redis()

            b.fill("email", "*****@*****.**")
            b.find_by_name("subscribe").click()

            # Displayed as a message after succesful form subscription
            assert b.is_text_present("Thank you!")

            # Check we get an entry
            with transaction.manager:
                assert dbsession.query(NewsletterSubscriber).count() == 1
                subscription = dbsession.query(NewsletterSubscriber).first()
                assert subscription.email == "*****@*****.**"
                assert subscription.ip == "127.0.0.1"
                assert subscription.referral_program_id == ref_id
                assert subscription.referrer == "http://example.com"

    :param driver: The active WebDriver (usually ``browser.driver``)

    :param registry: The Pyramid registry (usually ``init.config.registry``)
    """

    # Decode the session our test browser is associated with by reading the raw session cookie value and fetching the session object from Redis
    secret = registry.settings["redis.sessions.secret"]

    session_cookie = driver.get_cookie("session")["value"]
    session_id = signed_deserialize(session_cookie, secret)

    class MockRequest:
        def __init__(self, registry):
            self.registry = registry

    # Use pyramid_redis_session to get a connection to the Redis database
    redis = get_default_connection(MockRequest(registry))

    session = RedisSession(redis, session_id, new=False, new_session=None)

    return session
 def _callFUT(self, serialized, secret, hmac=None):
     if hmac is None:
         import hmac
     from pyramid.session import signed_deserialize
     return signed_deserialize(serialized, secret, hmac=hmac)
Exemple #20
0
def validate_username_cookie(cookieval, cookie_token):
    """ Returns the username if it validates. Otherwise throws
    an exception"""

    return signed_deserialize(cookieval, cookie_token)
Exemple #21
0
 def _get_cookie(self, request):
     request_cookie = request.cookies.get('signed')
     if not request_cookie:
         return {}
     return signed_deserialize(request_cookie, SECRET)
Exemple #22
0
def validate_username_cookie(cookieval, cookie_token):
    """ Returns the username if it validates. Otherwise throws
    an exception"""

    return signed_deserialize(cookieval, cookie_token)
Exemple #23
0
    def factory(request, new_session_id=get_unique_session_id):
        # note: will raise ConnectionError if connection is not established
        redis = getattr(request.registry, '_redis_sessions', None)
        if redis is None: # pragma no cover
            redis = Redis(host=host, port=port, db=db, password=password,
                          socket_timeout=socket_timeout,
                          connection_pool=connection_pool, charset=charset,
                          errors=errors, unix_socket_path=unix_socket_path)
            setattr(request.registry, '_redis_sessions', redis)

        cookieval = request.cookies.get(cookie_name)

        session_id = None

        if cookieval is not None:
            try:
                session_id = signed_deserialize(cookieval, secret)
            except ValueError:
                pass

        def add_cookie(session_key):
            if not cookie_on_exception:
                exc = getattr(request, 'exception', None)
                if exc is None: # don't set cookie during exceptions
                    return
            def set_cookie_callback(request, response):
                cookieval = signed_serialize(session_key, secret)
                response.set_cookie(
                    cookie_name,
                    value = cookieval,
                    max_age = cookie_max_age,
                    domain = cookie_domain,
                    secure = cookie_secure,
                    httponly = cookie_httponly,
                    )
            request.add_response_callback(set_cookie_callback)
            return

        def delete_cookie():
            def set_cookie_callback(request, response):
                response.delete_cookie(cookie_name)
            request.add_response_callback(set_cookie_callback)
            return

        if session_id is None:
            session_id = new_session_id(redis, timeout)
            add_cookie(session_id)

        # attempt to find the session by session_id
        session_check = redis.get(session_id)

        # case: found session associated with session_id
        if session_check is not None:
            session = RedisSession(redis, session_id, timeout, delete_cookie)

        # case: session id obtained from cookie is not in Redis; begin anew
        else:
            new_id = new_session_id(redis, timeout)
            add_cookie(new_id)
            session = RedisSession(redis, new_id, timeout, delete_cookie)
            session._v_new = True
        return session