Skip to content

Commit

Permalink
Add prefix creation function
Browse files Browse the repository at this point in the history
Changes to be committed:
	modified:   authentication/services.py
	modified:   biocompute/models.py
	modified:   config/settings.py
	modified:   docs/refactor.md
	modified:   prefix/apis.py
	modified:   prefix/models.py
	modified:   prefix/services.py
	modified:   tests/test_views/test_api_objects_drafts_create.py
  • Loading branch information
HadleyKing committed Mar 26, 2024
1 parent 2530f7d commit bce794b
Show file tree
Hide file tree
Showing 8 changed files with 55 additions and 59 deletions.
1 change: 0 additions & 1 deletion authentication/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,6 @@ def create_bcodb_user(email: str) -> User:

return user


def send_bcodb(data: str, request_info: dict):
"""
"""
Expand Down
1 change: 1 addition & 0 deletions biocompute/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ class Bco(models.Model):
prefix = models.ForeignKey(Prefix, on_delete=models.CASCADE, to_field="prefix")
owner = models.ForeignKey(
User,
to_field="username",
on_delete=models.CASCADE,
related_name="owned_bcos"
)
Expand Down
7 changes: 0 additions & 7 deletions config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,18 +123,13 @@
},
]

# Object-level permissions with django-guardian
# Source: https://github.com/django-guardian/django-guardian#configuration
AUTHENTICATION_BACKENDS = [
"django.contrib.auth.backends.ModelBackend",
"guardian.backends.ObjectPermissionBackend",
]

# --- APPLICATION --- #
# Application definition

# Token-based authentication.
# Source: https://www.django-rest-framework.org/api-guide/authentication/#tokenau thentication
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.admindocs",
Expand All @@ -150,8 +145,6 @@
'rest_framework_jwt.blacklist',
"rest_framework_swagger",
"reset_migrations",
"guardian",
# "api",
"authentication",
"biocompute",
"prefix"
Expand Down
13 changes: 13 additions & 0 deletions docs/refactor.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@
### Refactor the BCO permission system
- same situation as prefix

## Permissions

- BCO has `owner`, `auth_group` and `auth_user`
- Prefix has `owner`, and `auth_group`

## Items to look at later
- `authentication.apis.RegisterUserNoVerificationAPI` has no swagger or tests
- fix email and secrets
Expand All @@ -40,3 +45,11 @@
- unwanted swagger endpoints
- need tests for token
- prefix api documentation and portal docs for prefix

