Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

validate that user can set the account on an asset #488

Merged
merged 5 commits into from Aug 26, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 21 additions & 0 deletions flexmeasures/api/v3_0/tests/test_assets_api.py
Expand Up @@ -212,6 +212,27 @@ def test_post_an_asset_with_existing_name(client, setup_api_test_data):
)


def test_post_an_asset_with_other_account(client, setup_api_test_data):
"""Catch auth error, when account-admin posts an asset for another account"""
with UserContext("test_prosumer_user_2@seita.nl") as account_admin_user:
auth_token = account_admin_user.get_auth_token()
with AccountContext("Test Supplier Account") as supplier:
supplier_id = supplier.id
post_data = get_asset_post_data()
post_data["account_id"] = supplier_id
asset_creation_response = client.post(
url_for("AssetAPI:post"),
json=post_data,
headers={"content-type": "application/json", "Authorization": auth_token},
)
print(f"Creation Response: {asset_creation_response.json}")
assert asset_creation_response.status_code == 422
assert (
"not allowed to create assets for this account"
in asset_creation_response.json["message"]["json"]["account_id"][0]
)


def test_post_an_asset_with_nonexisting_field(client, setup_api_test_data):
"""Posting a field that is unexpected leads to a 422"""
with UserContext("test_admin_user@seita.nl") as prosumer:
Expand Down
4 changes: 2 additions & 2 deletions flexmeasures/cli/data_show.py
Expand Up @@ -109,7 +109,7 @@ def show_account(account):
user.username,
user.email,
naturaltime(user.last_login_at),
"".join([role.name for role in user.roles]),
",".join([role.name for role in user.roles]),
)
for user in users
]
Expand Down Expand Up @@ -187,7 +187,7 @@ def show_generic_asset(asset):
sensor.unit,
naturaldelta(sensor.event_resolution),
sensor.timezone,
"".join([f"{k}:{v}\n" for k, v in sensor.attributes.items()]),
",".join([f"{k}:{v}\n" for k, v in sensor.attributes.items()]),
)
for sensor in sensors
]
Expand Down
9 changes: 9 additions & 0 deletions flexmeasures/data/schemas/generic_assets.py
Expand Up @@ -2,6 +2,7 @@
import json

from marshmallow import validates, validates_schema, ValidationError, fields
from flask_security import current_user

from flexmeasures.data import ma
from flexmeasures.data.models.user import Account
Expand All @@ -11,6 +12,7 @@
MarshmallowClickMixin,
with_appcontext_if_needed,
)
from flexmeasures.auth.policy import user_has_admin_access


class JSON(fields.Field):
Expand Down Expand Up @@ -66,6 +68,13 @@ def validate_account(self, account_id: int):
account = Account.query.get(account_id)
if not account:
raise ValidationError(f"Account with Id {account_id} doesn't exist.")
if (
not user_has_admin_access(current_user, "update")
and account_id != current_user.account_id
):
raise ValidationError(
"User is not allowed to create assets for this account."
)

@validates("latitude")
def validate_latitude(self, latitude: Optional[float]):
Expand Down
19 changes: 16 additions & 3 deletions flexmeasures/ui/crud/assets.py
Expand Up @@ -12,6 +12,7 @@

from flexmeasures.data import db
from flexmeasures.auth.error_handling import unauthorized_handler
from flexmeasures.auth.policy import check_access
from flexmeasures.data.models.generic_assets import (
GenericAssetType,
GenericAsset,
Expand Down Expand Up @@ -48,7 +49,7 @@ class AssetForm(FlaskForm):
places=4,
render_kw={"placeholder": "--Click the map or enter a longitude--"},
)
attributes = StringField("Other attributes (JSON)")
attributes = StringField("Other attributes (JSON)", default="{}")

def validate_on_submit(self):
if (
Expand Down Expand Up @@ -148,6 +149,15 @@ def expunge_asset():
return asset_data


def user_can_create_assets() -> bool:
try:
check_access(current_user.account, "create-children")
except Exception as exc:
current_app.logger.error(exc)
nhoening marked this conversation as resolved.
Show resolved Hide resolved
return False
return True


class AssetCrudUI(FlaskView):
"""
These views help us offer a Jinja2-based UI.
Expand Down Expand Up @@ -186,7 +196,10 @@ def get_asset_by_account(account_id) -> List[GenericAsset]:
assets = get_asset_by_account(current_user.account_id)

return render_flexmeasures_template(
"crud/assets.html", assets=assets, message=msg
"crud/assets.html",
nhoening marked this conversation as resolved.
Show resolved Hide resolved
assets=assets,
message=msg,
user_can_create_assets=user_can_create_assets(),
)

@login_required
Expand Down Expand Up @@ -218,7 +231,7 @@ def get(self, id: str):
"""GET from /assets/<id> where id can be 'new' (and thus the form for asset creation is shown)"""

if id == "new":
if not current_user.has_role("admin"):
if not user_can_create_assets():
return unauthorized_handler(None, [])

asset_form = with_options(NewAssetForm())
Expand Down
2 changes: 1 addition & 1 deletion flexmeasures/ui/templates/crud/assets.html
Expand Up @@ -20,7 +20,7 @@ <h3>Asset overview</h3>
<th class="text-right">Account</th>
<th class="text-right no-sort">Sensors</th>
<th class="text-right no-sort">
{% if user_is_admin %}
{% if user_can_create_assets %}
<form action="/assets/new" method="get">
<button class="btn btn-sm btn-responsive btn-success create-button" type="submit">Create new
asset</button>
Expand Down