Added "details" to REST for children of certain elements (such as authenticators-->users, user services --> publications, cache, assignations, groups, transports, etc...

This commit is contained in:
Adolfo Gómez 2013-11-15 16:04:51 +00:00
parent bf83de2f5e
commit 2615b5fca4
7 changed files with 161 additions and 24 deletions

View File

@ -10,12 +10,13 @@ encoding//src/server/settings.py=utf-8
encoding//src/server/urls.py=utf-8
encoding//src/uds/REST/__init__.py=utf-8
encoding//src/uds/REST/handlers.py=utf-8
encoding//src/uds/REST/methods/authentication.py=utf-8
encoding//src/uds/REST/methods/authenticators.py=utf-8
encoding//src/uds/REST/methods/login_logout.py=utf-8
encoding//src/uds/REST/methods/networks.py=utf-8
encoding//src/uds/REST/methods/osmanagers.py=utf-8
encoding//src/uds/REST/methods/providers.py=utf-8
encoding//src/uds/REST/methods/transports.py=utf-8
encoding//src/uds/REST/methods/users.py=utf-8
encoding//src/uds/REST/mixins.py=utf-8
encoding//src/uds/REST/processors.py=utf-8
encoding//src/uds/__init__.py=utf-8

View File

@ -36,6 +36,8 @@ from django.utils.translation import ugettext_lazy as _
from uds.models import Authenticator
from uds.core import auths
from users import Users
from uds.REST import Handler, HandlerError
from uds.REST.mixins import ModelHandlerMixin, ModelTypeHandlerMixin, ModelTableHandlerMixin
@ -47,6 +49,7 @@ logger = logging.getLogger(__name__)
class Authenticators(ModelHandlerMixin, Handler):
model = Authenticator
detail = { 'users': Users }
def item_as_dict(self, auth):
type_ = auth.getType()

View File

@ -0,0 +1,82 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2014 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
@author: Adolfo Gómez, dkmaster at dkmon dot com
'''
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.utils import formats
from uds.models import User
from uds.REST.mixins import DetailHandler
import logging
logger = logging.getLogger(__name__)
# Enclosed methods under /auth path
class Users(DetailHandler):
def user_as_dict(self, user):
return {
'id': user.id,
'name': user.name,
'real_name': user.real_name,
'comments': user.comments,
'state': user.state,
'staff_member': user.staff_member,
'is_admin': user.is_admin,
'last_access': formats.date_format(user.last_access, 'DATETIME_FORMAT'),
'parent': user.parent
}
def get(self):
logger.debug(self._parent)
logger.debug(self._kwargs)
# Extract authenticator
auth = self._kwargs['parent']
try:
if len(self._args) == 0:
res = []
for u in auth.users.all():
res.append(self.user_as_dict(u))
return res
else:
return self.user_as_dict(auth.get(pk=self._args[0]))
except:
logger.exception('En users')
return { 'error': 'not found' }

View File

@ -38,6 +38,13 @@ import logging
logger = logging.getLogger(__name__)
class DetailHandler(object):
def __init__(self, parentHandler, path, *args, **kwargs):
self._parent = parentHandler
self._path = path
self._args = args
self._kwargs = kwargs
class ModelHandlerMixin(object):
'''
Basic Handler for a model
@ -46,7 +53,7 @@ class ModelHandlerMixin(object):
'''
authenticated = True
needs_staff = True
detail = None # Dictionary containing detail routing
model = None
def item_as_dict(self, item):
@ -59,12 +66,29 @@ class ModelHandlerMixin(object):
except:
logger.exception('Exception getting item from {0}'.format(self.model))
def processDetail(self):
logger.debug('Processing detail')
try:
item = self.model.objects.filter(pk=self._args[0])[0]
detailCls = self.detail[self._args[1]]
args = list(self._args[2:])
path = self._path + '/'.join(args[:2])
detail = detailCls(self, path, parent = item)
return getattr(detail, self._operation)()
except:
return {'error': 'method not found' }
def get(self):
logger.debug('methot GET for {0}'.format(self.__class__.__name__))
logger.debug('method GET for {0}, {1}'.format(self.__class__.__name__, self._args))
if len(self._args) == 0:
return list(self.getItems())
# If has detail and is requesting detail
if self.detail is not None and len(self._args) > 1:
return self.processDetail()
try:
return list(self.getItems(pk=self._args[0]))[0]
item = list(self.getItems(pk=self._args[0]))[0]
except:
return {'error': 'not found' }

View File

@ -42,7 +42,7 @@
// We will take advantage of this and save a lot of nonsense, prone to failure code :-)
function BasicModelRest(path) {
this.path = path;
this.path = path || "";
this.cached_types = undefined;
this.cached_tableInfo = undefined;
}
@ -95,11 +95,31 @@ BasicModelRest.prototype = {
},
};
// For REST of type /auth/[id]/users, /services/[id]/users, ...
function DetailModelRestApi(parentApi, path) {
this.parentPath = parentApi.path;
this.path = path;
}
DetailModelRestApi.prototype = {
detail: function(parentId) {
var rest = new BasicModelRest(this.parentPath + '/' + parentId + '/' + this.path);
rest.types = function() {
return []; // No types at all
}
}
};
// Populate api
api.providers = new BasicModelRest('providers');
//api.services = new BasicModelRest('services');
api.authenticators = new BasicModelRest('authenticators');
api.authenticators.users = new DetailModelRestApi(api.authenticators, 'users');
api.osmanagers = new BasicModelRest('osmanagers');
api.transports = new BasicModelRest('transports');
api.networks = new BasicModelRest('networks');

View File

@ -121,7 +121,7 @@ GuiElement.prototype = {
gui.doLog('Initializing ' + this.name);
var $this = this;
this.rest.types(function(data){
var styles = '<style media="screen">';
var styles = '';
$.each(data, function(index, value){
var className = $this.name + '-' + value.type;
$this.types[value.type] = { css: className, name: value.name || '', description: value.description || '' };
@ -131,8 +131,10 @@ GuiElement.prototype = {
'width: 16px; height: 16px; vertical-align: middle; } ';
styles += style;
});
styles += '</style>'
$(styles).appendTo('head');
if(styles != '') {
styles = '<style media="screen">' + styles + '</style>'
$(styles).appendTo('head');
}
});
},
table: function(options) {
@ -190,18 +192,6 @@ GuiElement.prototype = {
}
var btns = [
/*{
"sExtends": "csv",
"sTitle": title,
"sFileName": title + '.csv',
},*/
/*{
"sExtends": "pdf",
"sTitle": title,
"sPdfMessage": "Summary Info",
"sFileName": title + '.pdf',
"sPdfOrientation": "portrait"
},*/
];
if( options.buttons ) {
@ -262,7 +252,7 @@ GuiElement.prototype = {
"fnSelect": editSelected,
"fnClick": editFnc,
"sButtonClass": "disabled"
}
};
break;
case 'delete':
btn = {
@ -271,7 +261,7 @@ GuiElement.prototype = {
"fnSelect": deleteSelected,
"fnClick": deleteFnc,
"sButtonClass": "disabled"
}
};
break;
case 'refresh':
btn = {
@ -279,8 +269,24 @@ GuiElement.prototype = {
"sButtonText": gettext('Refresh'),
"fnClick": refreshFnc,
"sButtonClass": "btn-info"
}
};
break;
case 'csb':
btn = {
"sExtends": "csv",
"sTitle": title,
"sFileName": title + '.csv',
};
break;
case 'pdf':
btn = {
"sExtends": "pdf",
"sTitle": title,
"sPdfMessage": "Summary Info",
"sFileName": title + '.pdf',
"sPdfOrientation": "portrait"
};
break;
}
if( btn != undefined )
@ -343,6 +349,7 @@ gui.providers.link = function(event) {
};
gui.authenticators = new GuiElement(api.authenticators, 'auth');
gui.authenticators.link = function(event) {
gui.clearWorkspace();
gui.appendToWorkspace(gui.breadcrumbs(gettext('Authenticators')));
@ -381,7 +388,7 @@ gui.connectivity.link = function(event) {
gui.connectivity.transports.table({
rowSelect: 'multi',
container: 'ttbl',
buttons: ['edit', 'refresh', 'delete'],
buttons: ['edit', 'refresh', 'delete', 'pdf'],
});
gui.connectivity.networks.table({
rowSelect: 'single',