1
0
mirror of https://github.com/dkmstr/openuds.git synced 2025-01-22 22:03:54 +03:00

fixing up REST exceptions

This commit is contained in:
Adolfo Gómez García 2019-09-12 12:42:08 +02:00
parent ecdc4fa606
commit 726cc33320
7 changed files with 47 additions and 47 deletions

View File

@ -120,7 +120,7 @@ class Authenticators(ModelHandler):
try:
type_ = self._params['type']
if type_ not in ('user', 'group'):
self.invalidRequestException()
raise self.invalidRequestException()
term = self._params['term']
@ -146,8 +146,7 @@ class Authenticators(ModelHandler):
authType = auths.factory().lookup(type_)
if not authType:
self.invalidRequestException('Invalid type: {}'.format(type_))
return False
raise self.invalidRequestException('Invalid type: {}'.format(type_))
self.ensureAccess(authType, permissions.PERMISSION_MANAGEMENT, root=True)

View File

@ -93,7 +93,7 @@ class AccessCalendars(DetailHandler):
if access not in (ALLOW, DENY):
raise Exception()
except Exception:
self.invalidRequestException(_('Invalid parameters on request'))
raise self.invalidRequestException(_('Invalid parameters on request'))
priority = int(self._params['priority'])
if uuid is not None:
@ -121,7 +121,7 @@ class ActionsCalendars(DetailHandler):
"""
Processes the transports detail requests of a Service Pool
"""
custom_methods = ('execute',)
custom_methods = ['execute',]
@staticmethod
def as_dict(item: 'CalendarAction') -> typing.Dict[str, typing.Any]:
@ -171,7 +171,7 @@ class ActionsCalendars(DetailHandler):
calendar = Calendar.objects.get(uuid=processUuid(self._params['calendarId']))
action = self._params['action'].upper()
if action not in CALENDAR_ACTION_DICT:
self.invalidRequestException()
raise self.invalidRequestException()
eventsOffset = int(self._params['eventsOffset'])
atStart = self._params['atStart'] not in ('false', False, '0', 0)
params = json.dumps(self._params['params'])

View File

@ -69,7 +69,7 @@ class Reports(model.BaseModelHandler):
break
if found is None:
self.invalidRequestException('Invalid report!')
raise self.invalidRequestException('Invalid report!')
return found
@ -90,7 +90,7 @@ class Reports(model.BaseModelHandler):
if self._args[0] == model.GUI:
return self.getGui(self._args[1])
return self.invalidRequestException()
raise self.invalidRequestException()
def put(self):
"""
@ -99,7 +99,7 @@ class Reports(model.BaseModelHandler):
logger.debug('method PUT for %s, %s, %s', self.__class__.__name__, self._args, self._params)
if len(self._args) != 1:
return self.invalidRequestException()
raise self.invalidRequestException()
report = self._findReport(self._args[0], self._params)
@ -117,7 +117,7 @@ class Reports(model.BaseModelHandler):
return data
except Exception as e:
logger.exception('Generating report')
return self.invalidRequestException(str(e))
raise self.invalidRequestException(str(e))
# Gui related
def getGui(self, uuid):

View File

@ -333,7 +333,7 @@ class Publications(DetailHandler):
if permissions.checkPermissions(self._user, parent, permissions.PERMISSION_MANAGEMENT) is False:
logger.debug('Management Permission failed for user %s', self._user)
self.accessDenied()
raise self.accessDenied()
logger.debug('Custom "publish" invoked for %s', parent)
parent.publish(changeLog) # Can raise exceptions that will be processed on response
@ -351,7 +351,7 @@ class Publications(DetailHandler):
"""
if permissions.checkPermissions(self._user, parent, permissions.PERMISSION_MANAGEMENT) is False:
logger.debug('Management Permission failed for user %s', self._user)
self.accessDenied()
raise self.accessDenied()
try:
ds = ServicePoolPublication.objects.get(uuid=processUuid(uuid))

View File