Prefix Perms:
add -> create new DRAFT
edit -> Change existing Draft
delete -> Delete Draft
publish -> Publish Draft
view -> View/download
ONLY if private
13 changes: 9 additions & 4 deletions prefix/apis.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,15 @@
description="A description of what this prefix should represent. For example, the prefix 'GLY' would be related to BCOs which were derived from GlyGen workflows.",
example="Test prefix description."
),
"authorized_groups": openapi.Schema(
type=openapi.TYPE_ARRAY,
description="Groups which can access the BCOs using this prefix. If it is none then anyone can access.",
items=openapi.Schema(type=openapi.TYPE_STRING, example="")
"certifying_key": openapi.Schema(
type=openapi.TYPE_STRING,
description="Hash of server and date-time of creation.",
example="12345678910"
),
"public": openapi.Schema(
type=openapi.TYPE_BOOLEAN,
description="Flag to set permissions.",
example=True
)
},
)
Expand Down
5 changes: 0 additions & 5 deletions prefix/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,6 @@ class Prefix(models.Model):
on_delete=models.CASCADE,
to_field="username"
)
authorized_groups = models.ManyToManyField(
Group,
blank=True,
related_name='authorized_prefix'
)
counter = models.IntegerField(
default=0,
help_text="Counter for object_id asignment"
Expand Down
66 changes: 28 additions & 38 deletions prefix/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import re
from urllib.parse import urlparse
from django.conf import settings
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from prefix.models import Prefix
from django.db import transaction
Expand All @@ -20,6 +22,7 @@ class PrefixSerializer(serializers.Serializer):
prefix = serializers.CharField(min_length=3, max_length=5)
description = serializers.CharField()
authorized_groups = serializers.ListField(child=serializers.CharField(allow_blank=True), required=False)
public = serializers.BooleanField(required=False)

def validate(self, attrs):
"""Prefix Validator
Expand All @@ -41,65 +44,52 @@ def validate(self, attrs):
if "create" in request.path_info:
pass
else:
errors["prefix_name"] = f"That Prefix, {prefix_name}, was not found."



# remove blank 'authorized_groups' relic from legacy conversion
if attrs['authorized_groups'][0] == "":
attrs.pop("authorized_groups")

#check for groups
if 'authorized_groups' in attrs:
for group in attrs['authorized_groups']:
try:
Group.objects.get(name=group)
except Group.DoesNotExist as err:
errors['authorized_groups'] = f"Invalid group: {group}"

# If erros exist than raise and exception and return it, otherwise
# return validated data
if errors:
raise serializers.ValidationError(errors)
raise serializers.ValidationError({"prefix_name": f"That Prefix, {prefix_name}, was not found."})

return attrs

@transaction.atomic
def create(self, validated_data):
"""Create function for Prefix
"""
authorized_group_names = validated_data.pop('authorized_groups', [])
public = validated_data.pop('public', [])
import pdb; pdb.set_trace()
prefix_instance = Prefix.objects.create(**validated_data, created=timezone.now())
# Set ManyToMany relations
if authorized_group_names:
authorized_groups = Group.objects.filter(name__in=authorized_group_names)
prefix_instance.authorized_groups.set(authorized_groups)

return prefix_instance

@transaction.atomic
def update(self, validated_data):
"""Update function for Prefix."""
prefix_instance = Prefix.objects.get(prefix=validated_data['prefix'])
if prefix_instance.owner != validated_data['owner']:
# import pdb; pdb.set_trace()
return "denied"
prefix_instance.description = validated_data.get('description', prefix_instance.description)
prefix_instance.save()

if 'authorized_groups' in validated_data:
authorized_group_names = validated_data['authorized_groups']
# If the list is empty or contains only an empty string, clear the groups
if not authorized_group_names or authorized_group_names == [""]:
prefix_instance.authorized_groups.clear()
return prefix_instance

else:
# Filter groups that exist in the database
authorized_groups = Group.objects.filter(name__in=authorized_group_names)

# Set the new groups, which automatically handles adding, keeping, or removing
prefix_instance.authorized_groups.set(authorized_groups)
def create_permissions_for_prefix(instance=None, owner=User):
"""Prefix Permission Creation
return prefix_instance
Creates permissions for a Prefix if it is not public. Owner is assigned
all permissions and then can add permissions to other users.
'view' -> View/download Prefix drafts
'add' -> create new drafts for Prefix
'change' -> Change existing drafts for Prefix
'delete' -> Delete drafts for Prefix
'publish' -> Publish drafts for Prefix
"""
try:
for perm in [ "view", "add", "change", "delete", "publish"]:
print(instance)
Permission.objects.create(
name="Can " + perm + " BCOs with prefix " + instance.prefix,
content_type=ContentType.objects.get(app_label="api", model="bco"),
codename=perm + "_" + instance.prefix,)
except:
return 0

def prefix_counter_increment(prefix: Prefix) -> int:
"""Prefix Counter Increment
Expand Down
8 changes: 4 additions & 4 deletions tests/test_views/test_api_objects_drafts_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@ def setUp(self):
"prefix": "BCO",
"authorized_users": ["hivelab"],
"contents": {
"object_id": "https://test.portal.biochemistry.gwu.edu/BCO_000001/DRAFT",
"spec_version": "https://w3id.org/ieee/ieee-2791-schema/2791object.json",
"etag": "11ee4c3b8a04ad16dcca19a6f478c0870d3fe668ed6454096ab7165deb1ab8ea"
}
"object_id": "https://test.portal.biochemistry.gwu.edu/BCO_000001/DRAFT",
"spec_version": "https://w3id.org/ieee/ieee-2791-schema/2791object.json",
"etag": "11ee4c3b8a04ad16dcca19a6f478c0870d3fe668ed6454096ab7165deb1ab8ea"
}
},
{
"object_id": "http://127.0.0.1:8000/TEST_000001",
Expand Down

0 comments on commit bce794b

Please sign in to comment.