async def load_session(self, request):
        await self._create_expire_index()
        cookie = self.load_cookie(request)

        if cookie is None:
            return Session(None, data=None, new=True, max_age=self.max_age)

        key = str(cookie)
        data_row = await self._collection.find_one(
            filter={
                '_id': self.__get_store_key(key),
                '$or': [{
                    'expire': None
                }, {
                    'expire': {
                        '$gt': datetime.utcnow()
                    }
                }]
            })

        if data_row is None:
            return Session(None, data=None, new=True, max_age=self.max_age)

        try:
            data = self._decoder(data_row['data'])
        except ValueError:
            data = None
        return Session(key, data=data, new=False, max_age=self.max_age)
Пример #2
0
def test_change() -> None:
    created = int(time.time())
    s = Session('test_identity',
                new=False,
                data={
                    'session': {
                        'a': {
                            'key': 'value'
                        }
                    },
                    'created': created
                })
    assert not s._changed

    s['a']['key2'] = 'val2'
    assert not s._changed
    assert cast(MutableMapping[str, Any],
                {'a': {
                    'key': 'value',
                    'key2': 'val2'
                }}) == s

    assert s.created == created

    s.changed()
    assert s._changed
    assert cast(MutableMapping[str, Any],
                {'a': {
                    'key': 'value',
                    'key2': 'val2'
                }}) == s
    assert s.created == created
Пример #3
0
    async def load_session(self, request):
        """Retrieve the WebSession data for a request."""
        cookie = self.load_cookie(request)
        if cookie is None:
            print("No cookie saved for this request, just create one.")
            return Session(None, data=None, new=True, max_age=self.max_age)
        else:
            token = cookie.encode()
            try:
                key = FERNET.decrypt(token)
            except InvalidToken:
                print("This is not a valid token", token)
                return Session(None, data=None, new=True, max_age=self.max_age)

            key = key.decode()
            try:
                uuid = UUID(key)
            except ValueError:
                session = None
            else:
                session = WebSession.get(uuid=uuid)

            if session is None:
                return Session(None, data=None, new=True, max_age=self.max_age)

            data = session.data
            print(f"Data for this session: {data}")
            return Session(key, data=data, new=False, max_age=self.max_age)
Пример #4
0
    def test_operations(self):
        s = Session('test_identity')
        self.assertEqual(s, {})
        self.assertEqual(len(s), 0)
        self.assertEqual(list(s), [])
        self.assertNotIn('foo', s)
        self.assertNotIn('key', s)

        s = Session('test_identity', data={'session': {'foo': 'bar'}})
        self.assertEqual(len(s), 1)
        self.assertEqual(s, {'foo': 'bar'})
        self.assertEqual(list(s), ['foo'])
        self.assertIn('foo', s)
        self.assertNotIn('key', s)

        s['key'] = 'value'
        self.assertEqual(len(s), 2)
        self.assertEqual(s, {'foo': 'bar', 'key': 'value'})
        self.assertEqual(sorted(s), ['foo', 'key'])
        self.assertIn('foo', s)
        self.assertIn('key', s)

        del s['key']
        self.assertEqual(len(s), 1)
        self.assertEqual(s, {'foo': 'bar'})
        self.assertEqual(list(s), ['foo'])
        self.assertIn('foo', s)
        self.assertNotIn('key', s)

        s.pop('foo')
        self.assertEqual(len(s), 0)
        self.assertEqual(s, {})
        self.assertEqual(list(s), [])
        self.assertNotIn('foo', s)
        self.assertNotIn('key', s)
    async def load_session(self, request):
        await self._create_table_if_not_exists()
        cookie = self.load_cookie(request)
        if cookie is None:
            return Session(None, data=None, new=True, max_age=self.max_age)
        else:
            key = str(cookie)
            stored_key = (self.cookie_name + '_' + key)
            data_row = await self._client.get_item(
                TableName=self._table_name, Key={'key': {
                    'S': stored_key
                }})

            if data_row is None or 'Item' not in data_row:
                return Session(None, data=None, new=True, max_age=self.max_age)

            data_row_item = data_row['Item']

            if 'expiration_time' in data_row_item and \
               int(data_row_item['expiration_time']['S']) < time.time():
                return Session(None, data=None, new=True, max_age=self.max_age)

            try:
                data = {
                    'session':
                    self._decoder(data_row_item['session_data']['S'])
                }
            except ValueError:
                data = None
            return Session(key, data=data, new=False, max_age=self.max_age)
