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
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
def getOAuthToken(): secretKey = current_app.config['SECRET_KEY'].encode('utf-8') cookie = request.cookies.get('zapfauth_token') if not cookie: return None data = SecureCookie.unserialize(cookie, secretKey) return (data["token"], data["secret"])
def oauth_callback(self, request): if request.args.get("denied") is not None: return False try: oauth_data = SecureCookie.unserialize(request.cookies["twitter_oauth"], self.consumer_secret) except KeyError: return False oauth_token = oauth2.Token(oauth_data["oauth_token"], oauth_data["oauth_token_secret"]) oauth_token.set_verifier(request.args.get("oauth_verifier")) oauth_consumer = oauth2.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth2.Client(oauth_consumer, oauth_token) resp, content = oauth_client.request(ACCESS_TOKEN_URL, "POST") if resp["status"] != "200": return False oauth_data = dict(parse_qsl(content)) user_data = twitter.Api(consumer_key=self.consumer_key, consumer_secret=self.consumer_secret, access_token_key=oauth_data["oauth_token"], access_token_secret=oauth_data["oauth_token_secret"]).VerifyCredentials().AsDict() return (user_data["id"], dict(user_data, **oauth_data))
def login(): #import logging #logging.info('sgvsevr') form = LoginForm() if request.method == 'POST': if form.validate_on_submit(): user = User.query.filter_by(account=form.name.data).first() if user is not None and user.verify_password(form.password.data): resp = make_response(redirect(url_for('account.index', account=user.account))) cookie_value = SecureCookie({'user': form.name.data, 'rn': user.username, 'uid': user.id, 'permission': user.permission, 'timestamp': time.time()}, SECRET_KEY).serialize() # x = SecureCookie.unserialize(value, SECRET_KEY) resp.set_cookie('info', cookie_value, expires=time.time() + COOKIE_EXPIRES) # expires=COOKIE_EXPIRES return resp flash('1-Invalid username or password.') return render_template('login.html', form=form) flash('用户名或密码错误') return render_template('login.html', form=form) else: cookie_info = request.cookies.get('info') if cookie_info: info = SecureCookie.unserialize(cookie_info, SECRET_KEY) user, timesite = info.get('user'), info.get('timestamp') _user = User.query.filter_by(account=user).first() if _user: if (time.time() - timesite) < COOKIE_EXPIRES: return redirect(url_for('account.index', account=user)) return render_template('login.html', form=form) return render_template('login.html', form=form)
def get(self): args = self.request.args response_type = args.get("response_type") client_id = args.get("client_id") redirect_uri = args.get("redirect_uri") scope = args.get("scope") state = args.get("state","") if response_type is None or client_id is None or redirect_uri is None: return self.error("The request invalid") data = self.request.cookies.get("l") if data is not None: login_data = SecureCookie.unserialize(data, self.settings.secret_key) else: self.settings.log.debug("cookie for user login data not found") login_data = {} if not login_data.has_key("username"): # not logged in, show login form self.settings.log.debug("redirecting to login form") return self.login_form() else: # logged in, retrieve an auth code and do the redirect username = login_data['username'] am = self.settings.authmanager try: token, auth_code = am.new_token(username, client_id) except usermanager.errors.ClientNotFound, e: return self.error("the client_id is incorrect") q = { 'code' : auth_code, 'state' : state, } url = redirect_uri+"?"+urllib.urlencode(q) return werkzeug.redirect(url)
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
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)
def is_authorized(self, request, op_request): data = request.cookies.get('session_data') if data: session = SecureCookie.unserialize(data, SECRET_KEY) if session.get("logged_in", False) == True: return True return False
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)
def oauth_callback(self, request): try: callback_url = SecureCookie.unserialize(request.cookies["facebook_oauth"], self.client_secret)["callback_url"] except KeyError: return False access_token = facebook.get_access_token_from_code(request.args.get("code"), callback_url, self.client_id, self.client_secret)["access_token"] user = facebook.GraphAPI(access_token).get_object("me") return (int(user["id"]), dict(user, access_token=access_token))
def _get_flash_msg(request): if 'ls_message' in request.cookies: update_message = SecureCookie.unserialize( request.cookies['ls_message'], settings.SECRET_KEY, ) delete_cookie('ls_message') return update_message['m'] else: return None
def get(self, **kw): """post a new vote to this poll""" _id = self.item._id data = self.request.cookies.get("qlpoll") if data is not None: poll_data = SecureCookie.unserialize(data, self.settings.secret_key) else: poll_data = {'_id' : None} voted = poll_data['_id']==_id return {'voted' : voted}
def oauth_callback(self, request): try: callback_url = SecureCookie.unserialize(request.cookies["foursquare_oauth"], self.client_secret)["callback_url"] except KeyError: return False client = foursquare.Foursquare(client_id=self.client_id, client_secret=self.client_secret, redirect_uri=callback_url) access_token = client.oauth.get_token(request.args.get("code")) client.set_access_token(access_token) user = client.users() return (int(user["user"]["id"]), dict(user, access_token=access_token))
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, {})
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 == {}
def get_gaema_user(service): try: gaema_user_key = GAEMA_USER_KEY_FORMAT % service if hasattr(settings, "GAEMA_STORAGE") and \ settings.GAEMA_STORAGE == "cookie": user_data = local.request.cookies.get(gaema_user_key, None) if user_data: return SecureCookie.unserialize(user_data, secret_key=settings.SECRET_KEY) else: return local.request.session.get(gaema_user_key, None) except Exception, e: raise InternalServerError('Getting gaema_user failed, reason: %s' % e)
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())
def test_basic_support(self): c = SecureCookie(secret_key="foo") assert c.new print c.modified, c.should_save 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 == {}
def get(self): """return the user related data""" userdata = self.request.cookies.get("u", None) userdata = SecureCookie.unserialize(userdata, self.settings.secret_key) cm = self.settings.contentmanager d = { 'userdata' : userdata, 'poco' : userdata['poco'], 'token' : userdata['token'], 'root' : cm.root.json, 'types' : cm.content_types.json, 'scraper' : 'http://pagescraper.mrtopf.clprojects.net' } return d
def get(self): client_id = self.request.args.get('client_id') data = self.request.cookies.get("l") if data is not None: login_data = SecureCookie.unserialize(data, self.settings.secret_key) else: login_data = {} if not login_data.has_key("username"): return self.error("user_not_logged_in", "The user is not logged in or the cookie is gone") # logged in, retrieve an auth code and do the redirect username = login_data['username'] am = self.settings.authmanager try: token, auth_code = am.new_token(username, client_id) except usermanager.errors.ClientNotFound, e: return self.error("unauthorized_client", "The client id is unknown")
def decorator(*args, **kwargs): cookie_info = request.cookies.get('info') if cookie_info: info = SecureCookie.unserialize(cookie_info, SECRET_KEY) user, uid, timesite = info.get('user'), \ info.get('uid'), info.get('timestamp') permission, rn = info.get('permission'), info.get('rn') request.uid, request.user, request.permission = uid,\ user, permission request.rn = rn if (time.time() - timesite) >= COOKIE_EXPIRES: flash('deco-1会话已过期,请重新登录') return redirect(url_for('account.login')) else: flash('deco-2会话已过期,请重新登录') return redirect(url_for('account.login')) return func(*args, **kwargs)
def load_cookie(request): datas = request.cookies.get(COOKIE_SESSION_ID) if not datas: return None cookie_content = SecureCookie.unserialize(datas, COOKIE_SECRET_KEY) if 'token' not in cookie_content: return None token = cookie_content['token'] if token is None or len(token) == 0: return None return token
def index(account): form = LoginForm() # return 'sdbvgsdf' info = request.cookies.get('info') if info: cookie_value = SecureCookie.unserialize(info, SECRET_KEY) if account == cookie_value.get('user'): today = datetime.datetime.now() year = today.isocalendar()[0] week_total = today.isocalendar()[1] uid = cookie_value.get('uid') permission, rn = cookie_value.get('permission'), cookie_value.get('rn') return render_template('index.html', year=year, week_total=week_total, uid=uid, account=account, permission=permission, rn=rn) else: render_template('login.html', form=form) return render_template('login.html', form=form)
def pre_process(self, environ): request = Request(environ) for prefix in self.excluded_paths: if request.path.startswith(prefix): return cookie = request.cookies.get(self.name) if not cookie: return session = SecureCookie.unserialize(cookie, self.secret) if not self.fetch_user: user = User() user._session_token = session['session_token'] user.id = session['uid'] User.set_current(user) else: user = User.become(session['session_token']) User.set_current(user)
def secure_decode(astring, secretkey): return SecureCookie.unserialize(astring, secretkey)
def session(self): data = self.cookies.get(COOKIE_NAME) if not data: return SecureCookie(secret_key=SECRET_KEY) return SecureCookie.unserialize(data, SECRET_KEY)
def session(self): data = self.cookies.get(login_cookie) if not data: return SecureCookie(secret_key=cookie_key) return SecureCookie.unserialize(data, cookie_key)
def prepare(): print '========================================' print 'BEGIN prepare(%s) [%s]' % (request.endpoint, str(datetime.now())) if request.endpoint in UNSUPPORTED_ENDPOINTS: abort(403) data = request.cookies.get('auth', None) if request.endpoint not in (None, 'static'): print '<<< %s >>>' % request.endpoint print '<< request.values:: %r >>' % request.values print '<< cookie_data:: %r >>' % str(SecureCookie.unserialize(data, app.secret_key) if data is not None else 'None') print '--------------------' # For guest user if request.endpoint == 'init': if not data: vid = save_visitor(request.environ) g.uid = str(vid) g.is_login = False else: cookie = SecureCookie.unserialize(data, app.secret_key) g.uid = cookie.get('uid', None) if g.uid is None: vid = save_visitor(request.environ) g.uid = str(vid) g.is_login = False else: g.is_login = True elif request.endpoint in LOGIN_REQUIRED_ENDPOINTS: if data: # Get uid & ticket from cookie then new Client cookie = SecureCookie.unserialize(data, app.secret_key) print '[...].cookie: ', cookie g.cookie = cookie g.uid = cookie.get('uid', None) g.is_login = True g.is_guest = cookie.get('is_guest', None) show = cookie.get('show', 'available') record, nick, pic_url = None, None, None if g.is_guest: record = db.load_visitor(g.uid) nick = '%s(%s)' % (record['nick'], record['location']) pic_url = gravatar_default(g.uid) else: record = db.load_user(g.uid) nick = record['nick'] pic_url = gravatar_url(record['email']) g.record = record print 'g.record:', g.record user = { 'id' : g.uid, 'nick': nick, 'show': show, 'status' : '', 'pic_url': pic_url, 'default_pic_url': gravatar_default(g.uid) } ticket = request.values.get('ticket', None) g.client = Client(user, CONFIG['domain'], CONFIG['apikey'], ticket=ticket, host=CONFIG['host'], port=CONFIG['port']) else: print '403.request.endpoint:', request.endpoint abort(403) print 'END prepare(%s) [%s]' % (request.endpoint, str(datetime.now()))
def unserialize(cls, string, secret_key, sid=None): u"""werkzeug.contrib.securecookie.SecureCookie.unserialize""" items = SecureCookie.unserialize(string, secret_key).items() return cls(items, sid=sid, secret_key=secret_key, new=False)
def get_session(self): from solace import settings for cookie in self.client.cookie_jar: if cookie.name == settings.COOKIE_NAME: value = unquote_header_value(cookie.value) return SecureCookie.unserialize(value, settings.SECRET_KEY)
def unserialize_secure_cookie(request): if not request.cookies.get('admin'): return dict() return SecureCookie.unserialize( request.cookies.get('admin'), secret_key=config.secure_key)
def __init__(self, secret, data): """Create a new SecureCookieSession """ self.cookie = SecureCookie.unserialize(data, secret) if data else SecureCookie(secret_key = secret)
def __init__(self, secret, data): """Create a new SecureCookieSession """ self.cookie = SecureCookie.unserialize( data, secret) if data else SecureCookie(secret_key=secret)
def unserialize_cookie(cookie): return SecureCookie.unserialize(cookie, secret_key)
def client_session(self): data = self.cookies.get(COOKIENAME) if not data: return SecureCookie(secret_key=application.secret_key) return SecureCookie.unserialize(data, application.secret_key)
def client_session(self): data = self.cookies.get("session_data") if not data: return SecureCookie(secret_key=SECURE_COOKIE_SECRET) return SecureCookie.unserialize(data, SECURE_COOKIE_SECRET)
def prepare(): print '========================================' print 'BEGIN prepare(%s) [%s]' % (request.endpoint, str(datetime.now())) if request.endpoint in UNSUPPORTED_ENDPOINTS: abort(403) data = request.cookies.get('auth', None) if request.endpoint not in (None, 'static'): print '<<< %s >>>' % request.endpoint print '<< request.values:: %r >>' % request.values print '<< cookie_data:: %r >>' % str( SecureCookie.unserialize(data, app.secret_key ) if data is not None else 'None') print '--------------------' # For guest user if request.endpoint == 'init': if not data: vid = save_visitor(request.environ) g.uid = str(vid) g.is_login = False else: cookie = SecureCookie.unserialize(data, app.secret_key) g.uid = cookie.get('uid', None) if g.uid is None: vid = save_visitor(request.environ) g.uid = str(vid) g.is_login = False else: g.is_login = True elif request.endpoint in LOGIN_REQUIRED_ENDPOINTS: if data: # Get uid & ticket from cookie then new Client cookie = SecureCookie.unserialize(data, app.secret_key) print '[...].cookie: ', cookie g.cookie = cookie g.uid = cookie.get('uid', None) g.is_login = True g.is_guest = cookie.get('is_guest', None) show = cookie.get('show', 'available') record, nick, pic_url = None, None, None if g.is_guest: record = db.load_visitor(g.uid) nick = '%s(%s)' % (record['nick'], record['location']) pic_url = gravatar_default(g.uid) else: record = db.load_user(g.uid) nick = record['nick'] pic_url = gravatar_url(record['email']) g.record = record print 'g.record:', g.record user = { 'id': g.uid, 'nick': nick, 'show': show, 'status': '', 'pic_url': pic_url, 'default_pic_url': gravatar_default(g.uid) } ticket = request.values.get('ticket', None) g.client = Client(user, CONFIG['domain'], CONFIG['apikey'], ticket=ticket, host=CONFIG['host'], port=CONFIG['port']) else: print '403.request.endpoint:', request.endpoint abort(403) print 'END prepare(%s) [%s]' % (request.endpoint, str(datetime.now()))