@ -176,7 +176,7 @@ class Users(DetailHandler):
raise RequestError(str(e.message))
except Exception:
logger.exception('Saving user')
self.invalidRequestException()
raise self.invalidRequestException()
return self.getItems(parent, user.uuid)
@ -302,7 +302,7 @@ class Groups(DetailHandler):
try:
return types[forType]
except Exception:
self.invalidRequestException()
raise self.invalidRequestException()
def saveItem(self, parent, item):
group = None # Avoid warning on reference before assignment
@ -356,7 +356,7 @@ class Groups(DetailHandler):
raise RequestError(str(e))
except Exception:
logger.exception('Saving group')
self.invalidRequestException()
raise self.invalidRequestException()
return self.getItems(parent, group.uuid)
@ -413,7 +413,7 @@ class Groups(DetailHandler):
else:
tmpSet &= gSet
if len(tmpSet) == 0 :
if not tmpSet:
break # If already empty, stop
users = list(tmpSet)
tmpSet = None

View File

@ -185,7 +185,7 @@ class BaseModelHandler(Handler):
def ensureAccess(self, obj: typing.Any, permission: int, root=False) -> int:
perm = permissions.getEffectivePermission(self._user, obj, root)
if perm < permission:
self.accessDenied()
raise self.accessDenied()
return perm
def typeInfo(self, type_: typing.Type['Module']) -> typing.Dict[str, typing.Any]:
@ -262,17 +262,17 @@ class BaseModelHandler(Handler):
return res
# Exceptions
def invalidRequestException(self, message: typing.Optional[str] = None):
def invalidRequestException(self, message: typing.Optional[str] = None) -> HandlerError:
"""
Raises an invalid request error with a default translated string
:param message: Custom message to add to exception. If it is None, "Invalid Request" is used
"""
message = message or _('Invalid Request')
raise RequestError('{} {}: {}'.format(message, self.__class__, self._args))
return RequestError('{} {}: {}'.format(message, self.__class__, self._args))
def invalidResponseException(self, message: typing.Optional[str] = None):
def invalidResponseException(self, message: typing.Optional[str] = None) -> HandlerError:
message = 'Invalid response' if message is None else message
raise ResponseError(message)
return ResponseError(message)
def invalidMethodException(self):
"""
@ -288,8 +288,8 @@ class BaseModelHandler(Handler):
raise NotFound(message)
# raise NotFound('{} {}: {}'.format(message, self.__class__, self._args))
def accessDenied(self, message: typing.Optional[str] = None) -> None:
raise AccessDenied(message or _('Access denied'))
def accessDenied(self, message: typing.Optional[str] = None) -> HandlerError:
return AccessDenied(message or _('Access denied'))
def notSupported(self, message: typing.Optional[str] = None) -> None:
raise NotSupportedError(message or _('Operation not supported'))
@ -307,7 +307,7 @@ class BaseModelHandler(Handler):
Invokes a test for an item
"""
logger.debug('Called base test for %s --> %s', self.__class__.__name__, self._params)
return self.invalidMethodException()
self.invalidMethodException()
# Details do not have types at all
@ -441,7 +441,7 @@ class DetailHandler(BaseModelHandler):
if len(self._args) == 1:
item = self._args[0]
elif len(self._args) > 1: # PUT expects 0 or 1 parameters. 0 == NEW, 1 = EDIT
self.invalidRequestException()
raise self.invalidRequestException()
logger.debug('Invoking proper saving detail item %s', item)
return self.saveItem(parent, item)
@ -452,7 +452,7 @@ class DetailHandler(BaseModelHandler):
Post can be used for, for example, testing.
Right now is an invalid method for Detail elements
"""
self.invalidRequestException('This method does not accepts POST')
raise self.invalidRequestException('This method does not accepts POST')
def delete(self) -> typing.Any:
"""
@ -464,7 +464,7 @@ class DetailHandler(BaseModelHandler):
parent = self._kwargs['parent']
if len(self._args) != 1:
self.invalidRequestException()
raise self.invalidRequestException()
self.deleteItem(parent, self._args[0])
@ -502,7 +502,7 @@ class DetailHandler(BaseModelHandler):
:return: Normally "success" is expected, but can throw any "exception"
"""
logger.debug('Default saveItem handler caller for %s', self._path)
self.invalidRequestException()
raise self.invalidRequestException()
# Default delete
def deleteItem(self, parent: models.Model, item: str) -> None:
@ -513,7 +513,7 @@ class DetailHandler(BaseModelHandler):
:param item: Item id (uuid)
:return: Normally "success" is expected, but can throw any "exception"
"""
self.invalidRequestException()
raise self.invalidRequestException()
# A detail handler must also return title & fields for tables
def getTitle(self, parent: models.Model) -> str: # pylint: disable=no-self-use
@ -669,7 +669,7 @@ class ModelHandler(BaseModelHandler):
# gui related
def getGui(self, type_: str) -> typing.List[typing.Any]:
return []
# self.invalidRequestException()
# raise self.invalidRequestException()
# Delete related, checks if the item can be deleted
# If it can't be so, raises an exception
@ -754,7 +754,7 @@ class ModelHandler(BaseModelHandler):
if permissions.checkPermissions(self._user, item, requiredPermission) is False:
logger.debug('Permission for user %s does not comply with %s', self._user, requiredPermission)
self.accessDenied()
raise self.accessDenied()
detailCls = self.detail[self._args[1]] # pylint: disable=unsubscriptable-object
args = list(self._args[2:])
@ -850,19 +850,19 @@ class ModelHandler(BaseModelHandler):
# Request type info or gui, or detail
if self._args[0] == OVERVIEW:
if nArgs != 2:
self.invalidRequestException()
raise self.invalidRequestException()
elif self._args[0] == TYPES:
if nArgs != 2:
self.invalidRequestException()
raise self.invalidRequestException()
return self.getType(self._args[1])
elif self._args[0] == GUI:
if nArgs != 2:
self.invalidRequestException()
raise self.invalidRequestException()
gui = self.getGui(self._args[1])
return sorted(gui, key=lambda f: f['gui']['order'])
elif self._args[1] == LOG:
if nArgs != 2:
self.invalidRequestException()
raise self.invalidRequestException()
try:
item = self.model.objects.get(uuid=self._args[0].lower()) # DB maybe case sensitive??, anyway, uuids are stored in lowercase
return self.getLogs(item)
@ -873,8 +873,7 @@ class ModelHandler(BaseModelHandler):
if self.detail is not None:
return self.processDetail()
self.invalidRequestException() # Will not return
return None # So pylint does not complains :)
raise self.invalidRequestException() # Will not return
def post(self):