Пример #6
0
def test_set_new_identity_ok() -> None:
    s = Session(identity=1, data=None, new=True)
    assert s.new
    assert s.identity == 1

    s.set_new_identity(2)
    assert s.new
    assert s.identity == 2
Пример #7
0
def test_invalidate2() -> None:
    s = Session('test_identity', data={'session': {'foo': 'bar'}}, new=False)
    assert s == cast(MutableMapping[str, Any], {'foo': 'bar'})
    assert not s._changed

    s.invalidate()
    assert s == cast(MutableMapping[str, Any], {})
    assert s._changed
    assert s.created is not None
Пример #8
0
def test_invalidate2():
    s = Session('test_identity', data={'session': {'foo': 'bar'}}, new=False)
    assert s == {'foo': 'bar'}
    assert not s._changed

    s.invalidate()
    assert s == {}
    assert s._changed
    assert s.created is not None
Пример #9
0
    def test_invalidate2(self):
        s = Session('test_identity', data={'session': {'foo': 'bar'}})
        self.assertEqual(s, {'foo': 'bar'})
        self.assertFalse(s._changed)

        s.invalidate()
        self.assertEqual(s, {})
        self.assertTrue(s._changed)
        self.assertIsNotNone(s.created)
Пример #10
0
    def test_invalidate2(self):
        s = Session('test_identity', data={'session': {'foo': 'bar'}})
        self.assertEqual(s, {'foo': 'bar'})
        self.assertFalse(s._changed)

        s.invalidate()
        self.assertEqual(s, {})
        self.assertTrue(s._changed)
        self.assertIsNotNone(s.created)
Пример #11
0
def test_invalidate2():
    s = Session('test_identity', data={'session': {'foo': 'bar'}},
                new=False)
    assert s == {'foo': 'bar'}
    assert not s._changed

    s.invalidate()
    assert s == {}
    assert s._changed
    assert s.created is not None
Пример #12
0
def test__repr__2() -> None:
    created = int(time.time()) - 1000
    session_data = {'session': {'key': 123}, 'created': created}
    s = Session('test_identity', data=session_data, new=False)
    assert str(s) == \
        "<Session [new:False, changed:False, created:{0}]" \
        " {{'key': 123}}>".format(created)
    s.invalidate()
    assert str(s) == \
        "<Session [new:False, changed:True, created:{0}] {{}}>".format(
            created)
Пример #13
0
    def _del_user_session(self, session: aiohttp_session.Session):
        """Delete user session.

        Args:
            session (aiohttp_session.Session): session.
        """
        if SESSION_KEY in session and session[SESSION_KEY] in self._sessions:
            _LOGGER.debug(f"Deleting user session: {session[SESSION_KEY]}")

            self._sessions.pop(session[SESSION_KEY])
            session.pop(SESSION_KEY)
Пример #14
0
 def test__repr__2(self):
     created = int(time.time()) - 1000
     session_data = {'session': {'key': 123}, 'created': created}
     s = Session('test_identity', data=session_data, new=False)
     self.assertEqual(
         str(s), "<Session [new:False, changed:False, created:{0}]"
         " {{'key': 123}}>".format(created))
     s.invalidate()
     self.assertEqual(
         str(s),
         "<Session [new:False, changed:True, created:{0}] {{}}>".format(
             created))
Пример #15
0
 async def main_handler(self, request: web.Request, session: Session):
     available_rooms = {
         room
         for room in GameRoom.instances.values()
         if room.manager.unregistered_players
     }
     if user := session.get('user'):
         joined_rooms = {
             room
             for room in GameRoom.instances.values()
             if user in room.manager.users_players
         }
Пример #16
0
 async def load_session(self, request):
     token = self.load_token(request)
     if token is None:
         return Session(None, data=None, new=True, max_age=self.max_age)
     else:
         try:
             data = self._decoder(
                 self._fernet.decrypt(
                     token.encode('utf-8')).decode('utf-8'))
             return Session(None, data=data,
                            new=False, max_age=self.max_age)
         except InvalidToken:
             return Session(None, data=None, new=True, max_age=self.max_age)
