def _can_edit(self, uri): if current_user.has_role('Publisher') or current_user.has_role( 'Editor'): return True if (uri + "#assertion", app.NS.prov.wasAttributedTo, current_user.resUri) in app.db: return True return False
def add_user_role(): if hasattr(current_user, "id"): user = db.session.query(User).get(current_user.id) if not current_user.has_role("candidate") or \ not current_user.has_role("company"): role = request.args.get("role", None) if role: role_to_set = db.session.query(Role).filter_by(name=role).first() user.roles.append(role_to_set) db.session.commit()
def _can_edit(self, uri): if current_user.has_role('Publisher') or current_user.has_role('Editor') or current_user.has_role('Admin'): return True if app.db.query('''ask { ?nanopub np:hasAssertion ?assertion; np:hasPublicationInfo ?info. graph ?info { ?assertion dc:contributor ?user. } }''', initBindings=dict(nanopub=uri, user=current_user.resUri), initNs=dict(np=app.NS.np, dc=app.NS.dc)): print "Is owner." return True return False
def home(): """Home page.""" if current_user.has_role('admin'): organisations = models.Organisation.query else: organisations = [o for o in models.Organisation.query if current_user.has_role(organisation_id=o.id)] if len(organisations) == 1: return redirect(url_for('core.summary', organisation=organisations[0])) return render_template('core/home.html', organisations=organisations)
def home(): """Home page.""" if current_user.has_role('admin'): organisations = models.Organisation.query else: organisations = [ o for o in models.Organisation.query if current_user.has_role(organisation_id=o.id) ] if len(organisations) == 1: return redirect( url_for('core.summary', organisation=organisations[0])) return render_template('core/home.html', organisations=organisations)
def add_user(): password = request.form['password'] confirm = request.form['confirm'] email = request.form['email'] role = request.form['role'] if password == confirm: datastore = current_app.extensions['security'].datastore if datastore.get_user(email) is not None: flash("User %s already exists" % (email), "danger") else: if role != "student": if current_user.has_role("admin"): role = datastore.find_role("admin") user = datastore.create_user( email=email, password=hash_password(password)) datastore.add_role_to_user(user, role) flash("User %s has been created" % (email), "success") else: flash("Only admins can add non-student users", "danger") else: role = datastore.find_role("student") user = datastore.create_user(email=email, password=hash_password(password)) datastore.add_role_to_user(user, role) flash("User %s has been created" % (email), "success") else: flash("Passwords do not match", "danger") return redirect("/view")
def _build_asset_query( owner_id: Optional[int] = None, order_by_asset_attribute: str = "id", order_direction: str = "desc", ) -> Query: """Build an Asset query. Only authenticated users can use this. Admins can query for all assets (owner_id is None) or for any user (the asset's owner). Non-admins can only query for themselves (owner_id is ignored). order_direction can be "asc" or "desc". """ if current_user.is_authenticated: if current_user.has_role(ADMIN_ROLE): if owner_id is not None: if not isinstance(owner_id, int): try: owner_id = int(owner_id) except TypeError: raise Exception( "Owner id %s cannot be parsed as integer, thus seems to be invalid." % owner_id) query = Asset.query.filter(Asset.owner_id == owner_id) else: query = Asset.query else: query = Asset.query.filter_by(owner=current_user) else: query = Asset.query.filter(Asset.owner_id == -1) query = query.order_by( getattr(getattr(Asset, order_by_asset_attribute), order_direction)()) return query
def mock_flex_figure(x_range, x_index, fig_width) -> Figure: df_actions = pd.DataFrame(index=x_index, columns=["event_value"]).fillna(0) next_action_hour4 = get_flex_action_hour(4) if next_action_hour4 in df_actions.index: if current_user.is_authenticated: if current_user.has_role(ADMIN_ROLE): df_actions.loc[next_action_hour4] = -2.4 # mock two actions elif "wind" in current_user.email: df_actions.loc[next_action_hour4] = -1.3 # mock one action elif "charging" in current_user.email: df_actions.loc[next_action_hour4] = -1.1 # mock one action next_action_hour2 = get_flex_action_hour(2) if next_action_hour2 in df_actions.index: if next_action_hour2 < next_action_hour4 and ( current_user.is_authenticated and (current_user.has_role(ADMIN_ROLE) or "wind" in current_user.email or "charging" in current_user.email)): # mock the shift "payback" (actually occurs earlier in our mock example) df_actions.loc[next_action_hour2] = 1.1 next_action_hour9 = get_flex_action_hour(9) if next_action_hour9 in df_actions.index: # mock some other ordered actions that are not in an opportunity hour any more df_actions.loc[next_action_hour9] = 3.5 fig_actions = plotting.create_graph( df_actions, unit="MW", title="Ordered balancing actions", x_range=x_range, y_label="Power (in MW)", ) fig_actions.plot_height = 150 fig_actions.plot_width = fig_width fig_actions.xaxis.visible = False if current_user.is_authenticated and (current_user.has_role(ADMIN_ROLE) or "wind" in current_user.email or "charging" in current_user.email): plotting.highlight( fig_actions, next_action_hour4, next_action_hour4 + timedelta(hours=1), redirect_to="/control", ) return fig_actions
def home(): if current_user.has_role('admin'): users = dbSession.query(User).filter( User.active == True) # need to add filter role return render_template("users.html", company="Admin", users=users) else: return render_template("dashboard.html", company=current_user.company_name)
def _can_edit(self, uri): if self.managed: return True if current_user._get_current_object() is None: # This isn't null even when not authenticated, unless we are an autonomic agent. return True if not hasattr(current_user, 'identifier'): # This is an anonymous user. return False if current_user.has_role('Publisher') or current_user.has_role('Editor') or current_user.has_role('Admin'): return True if self.db.query('''ask { ?nanopub np:hasAssertion ?assertion; np:hasPublicationInfo ?info. graph ?info { ?assertion dc:contributor ?user. } }''', initBindings=dict(nanopub=uri, user=current_user.identifier), initNs=dict(np=self.NS.np, dc=self.NS.dc)): #print "Is owner." return True return False
def can_access_asset(asset: Asset) -> bool: """Return True if the current user is an admin or the owner of the asset:""" if current_user.is_authenticated: if current_user.has_role("admin"): return True if asset.owner == current_user: return True return False
def get(self, article_id): article = NewsArticle.query.get(article_id) if not current_user.has_role(ROLE_FULL_TEXT_ACCESS): article.text = None if article is None: abort(404) return article
def doesUserHaveRole(role): ''' Pulls the user's username from the session Args: role (str): Checks to see if a user has a certain role Returns: boolean: True if user has role, false otherwise ''' if role == "anonymous": return current_user.is_anonymous if current_user.has_role(role): return True return False
def mock_flex_action_in_main_figure(fig_profile: Figure): # show when user has (possible) actions in order book for a time slot if current_user.is_authenticated and (current_user.has_role(ADMIN_ROLE) or "wind" in current_user.email or "charging" in current_user.email): next_action_hour = get_flex_action_hour(4) plotting.highlight( fig_profile, next_action_hour, next_action_hour + timedelta(hours=1), redirect_to="/control", )
def mask_inaccessible_assets( asset_queries: Union[Query, Dict[str, Query]] ) -> Union[Query, Dict[str, Query]]: """Filter out any assets that the user should not be able to access. We do not explicitly check user authentication here, because non-authenticated users are not admins and have no asset ownership, so applying this filter for non-admins masks all assets. """ if not current_user.has_role(ADMIN_ROLE): if isinstance(asset_queries, dict): for name, query in asset_queries.items(): asset_queries[name] = query.filter_by(owner=current_user) else: asset_queries = asset_queries.filter_by(owner=current_user) return asset_queries
def remove_user(): datastore = current_app.extensions['security'].datastore email = request.form['email'] user = datastore.get_user(email) if user.has_role("admin"): if current_user.has_role("admin"): datastore.delete_user(user) flash("User %s has been removed" % (email), "success") else: flash("User %s can only be removed by an admin" % (email), "danger") else: datastore.delete_user(user) flash("User %s has been removed" % (email), "success") return redirect("/view")
def get(self): """Download a corpus of linked news and science""" parser = reqparse.RequestParser() parser.add_argument('offset', default=0, type=int, location='args') parser.add_argument('limit', default=10, type=int, location='args') args = parser.parse_args() q = NewsArticle.query.join(ArticlePaper).filter( NewsArticle.hidden == False, NewsArticle.spam == False).distinct(NewsArticle.id) articles = q.limit(args.limit).offset(args.offset).all() if not current_user.has_role(ROLE_FULL_TEXT_ACCESS): for article in articles: article.text = None return {"total_count": q.count(), "links": articles}
def can_access_asset(asset_or_sensor: Union[Asset, Sensor]) -> bool: """Return True if: - the current user is an admin, or - the current user is the owner of the asset, or - the current user's organisation account owns the corresponding generic asset, or - the corresponding generic asset is public todo: refactor to `def can_access_sensor(sensor: Sensor) -> bool` once `ui.views.state.state_view` stops calling it with an Asset todo: let this function use our new auth model (row-level authorization) todo: deprecate this function in favor of an authz decorator on the API route """ if current_user.is_authenticated: if current_user.has_role(ADMIN_ROLE): return True if isinstance(asset_or_sensor, Sensor): if asset_or_sensor.generic_asset.owner in (None, current_user.account): return True elif asset_or_sensor.owner == current_user: return True return False
def getAuthData(): """ Return relevant information from flask-login current_user""" # is_authenticated # This property should return True if the user is authenticated, i.e. they have provided valid credentials. (Only authenticated users will fulfill the criteria of login_required.) # is_active # This property should return True if this is an active user - in addition to being authenticated, they also have activated their account, not been suspended, or any condition your application has for rejecting an account. Inactive accounts may not log in (without being forced of course). # is_anonymous # This property should return True if this is an anonymous user. (Actual users should return False instead.) is_authenticated = current_user.is_authenticated is_active = current_user.is_active is_anonymous = current_user.is_anonymous if is_anonymous: username = "******" is_admin = False else: username = current_user.email is_admin = current_user.has_role('admin') return {'is_authenticated': is_authenticated,\ 'is_active': is_active,\ 'is_anonymous': is_anonymous,\ 'is_admin': is_admin,\ 'username': username}
def is_accessible(self): return (current_user.is_authenticated() and current_user.has_role('Admin'))
def get(self): parser = reqparse.RequestParser() parser.add_argument('urlfilter', type=str, default="", location='args') parser.add_argument('offset', default=0, type=int, location='args') parser.add_argument('limit', default=10, type=int, location='args') parser.add_argument('hidden', default="false", choices=['true', 'false'], location='args') parser.add_argument('spam', default="false", choices=['true', 'false'], location='args') parser.add_argument('linked', default="false", choices=['true', 'false'], location='args') parser.add_argument('review', default="false", choices=['true', 'false'], location='args') args = parser.parse_args() # use boolean comparisons to convert string "true"/"false" vals into bool type args.hidden = args.hidden == "true" args.spam = args.spam == "true" if current_user.is_authenticated: # query for articles that the current user has seen userlist = db.session.query(ArticlePaper.article_id)\ .filter(ArticlePaper.user_id == current_user.id) else: # query for articles that the current user has seen userlist = db.session.query(ArticlePaper.article_id)\ .filter(ArticlePaper.user_id == None) if current_app.config.get('REVIEW_PROCESS_ENABLED', True): min_iaa_users = current_app.config.get('REVIEW_MIN_IAA', 3) blacklisted_iaa_users = current_app.config.get( 'REVIEW_USER_BLACKLIST', []) else: min_iaa_users = 1 blacklisted_iaa_users = [] # add query for getting articles that have are not passed IAA linked = db.session.query(ArticlePaper.article_id)\ .filter(~ArticlePaper.user_id.in_(blacklisted_iaa_users))\ .group_by(ArticlePaper.article_id)\ .having(and_(func.count(ArticlePaper.user_id.distinct()) > 0, func.count(ArticlePaper.user_id.distinct()) < min_iaa_users)) # query for articles that have been linked and have passed IAA linked_and_reviewed = db.session.query(ArticlePaper.article_id)\ .group_by(ArticlePaper.article_id)\ .having(func.count(ArticlePaper.user_id.distinct()) >= min_iaa_users) # add select filters for hidden and spam states r = NewsArticle.query\ .filter(NewsArticle.hidden == args.hidden)\ .filter(NewsArticle.spam == args.spam) if args.urlfilter != "": r = r.filter(NewsArticle.url.like("%{}%".format(args.urlfilter))) # if linked then show all linked articles that the user is allowed to see if args.linked == "true": r = r.join(ArticlePaper).filter( or_(NewsArticle.do_iaa == False, #and_(NewsArticle.do_iaa == True, NewsArticle.id.in_(linked_and_reviewed.union(userlist))) )).distinct(NewsArticle.id) # deal with review elif args.review == "true": # we want articles that have one or more links but that the user hasn't seen r = r.filter(NewsArticle.do_iaa == True).filter( NewsArticle.id.in_(linked)).filter( ~NewsArticle.id.in_(userlist)) # default case -show 'new' articles that need to be tagged - news has no ArticlePapers else: r = r.filter( ~NewsArticle.id.in_(select([ArticlePaper.article_id]))) articles = r.offset(args.offset).limit(min(args.limit, 100)).all() if not current_user.has_role(ROLE_FULL_TEXT_ACCESS): for article in articles: article.text = None return {"total_count": r.count(), "articles": articles}
def render_flexmeasures_template(html_filename: str, **variables): """Render template and add all expected template variables, plus the ones given as **variables.""" variables["documentation_exists"] = False if os.path.exists( "%s/static/documentation/html/index.html" % flexmeasures_ui.root_path ): variables["documentation_exists"] = True variables["show_queues"] = False if current_user.is_authenticated: if ( current_user.has_role(ADMIN_ROLE) or current_app.config.get("FLEXMEASURES_MODE", "") == "demo" ): variables["show_queues"] = True variables["start_time"] = time_utils.get_default_start_time() if "start_time" in session: variables["start_time"] = session["start_time"] variables["end_time"] = time_utils.get_default_end_time() if "end_time" in session: variables["end_time"] = session["end_time"] variables["page"] = html_filename.split("/")[-1].replace(".html", "") if "show_datepicker" not in variables: variables["show_datepicker"] = variables["page"] in ("analytics", "portfolio") variables["contains_plots"] = False if any([n.endswith(("plots_div", "plots_divs")) for n in variables.keys()]): variables["contains_plots"] = True variables["bokeh_css_resources"] = CDN.render_css() variables["bokeh_js_resources"] = CDN.render_js() variables["resolution"] = session.get("resolution", "") variables["resolution_human"] = time_utils.freq_label_to_human_readable_label( session.get("resolution", "") ) variables["horizon_human"] = time_utils.freq_label_to_human_readable_label( session.get("forecast_horizon", "") ) variables["flexmeasures_version"] = flexmeasures_version ( variables["git_version"], variables["git_commits_since"], variables["git_hash"], ) = get_git_description() app_start_time = current_app.config.get("START_TIME") variables["app_running_since"] = time_utils.naturalized_datetime_str(app_start_time) variables["loaded_plugins"] = ", ".join( f"{p_name} (v{p_version})" for p_name, p_version in current_app.config.get("LOADED_PLUGINS", {}).items() ) variables["user_is_logged_in"] = current_user.is_authenticated variables[ "user_is_admin" ] = current_user.is_authenticated and current_user.has_role(ADMIN_ROLE) variables[ "user_is_anonymous" ] = current_user.is_authenticated and current_user.has_role("anonymous") variables["user_email"] = current_user.is_authenticated and current_user.email or "" variables["user_name"] = ( current_user.is_authenticated and current_user.username or "" ) variables["js_versions"] = current_app.config.get("FLEXMEASURES_JS_VERSIONS") variables["chart_options"] = json.dumps(chart_options) variables["menu_logo"] = current_app.config.get("FLEXMEASURES_MENU_LOGO_PATH") variables["extra_css"] = current_app.config.get("FLEXMEASURES_EXTRA_CSS_PATH") return render_template(html_filename, **variables)
def filter_non_org_admins(*args, **kwargs): organisation = kwargs.get('organisation') if not (current_user.has_role('admin') or current_user.has_role(organisation_id=organisation.id)): return abort(401) return func(*args, **kwargs)
def portfolio_view(): # noqa: C901 """Portfolio view. By default, this page shows live results (production, consumption and market data) from the user's portfolio. Time windows for which the platform has identified upcoming balancing opportunities are highlighted. The page can also be used to navigate historical results. """ set_time_range_for_session() start = session.get("start_time") end = session.get("end_time") resolution = session.get("resolution") # Get plot perspective perspectives = ["production", "consumption"] default_stack_side = "production" # todo: move to user config setting show_stacked = request.values.get("show_stacked", default_stack_side) perspectives.remove(show_stacked) show_summed: str = perspectives[0] plot_label = f"Stacked {show_stacked} vs aggregated {show_summed}" # Get structure and data assets: List[Asset] = get_assets( order_by_asset_attribute="display_name", order_direction="asc" ) represented_asset_types, markets, resource_dict = get_structure(assets) for resource_name, resource in resource_dict.items(): resource.load_sensor_data( [Power, Price], start=start, end=end, resolution=resolution, exclude_source_types=["scheduling script"], ) # The resource caches the results ( supply_resources_df_dict, demand_resources_df_dict, production_per_asset_type, consumption_per_asset_type, production_per_asset, consumption_per_asset, ) = get_power_data(resource_dict) price_bdf_dict, average_price_dict = get_price_data(resource_dict) # Pick a perspective for summing and for stacking sum_dict = ( demand_resources_df_dict.values() if show_summed == "consumption" else supply_resources_df_dict.values() ) power_sum_df = ( pd.concat(sum_dict, axis=1).sum(axis=1).to_frame(name="event_value") if sum_dict else pd.DataFrame() ) stack_dict = ( rename_event_value_column_to_resource_name(supply_resources_df_dict).values() if show_summed == "consumption" else rename_event_value_column_to_resource_name( demand_resources_df_dict ).values() ) df_stacked_data = pd.concat(stack_dict, axis=1) if stack_dict else pd.DataFrame() # Create summed plot power_sum_df = data_or_zeroes(power_sum_df, start, end, resolution) x_range = plotting.make_range( pd.date_range(start, end, freq=resolution, closed="left") ) fig_profile = plotting.create_graph( power_sum_df, unit="MW", title=plot_label, x_range=x_range, x_label="Time (resolution of %s)" % time_utils.freq_label_to_human_readable_label(resolution), y_label="Power (in MW)", legend_location="top_right", legend_labels=(capitalize(show_summed), None, None), show_y_floats=True, non_negative_only=True, ) fig_profile.plot_height = 450 fig_profile.plot_width = 900 # Create stacked plot df_stacked_data = data_or_zeroes(df_stacked_data, start, end, resolution) df_stacked_areas = stack_df(df_stacked_data) num_areas = df_stacked_areas.shape[1] if num_areas <= 2: colors = ["#99d594", "#dddd9d"] else: colors = palettes.brewer["Spectral"][num_areas] df_stacked_data = time_utils.tz_index_naively(df_stacked_data) x_points = np.hstack((df_stacked_data.index[::-1], df_stacked_data.index)) fig_profile.grid.minor_grid_line_color = "#eeeeee" for a, area in enumerate(df_stacked_areas): fig_profile.patch( x_points, df_stacked_areas[area].values, color=colors[a], alpha=0.8, line_color=None, legend=df_stacked_data.columns[a], level="underlay", ) # Flexibility numbers are mocked for now curtailment_per_asset = {a.name: 0 for a in assets} shifting_per_asset = {a.name: 0 for a in assets} profit_loss_flexibility_per_asset = {a.name: 0 for a in assets} curtailment_per_asset_type = {k: 0 for k in represented_asset_types.keys()} shifting_per_asset_type = {k: 0 for k in represented_asset_types.keys()} profit_loss_flexibility_per_asset_type = { k: 0 for k in represented_asset_types.keys() } shifting_per_asset["48_r"] = 1.1 profit_loss_flexibility_per_asset["48_r"] = 76000 shifting_per_asset_type["one-way EVSE"] = shifting_per_asset["48_r"] profit_loss_flexibility_per_asset_type[ "one-way EVSE" ] = profit_loss_flexibility_per_asset["48_r"] curtailment_per_asset["hw-onshore"] = 1.3 profit_loss_flexibility_per_asset["hw-onshore"] = 84000 curtailment_per_asset_type["wind turbines"] = curtailment_per_asset["hw-onshore"] profit_loss_flexibility_per_asset_type[ "wind turbines" ] = profit_loss_flexibility_per_asset["hw-onshore"] # Add referral to mocked control action this_hour = time_utils.get_most_recent_hour() next4am = [ dt for dt in [this_hour + timedelta(hours=i) for i in range(1, 25)] if dt.hour == 4 ][0] # TODO: show when user has (possible) actions in order book for a time slot if current_user.is_authenticated and ( current_user.has_role("admin") or "wind" in current_user.email or "charging" in current_user.email ): plotting.highlight( fig_profile, next4am, next4am + timedelta(hours=1), redirect_to="/control" ) # actions df_actions = pd.DataFrame(index=power_sum_df.index, columns=["event_value"]).fillna( 0 ) if next4am in df_actions.index: if current_user.is_authenticated: if current_user.has_role("admin"): df_actions.loc[next4am] = -2.4 # mock two actions elif "wind" in current_user.email: df_actions.loc[next4am] = -1.3 # mock one action elif "charging" in current_user.email: df_actions.loc[next4am] = -1.1 # mock one action next2am = [ dt for dt in [this_hour + timedelta(hours=i) for i in range(1, 25)] if dt.hour == 2 ][0] if next2am in df_actions.index: if next2am < next4am and ( current_user.is_authenticated and ( current_user.has_role("admin") or "wind" in current_user.email or "charging" in current_user.email ) ): # mock the shift "payback" (actually occurs earlier in our mock example) df_actions.loc[next2am] = 1.1 next9am = [ dt for dt in [this_hour + timedelta(hours=i) for i in range(1, 25)] if dt.hour == 9 ][0] if next9am in df_actions.index: # mock some other ordered actions that are not in an opportunity hour anymore df_actions.loc[next9am] = 3.5 fig_actions = plotting.create_graph( df_actions, unit="MW", title="Ordered balancing actions", x_range=x_range, y_label="Power (in MW)", ) fig_actions.plot_height = 150 fig_actions.plot_width = fig_profile.plot_width fig_actions.xaxis.visible = False if current_user.is_authenticated and ( current_user.has_role("admin") or "wind" in current_user.email or "charging" in current_user.email ): plotting.highlight( fig_actions, next4am, next4am + timedelta(hours=1), redirect_to="/control" ) portfolio_plots_script, portfolio_plots_divs = components( (fig_profile, fig_actions) ) next24hours = [ (time_utils.get_most_recent_hour() + timedelta(hours=i)).strftime("%I:00 %p") for i in range(1, 26) ] return render_flexmeasures_template( "views/portfolio.html", assets=assets, average_prices=average_price_dict, asset_types=represented_asset_types, markets=markets, production_per_asset=production_per_asset, consumption_per_asset=consumption_per_asset, curtailment_per_asset=curtailment_per_asset, shifting_per_asset=shifting_per_asset, profit_loss_flexibility_per_asset=profit_loss_flexibility_per_asset, production_per_asset_type=production_per_asset_type, consumption_per_asset_type=consumption_per_asset_type, curtailment_per_asset_type=curtailment_per_asset_type, shifting_per_asset_type=shifting_per_asset_type, profit_loss_flexibility_per_asset_type=profit_loss_flexibility_per_asset_type, sum_production=sum(production_per_asset_type.values()), sum_consumption=sum(consumption_per_asset_type.values()), sum_curtailment=sum(curtailment_per_asset_type.values()), sum_shifting=sum(shifting_per_asset_type.values()), sum_profit_loss_flexibility=sum( profit_loss_flexibility_per_asset_type.values() ), portfolio_plots_script=portfolio_plots_script, portfolio_plots_divs=portfolio_plots_divs, next24hours=next24hours, alt_stacking=show_summed, )
def filter_non_org_admins(*args, **kwargs): organisation = kwargs.get('organisation') if not (current_user.has_role('admin') or current_user.has_role(organisation_id=organisation.id)): return abort(401) return func(*args, **kwargs)
def is_accessible(self): app.logger.debug('Auth admin : %s' % (current_user.roles)) return current_user.is_authenticated and current_user.has_role('admin')
def is_accessible(self): return current_user.has_role('admin')