1
0
mirror of https://github.com/dkmstr/openuds.git synced 2025-03-06 08:58:37 +03:00

fixed REST authenticator for python 3.x

This commit is contained in:
Adolfo Gómez García 2019-09-11 08:42:11 +02:00
parent 420e491196
commit 060e2cd023
3 changed files with 47 additions and 39 deletions

View File

@ -75,7 +75,7 @@ class AccountsUsage(DetailHandler): # pylint: disable=too-many-public-methods
return retVal return retVal
def getItems(self, parent: Account, item: typing.Optional[str]): def getItems(self, parent: 'Account', item: typing.Optional[str]):
# Check what kind of access do we have to parent provider # Check what kind of access do we have to parent provider
perm = permissions.getEffectivePermission(self._user, parent) perm = permissions.getEffectivePermission(self._user, parent)
try: try:
@ -87,7 +87,7 @@ class AccountsUsage(DetailHandler): # pylint: disable=too-many-public-methods
logger.exception('itemId %s', item) logger.exception('itemId %s', item)
self.invalidItemException() self.invalidItemException()
def getFields(self, parent: Account) -> typing.List[typing.Any]: def getFields(self, parent: 'Account') -> typing.List[typing.Any]:
return [ return [
{'pool_name': {'title': _('Pool name')}}, {'pool_name': {'title': _('Pool name')}},
{'user_name': {'title': _('User name')}}, {'user_name': {'title': _('User name')}},
@ -98,13 +98,13 @@ class AccountsUsage(DetailHandler): # pylint: disable=too-many-public-methods
{'elapsed_timemark': {'title': _('Elapsed timemark')}}, {'elapsed_timemark': {'title': _('Elapsed timemark')}},
] ]
def getRowStyle(self, parent: Account) -> typing.Dict[str, typing.Any]: def getRowStyle(self, parent: 'Account') -> typing.Dict[str, typing.Any]:
return {'field': 'running', 'prefix': 'row-running-'} return {'field': 'running', 'prefix': 'row-running-'}
def saveItem(self, parent: Account, item: typing.Optional[str]) -> None: def saveItem(self, parent: 'Account', item: typing.Optional[str]) -> None:
raise RequestError('Accounts usage cannot be edited') raise RequestError('Accounts usage cannot be edited')
def deleteItem(self, parent: Account, item: str) -> None: def deleteItem(self, parent: 'Account', item: str) -> None:
logger.debug('Deleting account usage %s from %s', item, parent) logger.debug('Deleting account usage %s from %s', item, parent)
try: try:
usage = parent.usages.get(uuid=processUuid(item)) usage = parent.usages.get(uuid=processUuid(item))
@ -113,7 +113,7 @@ class AccountsUsage(DetailHandler): # pylint: disable=too-many-public-methods
logger.exception('Exception') logger.exception('Exception')
self.invalidItemException() self.invalidItemException()
def getTitle(self, parent: Account) -> str: def getTitle(self, parent: 'Account') -> str:
try: try:
return _('Usages of {0}').format(parent.name) return _('Usages of {0}').format(parent.name)
except Exception: except Exception:

View File