Пример #17
0
def test_create2() -> None:
    s = Session('test_identity', data={'session': {'some': 'data'}}, new=False)
    assert s == cast(MutableMapping[str, Any], {'some': 'data'})
    assert not s.new
    assert 'test_identity' == s.identity
    assert not s._changed
    assert s.created is not None
Пример #18
0
 def test_create3(self):
     s = Session(identity=1, new=True)
     self.assertEqual(s, {})
     self.assertTrue(s.new)
     self.assertEqual(s.identity, 1)
     self.assertFalse(s._changed)
     self.assertIsNotNone(s.created)
Пример #19
0
 def test_create2(self):
     s = Session('test_identity', data={'session': {'some': 'data'}})
     self.assertEqual(s, {'some': 'data'})
     self.assertFalse(s.new)
     self.assertEqual('test_identity', s.identity)
     self.assertFalse(s._changed)
     self.assertIsNotNone(s.created)
Пример #20
0
def test__repr__2():
    created = int(time.time()) - 1000
    session_data = {
        'session': {
            'key': 123
        },
        'created': created
    }
    s = Session('test_identity', data=session_data, new=False)
    assert str(s) == \
        "<Session [new:False, changed:False, created:{0}]" \
        " {{'key': 123}}>".format(created)
    s.invalidate()
    assert str(s) == \
        "<Session [new:False, changed:True, created:{0}] {{}}>".format(
            created)
Пример #21
0
def test_create2():
    s = Session('test_identity', data={'session': {'some': 'data'}}, new=False)
    assert s == {'some': 'data'}
    assert not s.new
    assert 'test_identity' == s.identity
    assert not s._changed
    assert s.created is not None
Пример #22
0
def test_create3():
    s = Session(identity=1, data=None, new=True)
    assert s == {}
    assert s.new
    assert s.identity == 1
    assert not s._changed
    assert s.created is not None
Пример #23
0
def test_create():
    s = Session('test_identity', data=None, new=True)
    assert s == {}
    assert s.new
    assert 'test_identity' == s.identity
    assert not s._changed
    assert s.created is not None
Пример #24
0
 async def load_session(self, request):
     cookie = self.load_cookie(request)
     if cookie is None:
         return Session(None, data=None, new=True, max_age=self.max_age)
     else:
         async with self.db as conn:
             key = str(cookie)
             stmt = await conn.prepare("SELECT data FROM sessions WHERE id = $1 AND expires_at > $2")
             data = await stmt.fetchval(key, datetime.utcnow())
             if data is None:
                 return Session(None, data=None, new=True, max_age=self.max_age)
             try:
                 data = self._decoder(data)
             except ValueError:
                 data = None
             return Session(key, data=data, new=False, max_age=self.max_age)
Пример #25
0
def test_create() -> None:
    s = Session('test_identity', data=None, new=True)
    assert s == cast(MutableMapping[str, Any], {})
    assert s.new
    assert 'test_identity' == s.identity
    assert not s._changed
    assert s.created is not None
Пример #26
0
def test_create3() -> None:
    s = Session(identity=1, data=None, new=True)
    assert s == cast(MutableMapping[str, Any], {})
    assert s.new
    assert s.identity == 1
    assert not s._changed
    assert s.created is not None
Пример #27
0
        def go():
            req = self.make_request('GET', '/')
            session = Session('identity')
            req[SESSION_KEY] = session

            ret = yield from get_session(req)
            self.assertIs(session, ret)
Пример #28
0
 def test_create(self):
     s = Session('test_identity', data=None, new=True)
     self.assertEqual(s, {})
     self.assertTrue(s.new)
     self.assertEqual('test_identity', s.identity)
     self.assertFalse(s._changed)
     self.assertIsNotNone(s.created)
Пример #29
0
async def test_get_stored_session() -> None:
    req = make_mocked_request('GET', '/')
    session = Session('identity', data=None, new=False)
    req[SESSION_KEY] = session

    ret = await get_session(req)
    assert session is ret
Пример #30
0
    async def load_session(self, request):
        cookie = self.load_cookie(request)
        if cookie is None:
            return Session(None, data=None, new=True, max_age=self.max_age)
        else:
            key = str(cookie)
            stored_key = (self.cookie_name + '_' + key).encode('utf-8')
            data_row = await self._db.doc(stored_key)
            if not data_row.exists():
                return Session(None, data=None, new=True, max_age=self.max_age)

            try:
                data = self._decoder(data_row['data'])
            except ValueError:
                data = None
            return Session(key, data=data, new=False, max_age=self.max_age)
