def get(self, room_id): room = Room(room_id) if not room.exists(): self.redirect('/') self.render("views/room.html", video_key=room.get_video_id(), user_email=create_signed_value(APPLICATION['cookie_secret'], 'user_email', self.current_user.email), user_token=create_signed_value(APPLICATION['cookie_secret'], 'user_token', self.current_user.token))
def Merge(client, target_user_id, source_user_id, base_url, no_prompt=False): # Get source and target user objects. source_user = yield gen.Task(User.Query, client, source_user_id, None) target_user = yield gen.Task(User.Query, client, target_user_id, None) print '--------- MERGE ACCOUNTS ----------' print ' Source User (will be terminated): %s (user %d)' % (source_user.email, source_user_id) print ' Target User (gets the assets) : %s (user %d)' % (target_user.email, target_user_id) print '' if not no_prompt: answer = raw_input('Are you SURE you want to do this? Type \'yes\' to confirm: ') if answer.lower() != 'yes': return # Construct cookies for source and target users. cookie_secret = GetSecret('cookie_secret') source_cookie = create_signed_value(cookie_secret, 'user', json.dumps(dict(user_id=source_user_id, device_id=source_user.webapp_dev_id, server_version=SERVER_VERSION, confirm_time=time.time()))) target_cookie = create_signed_value(cookie_secret, 'user', json.dumps(dict(user_id=target_user_id, device_id=target_user.webapp_dev_id, server_version=SERVER_VERSION))) timestamp = time.time() http_headers = { 'Cookie': '_xsrf=fake_xsrf; user=%s' % target_cookie, 'X-XSRFToken': 'fake_xsrf', 'Content-Type': 'application/json', } # Allocate unique asset ids for the operation. http_client = AsyncHTTPClient() body = {'headers': {'version': MAX_SUPPORTED_MESSAGE_VERSION}, 'asset_types': ['o', 'a']} response = yield gen.Task(http_client.fetch, '%s/service/allocate_ids' % base_url, method='POST', body=json.dumps(body), headers=http_headers, validate_cert=options.validate_cert) operation_id, activity_id = json.loads(response.body)['asset_ids'] body = {'headers': {'version': MAX_SUPPORTED_MESSAGE_VERSION, 'op_id': operation_id, 'op_timestamp': timestamp, 'synchronous': True}, 'activity': {'activity_id': activity_id, 'timestamp': timestamp}, 'source_user_cookie': source_cookie} yield gen.Task(http_client.fetch, '%s/service/merge_accounts' % base_url, method='POST', body=json.dumps(body), headers=http_headers, validate_cert=options.validate_cert)
def get(self, room_id): room = Room(room_id) if not room.exists(): self.redirect('/') self.render( "views/room.html", video_key=room.get_video_id(), user_email=create_signed_value(APPLICATION['cookie_secret'], 'user_email', self.current_user.email), user_token=create_signed_value(APPLICATION['cookie_secret'], 'user_token', self.current_user.token))
def main(): parse_command_line() io_loop = IOLoop.instance() assert options.user_id, '--user_id must be set' assert options.device_id, '--device_id must be set' assert options.method, '--method must be set' assert not options.base_url.endswith('/'), 'base_url should be scheme://host:port only, no path' InitSecrets(callback=io_loop.stop) io_loop.start() cookie_secret = GetSecret('cookie_secret') # TODO(ben): move this (and the server_version constant) somewhere sharable that doesn't need # to pull in the entire server-side codebase. Or add an auth flow like fetch_logs so we don't # need production secrets at all. cookie = create_signed_value(cookie_secret, 'user', json.dumps(dict(user_id=options.user_id, device_id=options.device_id, server_version='1.1'))) url = '%s/service/%s' % (options.base_url, options.method) http_headers = { 'Cookie': '_xsrf=fake_xsrf; user=%s' % cookie, 'X-XSRFToken': 'fake_xsrf', 'Content-Type': 'application/json', } body = json.loads(options.body) body.setdefault('headers', {}).setdefault('version', MAX_SUPPORTED_MESSAGE_VERSION) # TODO: support op headers too response = HTTPClient().fetch(url, method='POST', body=json.dumps(body), headers=http_headers, validate_cert=options.validate_cert) print json.dumps(json.loads(response.body), indent=2)
def _get_secure_cookie(self, cookie_name, cookie_value): cookie_name, cookie_value = 'auth', '1' secure_cookie = create_signed_value( self.app.settings["cookie_secret"], cookie_name, cookie_value) return 'auth="' + str(secure_cookie)[2:-1] + '"'
def test_headers(self): # Headers are passed through, but cookie overrides it result = self.fetch(self.src, params={ 'url': '/httpbin', 'cookie': 'right=1' }, headers={ 'dnt': '1', 'user-agent': 'gramex-test', 'cookie': 'wrong=1' }) text = get_text(result.content) ok_(re.search(r'"dnt":\s+"1"', text, re.IGNORECASE)) ok_(re.search(r'"user\-agent":\s+"gramex-test"', text, re.IGNORECASE)) # ?cookie= should override header. Result must be right=1, not wrong=1 ok_('wrong' not in text) ok_('right' in text) # Check that the request can mimic a user user = {'id': '*****@*****.**', 'role': 'manager'} secret = gramex.service.app.settings['cookie_secret'] result = self.fetch(self.src, params={'url': '/auth/session'}, headers={ 'x-gramex-user': create_signed_value(secret, 'user', json.dumps(user)), }) text = get_text(result.content) ok_(user['id'] in text) ok_(user['role'] in text)
def post(self, *args, **kwargs): rsp = { 'stat': 'err', 'info': '', } self.get_paras_dict() username = self.qdict.get('username', '') # 用户名 passwd = self.qdict.get('passwd', '') # 密码 if not username or not passwd: rsp['info'] = '账号和密码不能为空' return self.write(ujson.dumps(rsp)) user_service = UserServices(self.db) status, user = user_service.check_user_login_pwd(username, passwd) if status: cookies = user_service.user_format_app(user) login_token = create_signed_value( self.application.settings["cookie_secret"], 'loginuser', ujson.dumps(cookies)) rsp['stat'] = 'ok' rsp['data'] = { 'login_token': login_token, 'nick_name': user.Fnick_name, 'photo_url': user.Fphoto_url } return self.write(ujson.dumps(rsp)) else: rsp['info'] = user return self.write(ujson.dumps(rsp))
def cookie_header(username): cookie_name, cookie_value = 'user', {'login': username} secure_cookie = create_signed_value( cls.settings.COOKIE_SECRET, cookie_name, json_encode(cookie_value)) return {'Cookie': '='.join((cookie_name, secure_cookie.decode()))}
def _authenticate_request(self): app = self.get_app() secure_cookie = create_signed_value(app.settings['cookie_secret'], 'test', 'user').decode('utf-8') headers = { 'Cookie':'='.join(secure_cookie) } return headers
def __init__(self, cookie_name, cookie_value, cookie_secret): # need to update this so it takes values like domain, expires, etc # for people who test more deeply. self._cookie = Cookie.SimpleCookie() self._cookie_name = cookie_name self._cookie[cookie_name] = create_signed_value( cookie_secret, cookie_name, cookie_value)
def test_override(self): self.login_ok('alpha', 'alpha', check_next='/dir/index/') eq_({'user': '******', 'id': 'alpha'}, self.get_session()['user']) result = {'user': '******', 'role': 'admin'} secret = gramex.service.app.settings['cookie_secret'] cipher = create_signed_value(secret, 'user', json.dumps(result)) session_data = self.get_session(headers={'X-Gramex-User': cipher}) eq_(result, session_data['user'])
def test_with_cookie(self): username = '******' cookie_name, cookie_value = 'user', username secure_cookie = ensure_str( create_signed_value(self.get_app().settings["cookie_secret"], cookie_name, cookie_value)) headers = {'Cookie': '='.join((cookie_name, secure_cookie))} response = self.fetch('/', method='GET', headers=headers) self.assertEqual(200, response.code)
def test_types(self): cookie_value = to_unicode(create_signed_value(self.COOKIE_SECRET, "asdf", "qwer")) response = self.fetch("/typecheck/asdf?foo=bar", headers={"Cookie": "asdf=" + cookie_value}) data = json_decode(response.body) self.assertEqual(data, {}) response = self.fetch( "/typecheck/asdf?foo=bar", method="POST", headers={"Cookie": "asdf=" + cookie_value}, body="foo=bar" )
def get_cookie(): cookie_secret = 'asdfasdf' auth = 'auth' auth_value = '7a7c4182f1bef7504a1d3d5eaa51a242' username = '******' username_value = 'threathunter_test' userid = 'user_id' userid_value = '2' secure_auth = create_signed_value(cookie_secret, auth, auth_value) secure_username = create_signed_value( cookie_secret, username, username_value) secure_userid = create_signed_value( cookie_secret, userid, userid_value) cookie = Cookie.SimpleCookie() cookie[auth] = secure_auth cookie[userid] = secure_userid cookie[username] = secure_username return cookie
def start_server(self, port, address, *, xsrf_protection=XSRF_PROTECTION_TOKEN): file_download_feature = FileDownloadFeature( UserFileStorage(b'some_secret'), test_utils.temp_folder) config = ServerConfig() config.port = port config.address = address config.xsrf_protection = xsrf_protection config.max_request_size_mb = 1 authorizer = Authorizer(ANY_USER, ['admin_user'], [], ['admin_user'], EmptyGroupProvider()) execution_service = MagicMock() execution_service.start_script.return_value = 3 cookie_secret = b'cookie_secret' server.init(config, MockAuthenticator(), authorizer, execution_service, MagicMock(), MagicMock(), ConfigService(authorizer, self.conf_folder), MagicMock(), FileUploadFeature(UserFileStorage(cookie_secret), test_utils.temp_folder), file_download_feature, 'cookie_secret', None, self.conf_folder, start_server=False) self.start_loop() self._user_session = requests.Session() self._user_session.cookies['username'] = create_signed_value(cookie_secret, 'username', 'normal_user') \ .decode('utf8') self._admin_session = requests.Session() self._admin_session.cookies['username'] = create_signed_value(cookie_secret, 'username', 'admin_user') \ .decode('utf8')
def set_cookie(self, name, value, expires_days=30, version=None, domain=None, expires=None, path="/", **kwargs): """ Sets the given cookie name/value with the given options. Set value to None to clear. The cookie value is secured using `flexx.config.cookie_secret`; don't forget to set that config value in your server. Additional keyword arguments are set on the Cookie.Morsel directly. """ # This code is taken (in modified form) from the Tornado project # Copyright 2009 Facebook # Licensed under the Apache License, Version 2.0 # Assume tornado is available ... from tornado.escape import native_str from tornado.httputil import format_timestamp from tornado.web import create_signed_value # Clear cookie? if value is None: value = "" expires = datetime.datetime.utcnow() - datetime.timedelta(days=365) else: secret = config.cookie_secret value = create_signed_value(secret, name, value, version=version, key_version=None) # The cookie library only accepts type str, in both python 2 and 3 name = native_str(name) value = native_str(value) if re.search(r"[\x00-\x20]", name + value): # Don't let us accidentally inject bad stuff raise ValueError("Invalid cookie %r: %r" % (name, value)) if name in self._cookies: del self._cookies[name] self._cookies[name] = value morsel = self._cookies[name] if domain: morsel["domain"] = domain if expires_days is not None and not expires: expires = datetime.datetime.utcnow() + datetime.timedelta( days=expires_days) if expires: morsel["expires"] = format_timestamp(expires) if path: morsel["path"] = path for k, v in kwargs.items(): if k == 'max_age': k = 'max-age' # skip falsy values for httponly and secure flags because # SimpleCookie sets them regardless if k in ['httponly', 'secure'] and not v: continue morsel[k] = v self._exec('document.cookie = "%s";' % morsel.OutputString().replace('"', '\\"'))
def populate_cookie_header(self, headers, username='******'): cookie_name, cookie_value = 'user', username secure_cookie = create_signed_value( self.get_app().settings["cookie_secret"], cookie_name, cookie_value) headers = HTTPHeaders(headers) headers.add( 'Cookie', b'='.join( (ensure_binary(cookie_name), ensure_binary(secure_cookie)))) return headers
def __init__(self, cookie_name, cookie_value, cookie_secret=None): # need to update this so it takes values like domain, expires, etc # for people who test more deeply. self._cookie = SimpleCookie() self._cookie_name = cookie_name if cookie_secret: cookie_value = create_signed_value(cookie_secret, cookie_name, cookie_value).decode("utf-8") self._cookie[cookie_name] = cookie_value
def fetch(self, url, method='GET', timeout=10, headers=None, user=None, **kwargs): if user: if secret is None: raise ConfError('Missing gramex.yaml:app.settings.cookie_secret. ' + 'Cannot encrypt user') user = json.dumps(user, ensure_ascii=True, separators=(',', ':')) if headers is None: headers = {} headers['X-Gramex-User'] = create_signed_value(secret, 'user', user) URLTest.r = requests.request(method, url, timeout=timeout, headers=headers, **kwargs)
def __init__(self, cookie_name, cookie_value, cookie_secret=None): # need to update this so it takes values like domain, expires, etc # for people who test more deeply. self._cookie = SimpleCookie() self._cookie_name = cookie_name if cookie_secret: cookie_value = create_signed_value( cookie_secret, cookie_name, cookie_value).decode("utf-8") self._cookie[cookie_name] = cookie_value
def get_headers(): cookie_secret = 'asdfasdf' auth = 'auth' auth_value = '7a7c4182f1bef7504a1d3d5eaa51a242' username = '******' username_value = 'threathunter_test' userid = 'user_id' userid_value = '2' secure_auth = create_signed_value(cookie_secret, auth, auth_value) secure_username = create_signed_value( cookie_secret, username, username_value) secure_userid = create_signed_value( cookie_secret, userid, userid_value) headers = HTTPHeaders() headers.add("Cookie", "=".join((auth, secure_auth))) headers.add("Cookie", "=".join((username, secure_username))) headers.add("Cookie", "=".join((userid, secure_userid))) return headers
def setUp(self): AsyncHTTPTestCase.setUp(self) self.tt_token = {'uid': '1', 'mobile': '18682212241'} token = create_signed_value( configs['cookie_secret'], 'token', token_encode(self.tt_token) ) self.tt_headers = {'Cookie': 'token=' + token} dbc = hqlh.db.get_conn('fitter') dbc.execute('TRUNCATE user')
def get_user_cookie(secret=None, author=None): if not secret: secret = config.appsettings["cookie_secret"] if not author: name = "user" if not author: author = model.Author(subdomain=SUBDOMAIN, email=EMAIL) return web.create_signed_value(secret, "user", author.url)
def encrypt_value(self, key: str, value: str) -> str: """Encrypt a value using the code used to create Tornado's secure cookies, using the common cookie secret. :param key: The name of the field containing the value :param value: The value to encrypt :rtype: str """ return web.create_signed_value(self.settings['cookie_secret'], key, value).decode('utf-8')
def test_types(self): cookie_value = to_unicode(create_signed_value(self.COOKIE_SECRET, "asdf", "qwer")) response = self.fetch("/typecheck/asdf?foo=bar", headers={"Cookie": "asdf=" + cookie_value}) data = json_decode(response.body) self.assertEqual(data, {}) response = self.fetch("/typecheck/asdf?foo=bar", method="POST", headers={"Cookie": "asdf=" + cookie_value}, body="foo=bar")
def get_user_cookie(secret=None, author=None): if not secret: secret = config.appsettings['cookie_secret'] if not author: name = 'user' if not author: author = model.Author(subdomain=SUBDOMAIN, email=EMAIL) return web.create_signed_value(secret, 'user', author.url)
def encrypt_value(key, value): """Encrypt a value using the code used to create Tornado's secure cookies, using the common cookie secret. :param str or bytes key: The name of the field containing the value :param str or bytes value: The value to encrypt :rtype: str """ return web.create_signed_value( os.environ.get('COOKIE_SECRET', DEFAULT_COOKIE_SECRET), key, value).decode('utf-8')
def Terminate(client, user_id, base_url, no_prompt=False): # Get target user objects. user = yield gen.Task(User.Query, client, user_id, None) print '--------- TERMINATE ACCOUNT ----------' print ' User account to terminate: %s (user %d)' % (user.email, user_id) print '' if not no_prompt: answer = raw_input('Are you SURE you want to do this? Type \'yes\' to confirm: ') print '' if answer.lower() != 'yes': print 'ABORTED account termination.' return # Construct cookies for the user. cookie_secret = GetSecret('cookie_secret') user_cookie = create_signed_value(cookie_secret, 'user', json.dumps(dict(user_id=user_id, device_id=user.webapp_dev_id, server_version=SERVER_VERSION))) timestamp = time.time() http_headers = { 'Cookie': '_xsrf=fake_xsrf; user=%s' % user_cookie, 'X-XSRFToken': 'fake_xsrf', 'Content-Type': 'application/json', } # Allocate unique asset ids for the operation. http_client = AsyncHTTPClient() body = {'headers': {'version': MAX_SUPPORTED_MESSAGE_VERSION}, 'asset_types': ['o']} response = yield gen.Task(http_client.fetch, '%s/service/allocate_ids' % base_url, method='POST', body=json.dumps(body), headers=http_headers, validate_cert=options.validate_cert) operation_id, = json.loads(response.body)['asset_ids'] body = {'headers': {'version': MAX_SUPPORTED_MESSAGE_VERSION, 'op_id': operation_id, 'op_timestamp': timestamp, 'synchronous': True}} yield gen.Task(http_client.fetch, '%s/service/terminate_account' % base_url, method='POST', body=json.dumps(body), headers=http_headers, validate_cert=options.validate_cert) print 'Account termination succeeded.'
def update_result_data(self, context, data): LOGGER.debug("current_user %s == %s", self.current_user, context.cookies.get('current_user')) if context.cookies.get('current_user') != self.current_user: setattr(self, '_current_user', context.cookies.get('current_user')) if not hasattr(self, "write_message"): self.set_current_user(context.cookies.get('current_user')) data['cookie_name'] = self.cookie_name data['cookie'] = web.create_signed_value( self.settings["cookie_secret"], self.cookie_name, dumps(self.current_user)).decode("utf-8")
def post(self, *args, **kwargs): self.get_paras_dict() user_service.set_db(self.db) rsp = {'stat': 'err', 'info': ''} try: is_ok, info = self.check_params() if not is_ok: rsp['info'] = info return self.write(ujson.dumps(rsp)) is_ok, info = self.check_phone_code() if not is_ok: rsp['info'] = info return self.write(ujson.dumps(rsp)) kargs = { 'phone': self.qdict.get('phone'), 'nick': self.qdict.get('nick', 'user_%s' % int(time.time())), 'is_employee': 0, 'user_pwd': self.qdict.get('password'), 'photo': options.DEFAULT_USER_PHOTO } is_add_ok, info = user_service.create_user(**kargs) if not is_add_ok: rsp['info'] = info return self.write(ujson.dumps(rsp)) if self.qdict.get('invite_code'): #存在邀请码 pass user_info = user_service.get_user_by_phone(kargs['phone']) cookies = user_service.user_format_app(user_info) login_token = create_signed_value( self.application.settings["cookie_secret"], 'loginuser', ujson.dumps(cookies)) rsp['stat'] = 'ok' rsp['data'] = { 'login_token': login_token, 'nick_name': user_info.Fnick_name, 'photo_url': user_info.Fphoto_url } return self.write(ujson.dumps(rsp)) except Exception, e: pass
def post_status_code(self, url, body, status_code): ''' make an authenticated POST request and return json if the status codes match ''' cookie_name, cookie_value = 'user', {'login': '******'} secure_cookie = create_signed_value(COOKIE_SECRET, cookie_name, json_encode(cookie_value)) headers = { 'Content-type': 'application/x-www-form-urlencoded', 'Cookie': '='.join((cookie_name, secure_cookie.decode())) } res = self.fetch(url, method='POST', body=json.dumps(body), headers=headers) assert res.code == status_code, "status {} != {} for url: {}\nparams: {}".format( res.code, status_code, url, body) return res.body
def post(self): '''用户登录''' form = SignInForm.from_json(self.get_body_json()) if not form.validate(): return self.fail(errors=form.errors) # support username login user = self.db.query(User).filter_by( username=form.username.data).first() # support email login if not user: user = self.db.query(User).filter_by( email=form.username.data).first() # support uid login if not user: try: UID = int(form.username.data) user = self.db.query(User).filter_by(uid=UID).first() except: pass if not user: return self.fail(_("Wrong username or password")) if user.is_locked: return self.fail(_("User is locked")) if not user.is_active: return self.fail(_("User is inactive")) if not user.check_password(form.password.data): return self.fail(_("Wrong username or password")) # 设置其他 user.last_login = datetime.datetime.utcnow() user.last_active = datetime.datetime.utcnow() # 验证成功 session = create_session( self.db, user, from_ip=self.request.remote_ip) self.require_setting("secret_key", "secure key") secret = self.application.settings["secret_key"] sid = create_signed_value( secret, "Sid", session.sid).decode() # TODO: fix me! self.success(sid=sid, expired=rfc3339_string(session.expired))
def post(self): '''用户登录''' form = SignInForm.from_json(self.get_body_json()) if not form.validate(): return self.fail(errors=form.errors) # support username login user = self.db.query(User).filter_by( username=form.username.data).first() # support email login if not user: user = self.db.query(User).filter_by( email=form.username.data).first() # support uid login if not user: try: UID = int(form.username.data) user = self.db.query(User).filter_by(uid=UID).first() except: pass if not user: return self.fail(_("Wrong username or password")) if user.is_locked: return self.fail(_("User is locked")) if not user.is_active: return self.fail(_("User is inactive")) if not user.check_password(form.password.data): return self.fail(_("Wrong username or password")) # 设置其他 user.last_login = datetime.datetime.utcnow() user.last_active = datetime.datetime.utcnow() # 验证成功 session = create_session(self.db, user, from_ip=self.request.remote_ip) self.require_setting("secret_key", "secure key") secret = self.application.settings["secret_key"] sid = create_signed_value(secret, "Sid", session.sid).decode() # TODO: fix me! self.success(sid=sid, expired=rfc3339_string(session.expired))
def get_play_ids(self, show_id, number, servers): results = [] for server in servers: results.append({ 'play_id': web.create_signed_value( secret=server.secret, name='play_id', value=utils.json_dumps({ 'show_id': int(show_id), 'number': int(number), }), version=2, ), 'play_server': server, }) server.__dict__.pop('secret') return results
def _auth_user(self, user): app = self.app # Generate a session ID session_id = app.session_store.generate_session_id() if self.session: app.session_store.delete_sessions(self.session.session_id) self.session = Session(session_id=session_id, redis_client=app.session_store.redis_client, user_id=user.id) app.session_store.add_session(self.session) # Generate a cookie associated to the created session ID cookie_name, cookie_value = app.session_store.COOKIE_NAME, str( session_id) secure_cookie = create_signed_value(app.settings['cookie_secret'], cookie_name, cookie_value).decode('utf-8') headers = {'Cookie': '='.join((cookie_name, secure_cookie))} return headers
def check_upload(self, *fileinfo, user={}, code=OK, check=True): files, data = [], {'tag': [], 'cat': []} for f in fileinfo: info = (f.get('name', f['file']), open(f['file'], 'rb')) if 'mime' in f: info += (f['mime'], ) files.append(('file', info)) for field in ('tag', 'cat'): if field in f: data[field].append(f[field]) headers = {} if user: secret = gramex.service.app.settings['cookie_secret'] headers['X-Gramex-User'] = create_signed_value( secret, 'user', json.dumps(user)) r = requests.post(self.url, files=files, data=data, headers=headers) eq_(r.status_code, code, '%s: code %d != %d' % (self.url, r.status_code, code)) data = gramex.data.filter(self.con, table='drive') data = data.sort_values('id').tail(len(files)) if not check: return for i, f in enumerate(fileinfo): result = data.iloc[i].to_dict() # If upload filehame has a path, only the basename is considered file = os.path.basename(f.get('name', f['file'])) eq_(result['file'], file) # Extension is stored in lowercase even if filename is in uppercase eq_(result['ext'], os.path.splitext(f['file'])[1].lower()) # Current time in seconds is stored as the date, to within a few seconds self.assertLess(time.time() - result['date'], 5) for field in ('tag', 'cat', 'user_id', 'user_role'): if field in f: eq_(result[field], f[field]) elif field[5:] in user: eq_(result[field], user[field[5:]]) else: ok_(result[field] in {'', None}) # File is stored in the target location os.path.exists(os.path.join(self.kwargs.path, f['file'])) return data
def main(): parse_command_line() io_loop = IOLoop.instance() assert options.user_id, '--user_id must be set' assert options.device_id, '--device_id must be set' assert options.method, '--method must be set' assert not options.base_url.endswith( '/'), 'base_url should be scheme://host:port only, no path' InitSecrets(callback=io_loop.stop) io_loop.start() cookie_secret = GetSecret('cookie_secret') # TODO(ben): move this (and the server_version constant) somewhere sharable that doesn't need # to pull in the entire server-side codebase. Or add an auth flow like fetch_logs so we don't # need production secrets at all. cookie = create_signed_value( cookie_secret, 'user', json.dumps( dict(user_id=options.user_id, device_id=options.device_id, server_version='1.1'))) url = '%s/service/%s' % (options.base_url, options.method) http_headers = { 'Cookie': '_xsrf=fake_xsrf; user=%s' % cookie, 'X-XSRFToken': 'fake_xsrf', 'Content-Type': 'application/json', } body = json.loads(options.body) body.setdefault('headers', {}).setdefault('version', MAX_SUPPORTED_MESSAGE_VERSION) # TODO: support op headers too response = HTTPClient().fetch(url, method='POST', body=json.dumps(body), headers=http_headers, validate_cert=options.validate_cert) print json.dumps(json.loads(response.body), indent=2)
def _get(self, show_id, number): with new_session() as session: p = session.query(models.Play_server).filter( models.Play_access.user_id == self.current_user.id, models.Play_server.id == models.Play_access.play_server_id, ).options(sa.orm.undefer_group('secret')).all() playids = [] for s in p: playids.append({ 'play_id': web.create_signed_value( secret=s.secret, name='play_id', value=utils.json_dumps({ 'show_id': int(show_id), 'number': int(number), }), version=2, ), 'play_url': s.url, }) return playids
def main(): parser = argparse.ArgumentParser( description="Generate a password reset link for manual delivery", ) parser.add_argument('config_file', help="Configuration file") parser.add_argument('user_login') args = parser.parse_args() config = {} config_file = os.path.abspath(args.config_file) with open(config_file) as fp: code = compile(fp.read(), config_file, 'exec') exec(code, config) DBSession = database.connect(config['DATABASE']) db = DBSession() user = db.query(database.User).get(args.user_login) if user is None: print("No such user: %r" % args.user_login, file=sys.stderr) # Generate a signed token reset_token = '%s|%s|%s' % ( int(time.time()), user.login, user.email, ) reset_token = create_signed_value( config['SECRET_KEY'], 'reset_token', reset_token, ) reset_token = reset_token.decode('utf-8') reset_link = '/new_password?reset_token=' + reset_token print(reset_link)
def gen_login_cookie(self,value): return create_signed_value(self.application.settings["cookie_secret"], self.cookie_name, value)
def encodestr(s): secret, name = _secret_and_name() return create_signed_value(secret, name, s)
def pack_user(self, user_info): assert "password" not in user_info value = json.dumps(user_info) return web.create_signed_value(self.key, self.value_name, value)
def headers(self): cookie = create_signed_value(self.app.settings['cookie_secret'], 'login_user', '1234').decode() headers = dict(COOKIE='login_user=%s' % cookie) return headers
def test_01_create_game(self): url = '/' kwargs = {'method': 'GET'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/signup' kwargs = {'method': 'GET'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/signup' cookie_value = create_signed_value(self.app.settings['cookie_secret'], 'loggedin', str(True)) cookies = 'loggedin='+cookie_value.decode('utf-8') kwargs = {'method': 'POST', 'body': b'game=&user=&password=NCSS', 'headers': {'Cache-Control': 'no-cache', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36', 'Origin': 'http://localhost:8888', 'Referer': 'http://localhost:8888/signup', 'Connection': 'keep-alive', 'Content-Length': '25', 'Cookie': cookies, 'Host': 'localhost:8888', 'Accept-Encoding': 'gzip, deflate', 'Pragma': 'no-cache', 'Accept-Language': 'en-GB,en-US;q=0.8,en;q=0.6', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'}} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/login' kwargs = {'method': 'GET'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/login' kwargs = {'body': b'game=&user=&password=NCSS', 'headers': {'Referer': 'http://localhost:8888/login', 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '19', 'Accept-Language': 'en-GB,en-US;q=0.8,en;q=0.6', 'Cookie': cookies, 'Host': 'localhost:8888', 'Origin': 'http://localhost:8888', 'Cache-Control': 'max-age=0', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36'}, 'method': 'POST'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/admin' kwargs = {'method': 'GET', 'headers': {'Cookie': cookies}} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/game?year=2014' kwargs = {'method': 'GET', 'headers': {'Cookie': cookies}} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/admin' kwargs = {'method': 'GET', 'headers': {'Cookie': cookies}} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/player' kwargs = {'body': b'------WebKitFormBoundarySAofcG3B09Hzp1dG\r\nContent-Disposition: form-data; name="game"\r\n\r\n0\r\n------WebKitFormBoundarySAofcG3B09Hzp1dG\r\nContent-Disposition: form-data; name="players"; filename="players.csv"\r\nContent-Type: text/csv\r\n\r\nname,type\nAndy,x\nBen,x\nCaitlin,y\nDaniel,x\nElla,y\nFran,x\nGeorge,x\n\r\n------WebKitFormBoundarySAofcG3B09Hzp1dG--\r\n', 'headers': {'Referer': 'http://localhost:8888/0/admin', 'Connection': 'keep-alive', 'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundarySAofcG3B09Hzp1dG', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '343', 'Accept-Language': 'en-GB,en-US;q=0.8,en;q=0.6', 'Cookie': cookies, 'Host': 'localhost:8888', 'Origin': 'http://localhost:8888', 'Cache-Control': 'max-age=0', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36'}, 'method': 'POST'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/profiles' kwargs = {'method': 'GET'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/profiles/Andy' kwargs = {'method': 'GET'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/stats' kwargs = {'method': 'GET'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/achievements' kwargs = {'method': 'GET'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/murders' kwargs = {'method': 'GET'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/admin' kwargs = {'method': 'GET', 'headers': {'Cookie': cookies}} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/player' kwargs = {'body': b'------WebKitFormBoundaryaqWmvV6HljZEtPn9\r\nContent-Disposition: form-data; name="game"\r\n\r\n0\r\n------WebKitFormBoundaryaqWmvV6HljZEtPn9\r\nContent-Disposition: form-data; name="players"; filename="players2.csv"\r\nContent-Type: text/csv\r\n\r\nname,type\nHenry,x\nIan,y\nJane,y\nKelly,z\nLisa,y\n\r\n------WebKitFormBoundaryaqWmvV6HljZEtPn9--\r\n', 'headers': {'Referer': 'http://localhost:8888/0/admin', 'Connection': 'keep-alive', 'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryaqWmvV6HljZEtPn9', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '325', 'Accept-Language': 'en-GB,en-US;q=0.8,en;q=0.6', 'Cookie': cookies, 'Host': 'localhost:8888', 'Origin': 'http://localhost:8888', 'Cache-Control': 'max-age=0', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36'}, 'method': 'POST'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/profiles' kwargs = {'method': 'GET'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/admin' kwargs = {'method': 'GET', 'headers': {'Cookie': cookies}} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/admin' kwargs = {'method': 'GET', 'headers': {'Cookie': cookies}} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/achievements' kwargs = {'method': 'GET'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/stats' kwargs = {'method': 'GET'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/admin' kwargs = {'method': 'GET', 'headers': {'Cookie': cookies}} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/murder' kwargs = {'body': b'game=0&murderer=1&victim=1&datetime=2014-12-18T08%3A11%2B1100&location=Women%27s+College&lat=-33.890763&lng=151.186772', 'headers': {'Referer': 'http://localhost:8888/0/admin', 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '111', 'Accept-Language': 'en-GB,en-US;q=0.8,en;q=0.6', 'Cookie': cookies, 'Host': 'localhost:8888', 'Origin': 'http://localhost:8888', 'Cache-Control': 'max-age=0', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36'}, 'method': 'POST'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/murders' kwargs = {'method': 'GET'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/murder' kwargs = {'body': b'game=0&murderer=10&victim=6&datetime=2014-12-17T22%3A11%2B1100&location=SIT&lat=-33.888216&lng=151.194132', 'headers': {'Referer': 'http://localhost:8888/0/admin', 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '98', 'Accept-Language': 'en-GB,en-US;q=0.8,en;q=0.6', 'Cookie': cookies, 'Host': 'localhost:8888', 'Origin': 'http://localhost:8888', 'Cache-Control': 'max-age=0', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36'}, 'method': 'POST'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/murders' kwargs = {'method': 'GET'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/profiles/Jane' kwargs = {'method': 'GET'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/murders' kwargs = {'method': 'GET'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/stats' kwargs = {'method': 'GET'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url)) url = '/0/achievements' kwargs = {'method': 'GET'} response = self.fetch(url, **kwargs) if response.error: raise Exception('{}: {} {} {}'.format(response.error, response.code, response.request.method, response.request.url))
def tokenize_value(key, value): return base64.b64encode(random_bytes(_TOKENIZE_RANDOM_PADDING) + create_signed_value(key, "0", value))
def CreateUnsubscribeCookie(cls, user_id, email_type): """Create a user unsubscribe cookie that is passed as an argument to the unsubscribe handler, and which proves control of the given user id. """ unsubscribe_dict = {'user_id': user_id, 'email_type': email_type} return web.create_signed_value(secrets.GetSecret('invite_signing'), 'unsubscribe', json.dumps(unsubscribe_dict))