Almos finished permissions gui

This commit is contained in:
Adolfo Gómez García 2015-03-04 12:07:22 +01:00
parent 5bde71b117
commit 6387629e7e
6 changed files with 142 additions and 24 deletions

View File

@ -55,13 +55,61 @@ class Permissions(Handler):
''' '''
needs_admin = True needs_admin = True
@staticmethod
def getClass(arg):
cls = {
'providers': Provider,
'service': Service,
'authenticators': Authenticator,
'osmanagers': OSManager,
'transports': Transport,
'networks': Network,
'servicespools': ServicesPool
}.get(arg, None)
if cls is None:
raise RequestError('Invalid request')
return cls
@staticmethod
def permsToDict(perms):
res = []
for perm in perms:
if perm.user is None:
kind = 'group'
entity = perm.group
else:
kind = 'user'
entity = perm.user
res.append({
'type': kind,
'auth': entity.manager.uuid,
'auth_name': entity.manager.name,
'id': entity.uuid,
'name': entity.name,
'perm': perm.permission,
'perm_name': perm.permission_as_string
})
return sorted(res, key=lambda v: v['auth_name'] + v['name'])
def get(self): def get(self):
''' '''
Processes get requests Processes get requests
''' '''
logger.debug("Permissions args for GET: {0}".format(self._args)) logger.debug("Permissions args for GET: {0}".format(self._args))
return '' if len(self._args) != 2:
raise RequestError('Invalid request')
cls = Permissions.getClass(self._args[0])
obj = cls.objects.get(uuid=self._args[1])
perms = permissions.getPermissions(obj)
return Permissions.permsToDict(perms)
def put(self): def put(self):
''' '''
@ -78,13 +126,7 @@ class Permissions(Handler):
'2': permissions.PERMISSION_ALL '2': permissions.PERMISSION_ALL
}.get(self._params.get('perm', '0'), permissions.PERMISSION_NONE) }.get(self._params.get('perm', '0'), permissions.PERMISSION_NONE)
cls = { cls = Permissions.getClass(self._args[0])
'providers': Provider,
'service': Service
}.get(self._args[0], None)
if cls is None:
raise RequestError('Invalid request')
obj = cls.objects.get(uuid=self._args[1]) obj = cls.objects.get(uuid=self._args[1])
@ -93,8 +135,8 @@ class Permissions(Handler):
permissions.addUserPermission(user, obj, perm) permissions.addUserPermission(user, obj, perm)
elif self._args[2] == 'groups': elif self._args[2] == 'groups':
group = Group.objects.get(uuid=self._args[3]) group = Group.objects.get(uuid=self._args[3])
permissions.addUserPermission(group, obj, perm) permissions.addGroupPermission(group, obj, perm)
else: else:
raise RequestError('Ivalid request') raise RequestError('Ivalid request')
return 'ok' return Permissions.permsToDict(permissions.getPermissions(obj))

View File

@ -32,7 +32,7 @@
''' '''
from __future__ import unicode_literals from __future__ import unicode_literals
__updated__ = '2015-03-02' __updated__ = '2015-03-04'
from uds.models import Permissions from uds.models import Permissions
from uds.core.util import ot from uds.core.util import ot
@ -50,6 +50,10 @@ def clean(obj):
Permissions.cleanPermissions(ot.getObjectType(obj), obj.pk) Permissions.cleanPermissions(ot.getObjectType(obj), obj.pk)
def getPermissions(obj):
return list(Permissions.enumeratePermissions(object_type=ot.getObjectType(obj), object_id=obj.pk))
def addUserPermission(user, obj, permission=PERMISSION_READ): def addUserPermission(user, obj, permission=PERMISSION_READ):
# Some permissions added to some object types needs at least READ_PERMISSION on parent # Some permissions added to some object types needs at least READ_PERMISSION on parent
Permissions.addPermission(user=user, object_type=ot.getObjectType(obj), object_id=obj.pk, permission=permission) Permissions.addPermission(user=user, object_type=ot.getObjectType(obj), object_id=obj.pk, permission=permission)
@ -67,3 +71,7 @@ def checkPermissions(user, obj, permission=PERMISSION_ALL):
return False return False
return Permissions.getPermissions(user=user, groups=user.groups.all(), object_type=ot.getObjectType(obj), object_id=obj.pk) >= permission return Permissions.getPermissions(user=user, groups=user.groups.all(), object_type=ot.getObjectType(obj), object_id=obj.pk) >= permission
def getPermissionName(perm):
return Permissions.permissionAsString(perm)