View File

@ -39,34 +39,36 @@ The registration of modules is done locating subclases of :py:class:`uds.core.au
.. moduleauthor:: Adolfo Gómez, dkmaster at dkmon dot com
"""
import os.path
import pkgutil
import sys
import logging
import typing
from uds.core import reports
logger = logging.getLogger(__name__)
availableReports = []
availableReports: typing.List[typing.Type['reports.Report']] = []
# noinspection PyTypeChecker
def __init__():
"""
This imports all packages that are descendant of this package, and, after that,
"""
import os.path
import pkgutil
import sys
from uds.core import reports
def addReportCls(cls):
def addReportCls(cls: typing.Type[reports.Report]):
logger.debug('Adding report %s', cls)
availableReports.append(cls)
def recursiveAdd(reportClass):
def recursiveAdd(reportClass: typing.Type[reports.Report]):
if reportClass.uuid:
addReportCls(reportClass)
else:
logger.debug('Report class %s not added because it lacks of uuid (it is probably a base class)', reportClass)
for c in reportClass.__subclasses__():
recursiveAdd(c)
subReport: typing.Type[reports.Report]
for subReport in reportClass.__subclasses__():
recursiveAdd(subReport)
# Dinamycally import children of this package. The __init__.py files must import classes
pkgpath = os.path.dirname(sys.modules[__name__].__file__)