@ -31,6 +31,7 @@
@author: Adolfo Gómez, dkmaster at dkmon dot com @author: Adolfo Gómez, dkmaster at dkmon dot com
""" """
import logging import logging
import typing
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from uds.models import Authenticator from uds.models import Authenticator
@ -42,6 +43,9 @@ from uds.core.util import permissions
from .users_groups import Users, Groups from .users_groups import Users, Groups
# Not imported at runtime, just for type checking
if typing.TYPE_CHECKING:
from uds.core import Module
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -66,28 +70,34 @@ class Authenticators(ModelHandler):
{'tags': {'title': _('tags'), 'visible': False}}, {'tags': {'title': _('tags'), 'visible': False}},
] ]
def enum_types(self): def enum_types(self) -> typing.Iterable[typing.Type[auths.Authenticator]]: # override this
return auths.factory().providers().values() return auths.factory().providers().values()
def typeInfo(self, type_): def typeInfo(self, type_: typing.Type['Module']) -> typing.Dict[str, typing.Any]:
return { if issubclass(type_, auths.Authenticator):
'canSearchUsers': type_.searchUsers != auths.Authenticator.searchUsers, return {
'canSearchGroups': type_.searchGroups != auths.Authenticator.searchGroups, 'canSearchUsers': type_.searchUsers != auths.Authenticator.searchUsers,
'needsPassword': type_.needsPassword, 'canSearchGroups': type_.searchGroups != auths.Authenticator.searchGroups,
'userNameLabel': _(type_.userNameLabel), 'needsPassword': type_.needsPassword,
'groupNameLabel': _(type_.groupNameLabel), 'userNameLabel': _(type_.userNameLabel),
'passwordLabel': _(type_.passwordLabel), 'groupNameLabel': _(type_.groupNameLabel),
'canCreateUsers': type_.createUser != auths.Authenticator.createUser, 'passwordLabel': _(type_.passwordLabel),
'isExternal': type_.isExternalSource, 'canCreateUsers': type_.createUser != auths.Authenticator.createUser,
} 'isExternal': type_.isExternalSource,
}
# Not of my type
return {}
def getGui(self, type_): def getGui(self, type_: str) -> typing.List[typing.Any]:
try: try:
return self.addDefaultFields(auths.factory().lookup(type_).guiDescription(), ['name', 'comments', 'tags', 'priority', 'small_name']) gui = auths.factory().lookup(type_)
if gui:
return self.addDefaultFields(gui.guiDescription(), ['name', 'comments', 'tags', 'priority', 'small_name'])
raise Exception() # Not found
except Exception: except Exception:
raise NotFound('type not found') raise NotFound('type not found')
def item_as_dict(self, item): def item_as_dict(self, item: Authenticator):
type_ = item.getType() type_ = item.getType()
return { return {
'numeric_id': item.id, 'numeric_id': item.id,
@ -105,7 +115,7 @@ class Authenticators(ModelHandler):
} }
# Custom "search" method # Custom "search" method
def search(self, item): def search(self, item: Authenticator) -> typing.List[typing.Dict]:
self.ensureAccess(item, permissions.PERMISSION_READ) self.ensureAccess(item, permissions.PERMISSION_READ)
try: try:
type_ = self._params['type'] type_ = self._params['type']
@ -123,18 +133,22 @@ class Authenticators(ModelHandler):
self.notSupported() self.notSupported()
if type_ == 'user': if type_ == 'user':
return auth.searchUsers(term)[:limit] return list(auth.searchUsers(term))[:limit]
else: else:
return auth.searchGroups(term)[:limit] return list(auth.searchGroups(term))[:limit]
except Exception as e: except Exception as e:
logger.exception('Too many results: %s', e) logger.exception('Too many results: %s', e)
return [{'id': _('Too many results...'), 'name': _('Refine your query')}] return [{'id': _('Too many results...'), 'name': _('Refine your query')}]
# self.invalidResponseException('{}'.format(e)) # self.invalidResponseException('{}'.format(e))
def test(self, type_): def test(self, type_: str):
from uds.core.environment import Environment from uds.core.environment import Environment
authType = auths.factory().lookup(type_) authType = auths.factory().lookup(type_)
if not authType:
self.invalidRequestException('Invalid type: {}'.format(type_))
return False
self.ensureAccess(authType, permissions.PERMISSION_MANAGEMENT, root=True) self.ensureAccess(authType, permissions.PERMISSION_MANAGEMENT, root=True)
dct = self._params.copy() dct = self._params.copy()
@ -142,10 +156,9 @@ class Authenticators(ModelHandler):
res = authType.test(Environment.getTempEnv(), dct) res = authType.test(Environment.getTempEnv(), dct)
if res[0]: if res[0]:
return self.success() return self.success()
else: return res[1]
return res[1]
def deleteItem(self, item): def deleteItem(self, item: Authenticator):
# For every user, remove assigned services (mark them for removal) # For every user, remove assigned services (mark them for removal)
for user in item.users.all(): for user in item.users.all():

View File

@ -63,7 +63,6 @@ if typing.TYPE_CHECKING:
from uds.models import User from uds.models import User
from uds.core import Module from uds.core import Module
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# a few constants # a few constants
@ -75,14 +74,12 @@ LOG = 'log'
OK = 'ok' # Constant to be returned when result is just "operation complete successfully" OK = 'ok' # Constant to be returned when result is just "operation complete successfully"
# Exception to "rethrow" on save error # Exception to "rethrow" on save error
class SaveException(HandlerError): class SaveException(HandlerError):
""" """
Exception thrown if couldn't save Exception thrown if couldn't save
""" """
class BaseModelHandler(Handler): class BaseModelHandler(Handler):
""" """
Base Handler for Master & Detail Handlers Base Handler for Master & Detail Handlers
@ -186,10 +183,7 @@ class BaseModelHandler(Handler):
return gui return gui
def ensureAccess(self, obj: typing.Any, permission: int, root=False) -> int: def ensureAccess(self, obj: typing.Any, permission: int, root=False) -> int:
if self._user: perm = permissions.getEffectivePermission(self._user, obj, root)
perm = permissions.getEffectivePermission(self._user, obj, root)
else:
perm = -999999
if perm < permission: if perm < permission:
self.accessDenied() self.accessDenied()
return perm return perm
@ -308,7 +302,7 @@ class BaseModelHandler(Handler):
logger.debug('Returning success on %s %s', self.__class__, self._args) logger.debug('Returning success on %s %s', self.__class__, self._args)
return OK return OK
def test(self, type_: typing.Type['Module']): def test(self, type_: str):
""" """
Invokes a test for an item Invokes a test for an item
""" """
@ -598,8 +592,9 @@ class ModelHandler(BaseModelHandler):
# Authentication related # Authentication related
authenticated = True authenticated = True
needs_staff = True needs_staff = True
# Which model does this manage
model: models.Model # Which model does this manage, must be a django model ofc
model: typing.ClassVar[models.Model]
# By default, filter is empty # By default, filter is empty
fltr: typing.Optional[str] = None fltr: typing.Optional[str] = None
@ -638,7 +633,7 @@ class ModelHandler(BaseModelHandler):
return self.item_as_dict(item) return self.item_as_dict(item)
# types related # types related
def enum_types(self) -> typing.Iterable['Module']: # override this def enum_types(self) -> typing.Iterable[typing.Type['Module']]: # override this
""" """
Must be overriden by desdencents if they support types Must be overriden by desdencents if they support types
Excpetcs the list of types that the handler supports Excpetcs the list of types that the handler supports