def login(request, user): """Spawn a login process for the user The ``auth_requred`` decorator is used to require that the user authenticate through ``auth.mast``, then the user is redirected back to the homepage. Parameters ---------- request : HttpRequest object Incoming request from the webpage user : dict A dictionary of user credentials. Returns ------- HttpResponse object Outgoing response sent to the webpage """ # Redirect to oauth login global PREV_PAGE PREV_PAGE = request.META.get('HTTP_REFERER') redirect_uri = os.path.join(get_base_url(), 'authorize') return JWQL_OAUTH.mast_auth.authorize_redirect(request, redirect_uri)
def archived_proposals(request, user, inst): """Generate the page listing all archived proposals in the database Parameters ---------- request : HttpRequest object Incoming request from the webpage inst : str Name of JWST instrument Returns ------- HttpResponse object Outgoing response sent to the webpage """ # Ensure the instrument is correctly capitalized inst = JWST_INSTRUMENT_NAMES_MIXEDCASE[inst.lower()] template = 'archive.html' context = { 'inst': inst, 'tools': MONITORS, 'user': user, 'base_url': get_base_url(), 'version': jwql.__version__ } return render(request, template, context)
def archive_thumbnails(request, user, inst, proposal): """Generate the page listing all archived images in the database for a certain proposal Parameters ---------- request : HttpRequest object Incoming request from the webpage inst : str Name of JWST instrument proposal : str Number of observing proposal Returns ------- HttpResponse object Outgoing response sent to the webpage """ # Ensure the instrument is correctly capitalized inst = JWST_INSTRUMENT_NAMES_MIXEDCASE[inst.lower()] template = 'thumbnails.html' context = {'inst': inst, 'prop': proposal, 'base_url': get_base_url()} return render(request, template, context)
def test_api_views(url): """Test to see if the given ``url`` returns a populated JSON object Parameters ---------- url : str The url to the api view of interest (e.g. ``http://127.0.0.1:8000/api/86700/filenames/'``). """ # Build full URL if not ON_JENKINS: base_url = get_base_url() else: base_url = 'https://dljwql.stsci.edu' if base_url == 'http://127.0.0.1:8000' and not LOCAL_SERVER: pytest.skip("Local server not running") url = '{}/{}'.format(base_url, url) # Determine the type of data to check for based on the url data_type = url.split('/')[-2] try: url = request.urlopen(url) except error.HTTPError as e: if e.code == 502: pytest.skip("Dev server problem") raise(e) data = json.loads(url.read().decode()) assert len(data[data_type]) > 0
def test_api_views(url): """Test to see if the given ``url`` returns a populated JSON object Parameters ---------- url : str The url to the api view of interest (e.g. ``http://127.0.0.1:8000/api/86700/filenames/'``). """ # Build full URL if not ON_GITHUB_ACTIONS: base_url = get_base_url() # For running unit tests locally else: base_url = 'https://jwql.stsci.edu' # Once this actually exists, remove skipif url = '{}/{}'.format(base_url, url) # Determine the type of data to check for based on the url data_type = url.split('/')[-2] try: url = request.urlopen(url) except error.HTTPError as e: if e.code == 502: pytest.skip("Dev server problem") raise (e) try: data = json.loads(url.read().decode()) assert len(data[data_type]) > 0 except (http.client.IncompleteRead) as e: data = e.partial assert len(data) > 0
def query_submit(request): """Generate the page listing all archived images in the database for a certain proposal Parameters ---------- request : HttpRequest object Incoming request from the webpage Returns ------- HttpResponse object Outgoing response sent to the webpage """ template = 'query_submit.html' parameters = {} parameters['instruments'] = anomaly_query_config.INSTRUMENTS_CHOSEN parameters['apertures'] = anomaly_query_config.APERTURES_CHOSEN parameters['filters'] = anomaly_query_config.FILTERS_CHOSEN parameters['detectors'] = anomaly_query_config.DETECTORS_CHOSEN parameters['exposure_types'] = anomaly_query_config.EXPTYPES_CHOSEN parameters['read_patterns'] = anomaly_query_config.READPATTS_CHOSEN parameters['gratings'] = anomaly_query_config.GRATINGS_CHOSEN parameters[ 'anomalies'] = anomaly_query_config.ANOMALIES_CHOSEN_FROM_CURRENT_ANOMALIES anomaly_query_config.PARAMETERS = parameters context = {'inst': '', 'base_url': get_base_url()} return render(request, template, context)
def check_auth(request, user): """Check if the user is authenticated through ``auth.mast``. If not, perform the authorization. Parameters ---------- request : HttpRequest object Incoming request from the webpage user : dict A dictionary of user credentials Returns ------- fn : function The decorated function """ # If user is currently anonymous, require a login if user["anon"]: # Redirect to oauth login redirect_uri = os.path.join(get_base_url(), 'authorize') return JWQL_OAUTH.mast_auth.authorize_redirect( request, redirect_uri) return fn(request, user)
def query_submit(request): """Generate the page listing all archived images in the database for a certain proposal Parameters ---------- request : HttpRequest object Incoming request from the webpage Returns ------- HttpResponse object Outgoing response sent to the webpage """ template = 'query_submit.html' parameters = {} parameters['instruments'] = anomaly_query_config.INSTRUMENTS_CHOSEN parameters['apertures'] = anomaly_query_config.APERTURES_CHOSEN parameters['filters'] = anomaly_query_config.FILTERS_CHOSEN parameters['detectors'] = anomaly_query_config.DETECTORS_CHOSEN parameters['exposure_types'] = anomaly_query_config.EXPTYPES_CHOSEN parameters['read_patterns'] = anomaly_query_config.READPATTS_CHOSEN parameters['gratings'] = anomaly_query_config.GRATINGS_CHOSEN parameters[ 'anomalies'] = anomaly_query_config.ANOMALIES_CHOSEN_FROM_CURRENT_ANOMALIES thumbnails = get_thumbnails_all_instruments(parameters) anomaly_query_config.THUMBNAILS = thumbnails # get information about thumbnails for thumbnail viewer proposal_info = get_proposal_info(thumbnails) context = { 'inst': '', 'anomalies_chosen_from_current_anomalies': anomaly_query_config.ANOMALIES_CHOSEN_FROM_CURRENT_ANOMALIES, 'apertures_chosen': anomaly_query_config.APERTURES_CHOSEN, 'filters_chosen': anomaly_query_config.FILTERS_CHOSEN, 'inst_list_chosen': anomaly_query_config.INSTRUMENTS_CHOSEN, 'detectors_chosen': anomaly_query_config.DETECTORS_CHOSEN, 'thumbnails': thumbnails, 'base_url': get_base_url(), 'rootnames': thumbnails, 'thumbnail_data': { 'inst': "Queried Anomalies", 'all_filenames': thumbnails, 'num_proposals': proposal_info['num_proposals'], 'thumbnails': { 'proposals': proposal_info['proposals'], 'thumbnail_paths': proposal_info['thumbnail_paths'], 'num_files': proposal_info['num_files'] } } } return render(request, template, context)
def test_base_context(self): """Tests the ``base_context`` function.""" client = Client() request = client.get('{}/about/'.format(get_base_url())) request.COOKIES = {} context = context_processors.base_context(request) assert isinstance(context, dict) keys = ['inst_list', 'tools', 'user', 'version'] for key in keys: assert key in context
def dashboard_instrument_pie_chart(self): """Create piechart showing number of files per instrument Returns ------- plot : bokeh.plotting.figure Pie chart figure """ # Replace with jwql.website.apps.jwql.data_containers.build_table data = build_table('filesystem_instrument') if not pd.isnull(self.delta_t): data = data[(data['date'] >= self.date - self.delta_t) & (data['date'] <= self.date)] try: file_counts = {'nircam': data.instrument.str.count('nircam').sum(), 'nirspec': data.instrument.str.count('nirspec').sum(), 'niriss': data.instrument.str.count('niriss').sum(), 'miri': data.instrument.str.count('miri').sum(), 'fgs': data.instrument.str.count('fgs').sum()} except AttributeError: file_counts = {'nircam': 0, 'nirspec': 0, 'niriss': 0, 'miri': 0, 'fgs': 0} data = pd.Series(file_counts).reset_index(name='value').rename(columns={'index': 'instrument'}) data['angle'] = data['value'] / data['value'].sum() * 2 * pi data['color'] = ['#F8B195', '#F67280', '#C06C84', '#6C5B7B', '#355C7D'] plot = figure(title="Number of Files Per Instruments", toolbar_location=None, tools="hover,tap", tooltips="@instrument: @value", x_range=(-0.5, 1.0)) plot.wedge(x=0, y=1, radius=0.4, start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'), line_color="white", color='color', legend='instrument', source=data) url = "{}/@instrument".format(get_base_url()) taptool = plot.select(type=TapTool) taptool.callback = OpenURL(url=url) plot.axis.axis_label = None plot.axis.visible = False plot.grid.grid_line_color = None return plot
def test_loading_times(url): """Test to see if the given ``url`` returns a webpage sucessfully within a reasonable time. Parameters ---------- url : str The url to the webpage of interest (e.g. ``http://127.0.0.1:8000/fgs/archive/'``). """ # Build full URL base_url = get_base_url() url = '{}/{}'.format(base_url, url) print('Testing {}'.format(url)) t1 = time.time() url = urllib.request.urlopen(url) t2 = time.time() assert (t2 - t1) <= TIME_CONSTRAINT
def test_api_views(url): """Test to see if the given ``url`` returns a populated JSON object Parameters ---------- url : str The url to the api view of interest (e.g. ``http://127.0.0.1:8000/api/86700/filenames/'``). """ # Build full URL base_url = get_base_url() url = '{}/{}'.format(base_url, url) # Determine the type of data to check for based on the url data_type = url.split('/')[-2] url = urllib.request.urlopen(url) data = json.loads(url.read().decode()) assert len(data[data_type]) > 0
def authorize(request): """Spawn the authentication process for the user The authentication process involves retreiving an access token from ``auth.mast`` and porting the data to a cookie. Parameters ---------- request : HttpRequest object Incoming request from the webpage Returns ------- HttpResponse object Outgoing response sent to the webpage """ # Get auth.mast token token = JWQL_OAUTH.mast_auth.authorize_access_token( request, headers={'Accept': 'application/json'}) # Determine domain base_url = get_base_url() if '127' in base_url: domain = '127.0.0.1' else: domain = base_url.split('//')[-1] # Set secure cookie parameters cookie_args = {} # cookie_args['domain'] = domain # Currently broken # cookie_args['secure'] = True # Currently broken cookie_args['httponly'] = True # Set the cookie response = redirect("/") response.set_cookie("ASB-AUTH", token["access_token"], **cookie_args) return response