Skip to content

Commit

Permalink
Merge pull request #485 from syucream/feature/format-with-black
Browse files Browse the repository at this point in the history
Auto-format with black
  • Loading branch information
hinashi authored Apr 28, 2022
2 parents 8667486 + 352e422 commit 8fb1db4
Show file tree
Hide file tree
Showing 166 changed files with 16,569 additions and 12,108 deletions.
6 changes: 5 additions & 1 deletion .flake8
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
[flake8]
max-line-length = 100
ignore = E203,W503
exclude =
./.git,
./venv,
./.venv,
./.tox,
./*/migrations,
.manage.py
.manage.py,
./node_modules,
per-file-ignores =
./airone/tests/test_elasticsearch.py:E501
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ user@hostname:~$ cd airone
user@hostname:~/airone$ virtualenv -p python3 virtualenv
user@hostname:~/airone$ source virtualenv/bin/activate
(virtualenv) user@hostname:~/airone$ sudo pip install -r requirements.txt
# or, during development
(virtualenv) user@hostname:~/airone$ sudo pip install -r requirements-dev.txt
```

### Setting-up MySQL configuration
Expand Down Expand Up @@ -335,6 +337,13 @@ $ source .venv/bin/activate
$ python manage.py runserver
```

## Auto-format

```
$ source .venv/bin/activate
$ black .
```

## [Experimental] Build the new UI with React

`/new-ui/` serves React-based new UI. Before you try it, you need to build `main.js`:
Expand Down
2 changes: 1 addition & 1 deletion acl/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
default_app_config = 'acl.apps.AclConfig'
default_app_config = "acl.apps.AclConfig"
86 changes: 55 additions & 31 deletions acl/api_v2/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,25 @@


class ACLSerializer(serializers.ModelSerializer):
parent = serializers.SerializerMethodField(method_name='get_parent', read_only=True)
acltypes = serializers.SerializerMethodField(method_name='get_acltypes', read_only=True)
members = serializers.SerializerMethodField(method_name='get_members', read_only=True)
parent = serializers.SerializerMethodField(method_name="get_parent", read_only=True)
acltypes = serializers.SerializerMethodField(method_name="get_acltypes", read_only=True)
members = serializers.SerializerMethodField(method_name="get_members", read_only=True)
# TODO better name?
acl = serializers.ListField(write_only=True)

class Meta:
model = ACLBase
fields = ['id', 'name', 'is_public', 'default_permission', 'objtype', 'parent', 'acltypes',
'members', 'acl']
fields = [
"id",
"name",
"is_public",
"default_permission",
"objtype",
"parent",
"acltypes",
"members",
"acl",
]

def get_parent(self, obj: ACLBase) -> Optional[Any]:
if isinstance(obj, Attribute):
Expand All @@ -31,7 +40,7 @@ def get_parent(self, obj: ACLBase) -> Optional[Any]:
return None

def get_acltypes(self, obj: ACLBase) -> List[Dict[str, Any]]:
return [{'id': x.id, 'name': x.label} for x in ACLType.all()]
return [{"id": x.id, "name": x.label} for x in ACLType.all()]

def get_members(self, obj: ACLBase) -> List[Dict[str, Any]]:
# get ACLTypeID of target_obj if a permission is set
Expand All @@ -42,42 +51,57 @@ def get_current_permission(member):
else:
return 0

return [{'id': x.id,
'name': x.username,
'current_permission': get_current_permission(x),
'type': 'user'} for x in User.objects.filter(is_active=True)] + \
[{'id': x.id,
'name': x.name,
'current_permission': get_current_permission(x),
'type': 'group'} for x in Group.objects.filter(is_active=True)]
return [
{
"id": x.id,
"name": x.username,
"current_permission": get_current_permission(x),
"type": "user",
}
for x in User.objects.filter(is_active=True)
] + [
{
"id": x.id,
"name": x.name,
"current_permission": get_current_permission(x),
"type": "group",
}
for x in Group.objects.filter(is_active=True)
]

def validate_default_permission(self, default_permission: int):
return default_permission in ACLType.all()

def validate(self, attrs: Dict[str, Any]):
user = User.objects.get(id=self.context['request'].user.id)
if not user.may_permitted(self.instance, ACLType.Full, **{
'is_public': attrs['is_public'],
'default_permission': attrs['default_permission'],
'acl_settings': attrs['acl']
}):
raise ValidationError("Inadmissible setting."
"By this change you will never change this ACL")
user = User.objects.get(id=self.context["request"].user.id)
if not user.may_permitted(
self.instance,
ACLType.Full,
**{
"is_public": attrs["is_public"],
"default_permission": attrs["default_permission"],
"acl_settings": attrs["acl"],
}
):
raise ValidationError(
"Inadmissible setting." "By this change you will never change this ACL"
)
return attrs

def update(self, instance, validated_data):
acl_obj = getattr(self._get_acl_model(validated_data['objtype']),
'objects').get(id=instance.id)
acl_obj.is_public = validated_data['is_public']
acl_obj.default_permission = validated_data['default_permission']
acl_obj = getattr(self._get_acl_model(validated_data["objtype"]), "objects").get(
id=instance.id
)
acl_obj.is_public = validated_data["is_public"]
acl_obj.default_permission = validated_data["default_permission"]
acl_obj.save()

for item in [x for x in validated_data['acl'] if x['value']]:
if item['member_type'] == 'user':
member = User.objects.get(id=item['member_id'])
for item in [x for x in validated_data["acl"] if x["value"]]:
if item["member_type"] == "user":
member = User.objects.get(id=item["member_id"])
else:
member = Group.objects.get(id=item['member_id'])
acl_type = [x for x in ACLType.all() if x == int(item['value'])][0]
member = Group.objects.get(id=item["member_id"])
acl_type = [x for x in ACLType.all() if x == int(item["value"])][0]

# update permissios for the target ACLBased object
self._set_permission(member, acl_obj, acl_type)
Expand Down
5 changes: 4 additions & 1 deletion acl/api_v2/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,8 @@
from acl.api_v2 import views

urlpatterns = [
url(r'^acls/(?P<pk>\d+)$', views.ACLAPI.as_view({'get': 'retrieve', 'put': 'update'})),
url(
r"^acls/(?P<pk>\d+)$",
views.ACLAPI.as_view({"get": "retrieve", "put": "update"}),
),
]
4 changes: 1 addition & 3 deletions acl/api_v2/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ def has_object_permission(self, request, view, obj):
return True


class ACLAPI(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
viewsets.GenericViewSet):
class ACLAPI(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet):
queryset = ACLBase.objects.all()
serializer_class = ACLSerializer

Expand Down
4 changes: 2 additions & 2 deletions acl/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@


class AclConfig(AppConfig):
name = 'acl'
name = "acl"

def ready(self):
from . import signals # noqa
from . import signals # noqa
39 changes: 22 additions & 17 deletions acl/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@
def _get_acltype(permission):
if not any([permission.name == x.name for x in ACLType.all()]):
return 0
return int(permission.codename.split('.')[-1])
return int(permission.codename.split(".")[-1])


def _get_objid(permission):
if not any([permission.name == x.name for x in ACLType.all()]):
return 0
return int(permission.codename.split('.')[0])
return int(permission.codename.split(".")[0])


Permission.get_aclid = lambda self: _get_acltype(self)
Expand All @@ -44,28 +44,31 @@ class ACLBase(models.Model):

def set_status(self, val):
self.status |= val
self.save(update_fields=['status'])
self.save(update_fields=["status"])

def del_status(self, val):
self.status &= ~val
self.save(update_fields=['status'])
self.save(update_fields=["status"])

def get_status(self, val):
return self.status & val

def delete(self, *args, **kwargs):
self.is_active = False
self.name = "%s_deleted_%s" % (self.name, datetime.now().strftime("%Y%m%d_%H%M%S"))
self.name = "%s_deleted_%s" % (
self.name,
datetime.now().strftime("%Y%m%d_%H%M%S"),
)
self.save()

def restore(self, *args, **kwargs):
self.is_active = True
self.name = re.sub(r'_deleted_[0-9_]*$', '', self.name)
self.name = re.sub(r"_deleted_[0-9_]*$", "", self.name)
self.save()

def inherit_acl(self, aclobj):
if not isinstance(aclobj, ACLBase):
raise TypeError('specified object(%s) is not ACLBase object')
raise TypeError("specified object(%s) is not ACLBase object")

# inherit parameter of ACL
self.is_public = aclobj.is_public
Expand All @@ -89,30 +92,32 @@ def _get_permission(self, acltype):
def get_subclass_object(self):
# Use importlib to prevent circular import
if self.objtype == ACLObjType.Entity:
model = importlib.import_module('entity.models').Entity
model = importlib.import_module("entity.models").Entity
elif self.objtype == ACLObjType.EntityAttr:
model = importlib.import_module('entity.models').EntityAttr
model = importlib.import_module("entity.models").EntityAttr
elif self.objtype == ACLObjType.Entry:
model = importlib.import_module('entry.models').Entry
model = importlib.import_module("entry.models").Entry
elif self.objtype == ACLObjType.EntryAttr:
model = importlib.import_module('entry.models').Attribute
model = importlib.import_module("entry.models").Attribute
else:
# set ACLBase model
model = type(self)

return model.objects.get(id=self.id)

def is_same_object(self, comp):
return all([self[x] == comp[x] for x in self._IMPORT_INFO['header']])
return all([self[x] == comp[x] for x in self._IMPORT_INFO["header"]])

@classmethod
def search(kls, query):
results = []
for obj in kls.objects.filter(name__icontains=query):
results.append({
'type': kls.__name__,
'object': obj,
'hint': '',
})
results.append(
{
"type": kls.__name__,
"object": obj,
"hint": "",
}
)

return results
2 changes: 1 addition & 1 deletion acl/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
def create_permission(instance):
content_type = ContentType.objects.get_for_model(instance)
for acltype in ACLType.availables():
codename = '%s.%s' % (instance.id, acltype.id)
codename = "%s.%s" % (instance.id, acltype.id)
Permission(name=acltype.name, codename=codename, content_type=content_type).save()


Expand Down
Loading

0 comments on commit 8fb1db4

Please sign in to comment.