def test_generate_unsigned(self): session_id = generate_session_id(signed=False) assert 44 == len(session_id) another_session_id = generate_session_id(signed=False) assert 44 == len(another_session_id) assert session_id != another_session_id
def test_generate_unsigned(self): session_id = generate_session_id(signed=False) self.assertEqual(44, len(session_id)) another_session_id = generate_session_id(signed=False) self.assertEqual(44, len(another_session_id)) self.assertNotEqual(session_id, another_session_id)
def plojo_help(): root = urlparse(request.base_url).hostname script = server_session(url='http://' + root + ':5006/plojo_help', session_id=generate_session_id()) return render_template('apps/simuojo.html', script=script, title='Plojo Help')
def sliders_view(request): # Define bokeh endpoint url bokeh_server_url = "%sbokehproxy/sliders" % (request.build_absolute_uri( location='/')) # Generate bokeh session token so user can access plot, this is done for all logged in users per the @login_required decorator # ensuring only logged in users can view plots # Using newer bokeh server_session method vs. deprecated bokeh.embed.autoload_server # Note: session_id.generate_session_id() relies on the presence of BOKEH_SECRET_KEY defined in settings.py via an OS variable server_script = server_session(None, session_id=session_id.generate_session_id(), url=bokeh_server_url) # Tip: More elaborate permission checks can be made using Django's user system, to generate (or not) bokeh session accesss tokens: # if user.is_authenticated() and user.has_perm("bokehdash.change_plot"): # server_session(None, session_id=....) # else: # HttpResponseRedirect("You can't see this plot") # Tip2: More elaborate permissions checks can also be made with other method decorators @user_passes_test, @permission_required # (besides @login_reqired) # Proceed with context and response context = { "graphname": "Sliders", "server_script": server_script, } return render(request, 'bokehdash/bokeh_server.html', context)
def get_session(self): session_id = self.get_argument("bokeh-session-id", default=None) if session_id is None: if self.application.generate_session_ids: session_id = generate_session_id(secret_key=self.application.secret_key, signed=self.application.sign_sessions) else: # if there is an auth server, redirect to it auth_server = os.environ.get('AUTH_SERVER') if auth_server: callback_url = '%s://%s/login?page=%s' % (self.request.protocol, self.request.host, self.request.uri) url = auth_server + '/login?next=%s' % callback_url self.set_status(302) self.set_header('Location', url) raise Finish() else: log.debug("Server configured not to generate session IDs and none was provided") raise HTTPError(status_code=403, reason="No bokeh-session-id provided") elif not check_session_id_signature(session_id, secret_key=self.application.secret_key, signed=self.application.sign_sessions): log.error("Session id had invalid signature: %r", session_id) raise HTTPError(status_code=403, reason="Invalid session ID") session = yield self.application_context.create_session_if_needed(session_id) raise gen.Return(session)
def _validate_token(self, token): try: url = '%s/validate/%s?next=%s' % (self.auth_server, token, self.login_url) r = requests.get(url) if r.status_code == 200: response = r.json() data = response.get('data') if data: if data.get('status') == 'valid': authenticator = data.get('authenticator', '') user = data.get('user', '') uid = '%s @ %s' % (user, authenticator) log.info('Logged in user: %s', uid) session_id = generate_session_id(secret_key=self.application.secret_key, signed=self.application.sign_sessions) next_url = '%s?bokeh-session-id=%s' % (self.next_page, session_id) self.redirect(next_url) return else: debug_err = 'token status is "%s"' % str(data.get('status')) else: debug_err = 'no token data was returned' else: debug_err = 'HTTP error (%d) when retreiving token data' % r.status_code except Exception as exc: debug_err = 'Exception: %s' % str(exc) log.warn('Token validation failed: %s', debug_err) self.redirect(self.login_url)
def test_check_signature_of_unsigned(self): session_id = generate_session_id( signed=False, secret_key="abc") # secret shouldn't be used self.assertFalse( check_session_id_signature(session_id, secret_key="abc", signed=True))
def home(): # pull a new session from a running Bokeh server bokeh_server_url = 'http://192.168.1.15:5006/aion-analytics' #bokeh_session = pull_session(url=bokeh_server_url) bokeh_session = generate_session_id() script = "{}?bokeh-session-id={}".format(bokeh_server_url, bokeh_session) logger.warning("bokeh url:%s", script) return render_template('index.html', script=script, template="Flask")
def test_generate_signed(self): session_id = generate_session_id(signed=True, secret_key="abc") assert '-' in session_id assert check_session_id_signature(session_id, secret_key="abc", signed=True) assert not check_session_id_signature( session_id, secret_key="qrs", signed=True)
def login(): error = None if request.method == 'POST': if request.form['username'] != 'admin' or request.form['password'] != 'xxxxxx': error = 'Invalid Credentials. Please try again.' else: s_id = session_id.generate_session_id() return redirect("http://192.168.0.99:5006/CRM_bokeh_app?bokeh-session-id={}".format(s_id), code=302) return render_template('login.html', error=error)
def bokeh_js_script(relative_urls=True): #session = pull_session(self.address) #session.document.template_variables['data_path'] = self.data_path s_id = session_id.generate_session_id(secret_key=BOKEH_KEY, signed=True) return server_session(None, session_id=s_id, url=BOKEH_ADDRESS, relative_urls=relative_urls, resources='default')
def test_string_encoding_does_not_affect_session_id_check(self): # originates from #6653 session_id = generate_session_id(signed=True, secret_key="abc") assert check_session_id_signature(session_id, secret_key="abc", signed=True) assert check_session_id_signature(session_id, secret_key="abc", signed=True)
def mybnb(self): # pull a new session from a running Bokeh server bokeh_server_url = 'http://amdatt.ml:5007' # bokeh_session = pull_session(url=bokeh_server_url) bokeh_session = generate_session_id() script = "{}?bokeh-session-id={}".format(bokeh_server_url, bokeh_session) return render_template('mybnb.html', data=script, base_template=appbuilder.base_template, appbuilder=appbuilder)
def confirmed_uk_map_plot(request): bokeh_server_url = "%sbokehproxy/covid-confirmed-uk-map-plot" % ( request.build_absolute_uri(location='/')) server_script = server_session(None, session_id=session_id.generate_session_id(), url=bokeh_server_url) context = { "server_script": server_script, } return render(request, 'charts/confirmed-uk-map-plot.html', context)
def country_stats(request): bokeh_server_url = "%sbokehproxy/covid-country-stats" % ( request.build_absolute_uri(location='/')) server_script = server_session(None, session_id=session_id.generate_session_id(), url=bokeh_server_url) context = { "server_script": server_script, } return render(request, 'charts/country-stats.html', context)
def confirmed_against_time_bar(request): bokeh_server_url = "%sbokehproxy/covid-confirmed-against-time-bar" % ( request.build_absolute_uri(location='/')) server_script = server_session(None, session_id=session_id.generate_session_id(), url=bokeh_server_url) context = { "server_script": server_script, } return render(request, 'charts/confirmed-against-time-bar.html', context)
def interactive(request): #bokeh_script=autoload_server(None, url="http://localhost:5006/random-generator") server_script = server_session(None, session_id=session_id.generate_session_id(), url="http://localhost:5006/slider") context = { "graphname": "Sliders", "server_script": server_script, } return render(request, 'bokehapp/interactive.html', context)
def daily_confirmed_vs_time(request): bokeh_server_url = "%sbokehproxy/covid-daily-confirmed-cases" % ( request.build_absolute_uri(location='/')) server_script = server_session(None, session_id=session_id.generate_session_id(), url=bokeh_server_url) context = { "server_script": server_script, } return render(request, 'charts/daily-confirmed-cases.html', context)
def total_deaths_since_first(request): bokeh_server_url = "%sbokehproxy/covid-total-deaths-since-first" % ( request.build_absolute_uri(location='/')) server_script = server_session(None, session_id=session_id.generate_session_id(), url=bokeh_server_url) context = { "server_script": server_script, } return render(request, 'charts/total-deaths-since-first.html', context)
def deaths_vs_time(request): bokeh_server_url = "%sbokehproxy/covid-deaths-against-time" % ( request.build_absolute_uri(location='/')) server_script = server_session(None, session_id=session_id.generate_session_id(), url=bokeh_server_url) context = { "server_script": server_script, } return render(request, 'charts/deaths-against-time.html', context)
def get_session(self): session_id = self.get_argument("bokeh-session-id", default=None) if session_id is None: session_id = generate_session_id() elif not check_session_id_signature(session_id): log.error("Session id had invalid signature: %r", session_id) raise HTTPError(status_code=403, reason="Invalid session ID") session = self.application_context.create_session_if_needed(session_id) return session
def test_generate_signed(self): session_id = generate_session_id(signed=True, secret_key="abc") self.assertTrue('-' in session_id) self.assertTrue( check_session_id_signature(session_id, secret_key="abc", signed=True)) self.assertFalse( check_session_id_signature(session_id, secret_key="qrs", signed=True))
def histogram_view(request): bokeh_server_url = "%sbokehproxy/selection_histogram" % ( request.build_absolute_uri(location='/')) server_script = server_session(None, session_id=session_id.generate_session_id(), url=bokeh_server_url) context = { "graphname": "Selection Histogram", "server_script": server_script, } return render(request, 'bokehdash/bokeh_server.html', context)
def Test(request): bokeh_server_url = "%sbokehproxy/Test" % (request.build_absolute_uri( location='/')) server_script = server_session(None, session_id=session_id.generate_session_id(), url=bokeh_server_url) context = { "graphname": "Test", "server_script": server_script, } return render(request, 'charts/Test.html', context)
def transactions(request): if validate_view(request, '820transactions'): bokeh_server_url = "%sbokehproxy/820transactions" % ( request.build_absolute_uri(location='/')) transactions_script = server_session( None, session_id=session_id.generate_session_id(), url=bokeh_server_url) context = { "graphname": "820 Transactions", "server_script": transactions_script, } context = build_access_context(context, request) return render(request, 'dashboard/dynamicsingle.html', context) else: return redirect('home')
def build_script_tag(): elementid = make_id() relative_urls, url = settings.BOKEH_SERVE_SETTINGS[ 'relative_urls'], settings.BOKEH_SERVE_SETTINGS['url'] _session_id = session_id.generate_session_id( secret_key=settings.BOKEH_SECRET_KEY, signed=True) app_path = server._get_app_path(url) src_path = server._src_path(url, elementid) src_path += server._process_app_path(app_path) src_path += server._process_relative_urls(relative_urls, url) src_path += server._process_session_id(_session_id) src_path += server._process_resources('default') src_path += server._process_arguments(arguments) return server.encode_utf8( server.AUTOLOAD_TAG.render(src_path=src_path, app_path=app_path, elementid=elementid))
def get_session(self): session_id = self.get_argument("bokeh-session-id", default=None) if session_id is None: if self.application.generate_session_ids: session_id = generate_session_id(secret_key=self.application.secret_key, signed=self.application.sign_sessions) else: log.debug("Server configured not to generate session IDs and none was provided") raise HTTPError(status_code=403, reason="No bokeh-session-id provided") elif not check_session_id_signature(session_id, secret_key=self.application.secret_key, signed=self.application.sign_sessions): log.error("Session id had invalid signature: %r", session_id) raise HTTPError(status_code=403, reason="Invalid session ID") session = yield self.application_context.create_session_if_needed(session_id, self) raise gen.Return(session)
def get_session(self): session_id = self.get_argument("bokeh-session-id", default=None) if session_id is None: if self.application.generate_session_ids: session_id = generate_session_id(secret_key=self.application.secret_key, signed=self.application.sign_sessions) else: log.debug("Server configured not to generate session IDs and none was provided") raise HTTPError(status_code=403, reason="No bokeh-session-id provided") elif not check_session_id_signature(session_id, secret_key=self.application.secret_key, signed=self.application.sign_sessions): log.error("Session id had invalid signature: %r", session_id) raise HTTPError(status_code=403, reason="Invalid session ID") session = yield self.application_context.create_session_if_needed(session_id, self.request) raise gen.Return(session)
def get(self, *args, **kwargs): session_id = self.get_argument("bokeh-session-id", default=None) if session_id is None: session_id = generate_session_id() elif not check_session_id_signature(session_id): log.error("Session id had invalid signature: %r", session_id) raise HTTPError(status_code=403, reason="Invalid session ID") session = self.application_context.create_session_if_needed(session_id) websocket_url = self.application.websocket_url_for_request(self.request, self.bokeh_websocket_path) page = server_html_page_for_session( session_id, self.application.resources(self.request), title=session.document.title, websocket_url=websocket_url, ) self.set_header("Content-Type", "text/html") self.write(page)
def index(): if not google.authorized: return redirect(url_for("google.login")) try: resp = google.get("/oauth2/v2/userinfo") assert resp.ok, resp.text domain = re.search("@[\w.]+", resp.json()["email"]) except (InvalidGrantError, TokenExpiredError) as e: # or maybe any OAuth2Error return redirect(url_for("google.login")) if domain.group() == ALLOWED_DOMAIN: s_id = session_id.generate_session_id(secret_key=BOKEH_SECRET, signed=True) return redirect( "{url}/dashboard_simple/?bokeh-session-id={s_id}".format( s_id=s_id, url=BOKEH_URL), code=302) return "Hi {email} you are not allowed to login on this page".format( email=resp.json()["email"])
async def _get_session(self): #session_id = self.get_argument("bokeh-session-id", default=None) session_id = None if session_id is None: if True: session_id = generate_session_id(secret_key=None, signed=False) else: log.debug("Server configured not to generate session IDs and none was provided") raise Exception(status_code=403, reason="No bokeh-session-id provided") elif not check_session_id_signature(session_id, secret_key=self.application.secret_key, signed=self.application.sign_sessions): log.error("Session id had invalid signature: %r", session_id) raise Exception(status_code=403, reason="Invalid session ID") self.arguments = {} self.request = self session = await self.application_context.create_session_if_needed(session_id, self.request) return session
async def get_plots(request): loaded_request = PlotsRequestSchema().load(request.query) offset = loaded_request['offset'] limit = loaded_request['limit'] total_length = len(request.app['keys_df'].index) selected_keys = request.app['keys_df'].sort_values( loaded_request['sort'], ascending=loaded_request['ascending']).iloc[offset:limit + offset] record_dicts_list = selected_keys.to_dict(orient='records') for i, record in enumerate(record_dicts_list): localhost_url = 'http://' + os.environ[ 'SERVER_HOST_NAME'] + ':5006/image' arguments = { 'key': record['Key'], 'bucket': request.app['bucket'], 'width': loaded_request['width'], 'height': loaded_request['height'] } resources = 'default' if i == 0 else None record['bokeh_tag'] = server_document(localhost_url, arguments=arguments) record['script_src'] = re.search(', "(.*)", true', record['bokeh_tag']).group(1) record['script_id'] = re.search('id="(.*)"', record['bokeh_tag']).group(1) record['session_id'] = generate_session_id() # session.id record['token'] = generate_jwt_token(record['session_id']) response_data = S3ObjectBokehPlotsGetResponseSchema().dump({ 'plots': record_dicts_list, 'length': total_length }) return web.json_response(response_data)
async def _get_session(self) -> ServerSession: session_id = generate_session_id(secret_key=None, signed=False) session = await self.application_context.create_session_if_needed( session_id, self.request) return session
def test_generate_signed(self): session_id = generate_session_id(signed=True, secret_key="abc") self.assertTrue('-' in session_id) self.assertTrue(check_session_id_signature(session_id, secret_key="abc", signed=True)) self.assertFalse(check_session_id_signature(session_id, secret_key="qrs", signed=True))
def test_string_encoding_does_not_affect_session_id_check(self): # originates from #6653 session_id = generate_session_id(signed=True, secret_key="abc") assert check_session_id_signature(session_id, secret_key="abc", signed=True) assert check_session_id_signature(decode_utf8(session_id), secret_key="abc", signed=True)
def test_check_signature_of_unsigned(self): session_id = generate_session_id(signed=False, secret_key="abc") # secret shouldn't be used assert not check_session_id_signature(session_id, secret_key="abc", signed=True)
def test_generate_signed(self): session_id = generate_session_id(signed=True, secret_key="abc") assert '-' in session_id assert check_session_id_signature(session_id, secret_key="abc", signed=True) assert not check_session_id_signature(session_id, secret_key="qrs", signed=True)
def _ensure_session_id(cls, session_id): if session_id is None: session_id = generate_session_id() return session_id