Пример #31
0
async def test_get_new_session_no_storage() -> None:
    req = make_mocked_request('GET', '/')
    session = Session('identity', data=None, new=False)
    req[SESSION_KEY] = session

    with pytest.raises(RuntimeError):
        await new_session(req)
Пример #32
0
def mock_request_session():
    request = make_mocked_request("GET", "/")
    session = Session("identity", data=None, new=False)
    session["token"] = "124"
    session["username"] = "******"
    request[SESSION_KEY] = session

    return request
Пример #33
0
 async def load_session(self, request):
     session = await super(EncryptedCookieStorageWithMaxAgeExpiration,
                           self).load_session(request)
     if (self.max_age and session.new is False
             and session.created + self.max_age < int(time.time())):
         log.warning('Cookie expired, ' 'create a new fresh session')
         return Session(None, data=None, new=True, max_age=self.max_age)
     return session
Пример #34
0
    async def load_session(self, request: Request):
        cookie = self.load_cookie(request)

        if not cookie:
            return Session(None, data=None, new=True, max_age=self.max_age)

        async with self._db.acquire() as connection:
            stmt = await connection.prepare(get_sess_query)

            data = await stmt.fetchrow(str(cookie))

            if not data:
                return Session(None, data=None, new=True, max_age=self.max_age)

            data = await self._encoder.decode(data['data'])

            return Session(None, data=data, new=False, max_age=self.max_age)
Пример #35
0
def test_change():
    created = int(time.time())
    s = Session('test_identity', new=False, data={
        'session': {
            'a': {'key': 'value'}
        },
        'created': created
    })
    assert not s._changed

    s['a']['key2'] = 'val2'
    assert not s._changed
    assert {'a': {'key': 'value',
                  'key2': 'val2'}} == s

    assert s.created == created

    s.changed()
    assert s._changed
    assert {'a': {'key': 'value',
                  'key2': 'val2'}} == s
    assert s.created == created
Пример #36
0
    def test_change(self):
        created = int(time.time())
        s = Session('test_identity', new=False, data={
            'session': {
                'a': {'key': 'value'}
            },
            'created': created
        })
        self.assertFalse(s._changed)

        s['a']['key2'] = 'val2'
        self.assertFalse(s._changed)
        self.assertEqual({'a': {'key': 'value',
                                'key2': 'val2'}},
                         s)
        self.assertEqual(s.created, created)

        s.changed()
        self.assertTrue(s._changed)
        self.assertEqual({'a': {'key': 'value',
                                'key2': 'val2'}},
                         s)
        self.assertEqual(s.created, created)
Пример #37
0
def test_operations():
    s = Session('test_identity', data=None, new=False)
    assert s == {}
    assert len(s) == 0
    assert list(s) == []
    assert 'foo' not in s
    assert 'key' not in s

    s = Session('test_identity', data={'session': {'foo': 'bar'}},
                new=False)
    assert len(s) == 1
    assert s == {'foo': 'bar'}
    assert list(s) == ['foo']
    assert 'foo' in s
    assert 'key' not in s

    s['key'] = 'value'
    assert len(s) == 2
    assert s == {'foo': 'bar', 'key': 'value'}
    assert sorted(s) == ['foo', 'key']
    assert 'foo' in s
    assert 'key' in s

    del s['key']
    assert len(s) == 1
    assert s == {'foo': 'bar'}
    assert list(s) == ['foo']
    assert 'foo' in s
    assert 'key' not in s

    s.pop('foo')
    assert len(s) == 0
    assert s == {}
    assert list(s) == []
    assert 'foo' not in s
    assert 'key' not in s
Пример #38
0
def get_id(session: Session) -> (str, None):
    """Return client ID if it exists; else None."""
    return session.get(CLIENT_ID_KEY)
Пример #39
0
def get_or_assign_id(session: Session) -> str:
    """Return client's ID, and if it doesn't exist, assign it and return."""
    client_id = session.setdefault(CLIENT_ID_KEY, get_random_id())
    return client_id