View File

@ -33,7 +33,7 @@
from __future__ import unicode_literals from __future__ import unicode_literals
__updated__ = '2015-03-02' __updated__ = '2015-03-04'
from django.utils.encoding import python_2_unicode_compatible from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
@ -153,6 +153,13 @@ class Permissions(UUIDModel):
except Exception: # DoesNotExists except Exception: # DoesNotExists
return Permissions.PERMISSION_NONE return Permissions.PERMISSION_NONE
@staticmethod
def enumeratePermissions(object_type, object_id):
'''
Get users permissions over object
'''
return Permissions.objects.filter(object_type=object_type, object_id=object_id)
@staticmethod @staticmethod
def cleanPermissions(object_type, object_id): def cleanPermissions(object_type, object_id):
Permissions.objects.filter(object_type=object_type, object_id=object_id).delete() Permissions.objects.filter(object_type=object_type, object_id=object_id).delete()
@ -165,6 +172,10 @@ class Permissions(UUIDModel):
def cleanGroupPermissions(group): def cleanGroupPermissions(group):
Permissions.objects.filter(group=group).delete() Permissions.objects.filter(group=group).delete()
@property
def permission_as_string(self):
return Permissions.permissionAsString(self.permission)
def __str__(self): def __str__(self):
return 'Permission {}, user {} group {} object_type {} object_id {} permission {}'.format( return 'Permission {}, user {} group {} object_type {} object_id {} permission {}'.format(
self.uuid, self.user, self.group, self.object_type, self.object_id, Permissions.permissionAsString(self.permission) self.uuid, self.user, self.group, self.object_type, self.object_id, Permissions.permissionAsString(self.permission)

View File

@ -268,7 +268,7 @@ class BasicModelRest
return return
getPermissions: (id, success_fnc, fail_fnc) -> getPermissions: (id, success_fnc, fail_fnc) ->
path = "permissions/" + @path + "/" + id path = "permissions/" + @path + '/' + id
@_requestPath path, @_requestPath path,
cacheKey: "." cacheKey: "."
success: success_fnc success: success_fnc
@ -282,6 +282,15 @@ class BasicModelRest
success: success_fnc success: success_fnc
fail: fail_fnc fail: fail_fnc
revokePermissions: (id, type, itemIds, success_fnc, fail_fnc)->
path = "permissions/revoke/" + @path + '/' + id + '/' + type
data =
ids: itemIds
api.putJson path, data,
success: success_fnc
fail: fail_fnc
types: (success_fnc, fail_fnc) -> types: (success_fnc, fail_fnc) ->
@_requestPath @typesPath, @_requestPath @typesPath,
cacheKey: @typesPath cacheKey: @typesPath

View File

@ -47,18 +47,64 @@ gui.permissions = (val, rest, tbl, refreshFnc) ->
gui.tools.applyCustoms modalId gui.tools.applyCustoms modalId
return return
delModal = (forUser, selectedItems) ->
if forUser
label = gettext('User')
items = 'users'
else
label = gettext('Group')
items = 'groups'
content = '<p>' + gettext("Confirm revocation of following permissions: <br/>")
content += '<ul style=\'font-family: "Courier New"\'><li>' + ($(v).text() for v in selectedItems).join('</li><li>') + '</li></ul>'
modalId = gui.launchModal gettext("Remove ") + label + " permission", content,
actionButton: "<button type=\"button\" class=\"btn btn-primary button-revoke\">" + gettext("Revoke") + "</button>"
toDel = ($(v).val() for v in selectedItems)
gui.doLog modalId
$(modalId + ' .button-revoke').on('click', () ->
rest.revokePermissions val.id, items, toDel
$(modalId).modal "hide"
)
fillSelect = (baseId, perms, forUser) ->
$select = $('#' + baseId + (if forUser then '_user_select' else '_group_select'))
$select.empty()
padRight = (str, len)->
numPads = len - str.length
if (numPads > 0) then str + Array(numPads+1).join('&nbsp;') else str
for item in perms
if (forUser is true and item.type is 'user') or (forUser is false and item.type is 'group')
$select.append('<option value="' + item.id + '">' + padRight(item.auth_name + '\\' + item.name, 28) + '&nbsp;| ' + item.perm_name)
api.templates.get "permissions", (tmpl) -> api.templates.get "permissions", (tmpl) ->
rest.getPermissions val.id, (data) -> rest.getPermissions val.id, (perms) ->
id = gui.genRamdonId('perms-') id = gui.genRamdonId('perms-')
content = api.templates.evaluate(tmpl, content = api.templates.evaluate(tmpl,
id: id id: id
perms: perms
) )
modalId = gui.launchModal gettext("Permissions for") + " " + val.name, content, modalId = gui.launchModal gettext("Permissions for") + " " + val.name, content,
actionButton: " " actionButton: " "
closeButton: '<button type="button" class="btn btn-default" data-dismiss="modal">Ok</button>' closeButton: '<button type="button" class="btn btn-default" data-dismiss="modal">Ok</button>'
# Fills user select
fillSelect id, perms, true
fillSelect id, perms, false
$('#' + id + '_user_del').on('click', () -> $('#' + id + '_user_del').on('click', () ->
alert('Del user') $select = $('#' + id + '_user_select')
selected = $select.find(":selected")
return if selected.length is 0
delModal true, selected
) )
$('#' + id + '_user_add').on('click', () -> $('#' + id + '_user_add').on('click', () ->
@ -66,7 +112,11 @@ gui.permissions = (val, rest, tbl, refreshFnc) ->
) )
$('#' + id + '_group_del').on('click', () -> $('#' + id + '_group_del').on('click', () ->
alert('Del group') $select = $('#' + id + '_group_select')
selected = $select.find(":selected")
return if selected.length is 0
delModal false, selected
) )
$('#' + id + '_group_add').on('click', () -> $('#' + id + '_group_add').on('click', () ->

View File

@ -5,15 +5,14 @@
<div class="col-md-6 column"> <div class="col-md-6 column">
<div class="form-group"> <div class="form-group">
<label for="{{ id }}_select">{% endverbatim %}{% trans 'Users' %}{% verbatim %}</label> <label for="{{ id }}_select">{% endverbatim %}{% trans 'Users' %}{% verbatim %}</label>
<select class="form-control" multiple size="8" id="{{ id }}_select"> <select class="form-control" multiple size="8" id="{{ id }}_user_select" style='font-family: "Courier New"'>
{{# each values }}<option>{{ this }}</option>{{/ each }}
</select> </select>
</div> </div>
<div class="form-group"> <div class="form-group">
<div class="row"> <div class="row">
<div class="col-xs-12"> <div class="col-xs-12">
<button type="button" id="{{ id }}_user_del" class="btn btn-warning">{% endverbatim %}{% trans 'Remove' %}{% verbatim %}</button> <button type="button" id="{{ id }}_user_del" class="btn btn-warning">{% endverbatim %}{% trans 'Revoke user permission' %}{% verbatim %}</button>
<button type="button" id="{{ id }}_user_add" class="btn btn-success">{% endverbatim %}{% trans 'Add User' %}{% verbatim %}</button> <button type="button" id="{{ id }}_user_add" class="btn btn-success">{% endverbatim %}{% trans 'Add user permission' %}{% verbatim %}</button>
</div> </div>
</div> </div>
</div> </div>
@ -21,15 +20,14 @@
<div class="col-md-6 column"> <div class="col-md-6 column">
<div class="form-group"> <div class="form-group">
<label for="{{ id }}_select">{% endverbatim %}{% trans 'Groups' %}{% verbatim %}</label> <label for="{{ id }}_select">{% endverbatim %}{% trans 'Groups' %}{% verbatim %}</label>
<select class="form-control" multiple size="8" id="{{ id }}_select"> <select class="form-control" multiple size="8" id="{{ id }}_group_select" style='font-family: "Courier New"'>
{{# each values }}<option>{{ this }}</option>{{/ each }}
</select> </select>
</div> </div>
<div class="form-group"> <div class="form-group">
<div class="row"> <div class="row">
<div class="col-xs-12"> <div class="col-xs-12">
<button type="button" id="{{ id }}_group_del" class="btn btn-warning">{% endverbatim %}{% trans 'Remove' %}{% verbatim %}</button> <button type="button" id="{{ id }}_group_del" class="btn btn-warning">{% endverbatim %}{% trans 'Revoke group permission' %}{% verbatim %}</button>
<button type="button" id="{{ id }}_group_add" class="btn btn-success">{% endverbatim %}{% trans 'Add Group' %}{% verbatim %}</button> <button type="button" id="{{ id }}_group_add" class="btn btn-success">{% endverbatim %}{% trans 'Add group permission' %}{% verbatim %}</button>
</div> </div>
</div> </div>
</div> </div>