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
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
perm = permissions.getEffectivePermission(self._user, parent)
try:
@ -87,7 +87,7 @@ class AccountsUsage(DetailHandler): # pylint: disable=too-many-public-methods
logger.exception('itemId %s', item)
self.invalidItemException()
def getFields(self, parent: Account) -> typing.List[typing.Any]:
def getFields(self, parent: 'Account') -> typing.List[typing.Any]:
return [
{'pool_name': {'title': _('Pool name')}},
{'user_name': {'title': _('User name')}},
@ -98,13 +98,13 @@ class AccountsUsage(DetailHandler): # pylint: disable=too-many-public-methods
{'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-'}
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')
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)
try:
usage = parent.usages.get(uuid=processUuid(item))
@ -113,7 +113,7 @@ class AccountsUsage(DetailHandler): # pylint: disable=too-many-public-methods
logger.exception('Exception')
self.invalidItemException()
def getTitle(self, parent: Account) -> str:
def getTitle(self, parent: 'Account') -> str:
try:
return _('Usages of {0}').format(parent.name)
except Exception:

View File

@ -31,6 +31,7 @@
@author: Adolfo Gómez, dkmaster at dkmon dot com
"""
import logging
import typing
from django.utils.translation import ugettext_lazy as _
from uds.models import Authenticator
@ -42,6 +43,9 @@ from uds.core.util import permissions
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__)
@ -66,28 +70,34 @@ class Authenticators(ModelHandler):
{'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()
def typeInfo(self, type_):
return {
'canSearchUsers': type_.searchUsers != auths.Authenticator.searchUsers,
'canSearchGroups': type_.searchGroups != auths.Authenticator.searchGroups,
'needsPassword': type_.needsPassword,
'userNameLabel': _(type_.userNameLabel),
'groupNameLabel': _(type_.groupNameLabel),
'passwordLabel': _(type_.passwordLabel),
'canCreateUsers': type_.createUser != auths.Authenticator.createUser,
'isExternal': type_.isExternalSource,
}
def typeInfo(self, type_: typing.Type['Module']) -> typing.Dict[str, typing.Any]:
if issubclass(type_, auths.Authenticator):
return {
'canSearchUsers': type_.searchUsers != auths.Authenticator.searchUsers,
'canSearchGroups': type_.searchGroups != auths.Authenticator.searchGroups,
'needsPassword': type_.needsPassword,
'userNameLabel': _(type_.userNameLabel),
'groupNameLabel': _(type_.groupNameLabel),
'passwordLabel': _(type_.passwordLabel),
'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:
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:
raise NotFound('type not found')
def item_as_dict(self, item):
def item_as_dict(self, item: Authenticator):
type_ = item.getType()
return {
'numeric_id': item.id,
@ -105,7 +115,7 @@ class Authenticators(ModelHandler):
}
# Custom "search" method
def search(self, item):
def search(self, item: Authenticator) -> typing.List[typing.Dict]:
self.ensureAccess(item, permissions.PERMISSION_READ)
try:
type_ = self._params['type']
@ -123,18 +133,22 @@ class Authenticators(ModelHandler):
self.notSupported()
if type_ == 'user':
return auth.searchUsers(term)[:limit]
return list(auth.searchUsers(term))[:limit]
else:
return auth.searchGroups(term)[:limit]
return list(auth.searchGroups(term))[:limit]
except Exception as e:
logger.exception('Too many results: %s', e)
return [{'id': _('Too many results...'), 'name': _('Refine your query')}]
# self.invalidResponseException('{}'.format(e))
def test(self, type_):
def test(self, type_: str):
from uds.core.environment import Environment
authType = auths.factory().lookup(type_)
if not authType:
self.invalidRequestException('Invalid type: {}'.format(type_))
return False
self.ensureAccess(authType, permissions.PERMISSION_MANAGEMENT, root=True)
dct = self._params.copy()
@ -142,10 +156,9 @@ class Authenticators(ModelHandler):
res = authType.test(Environment.getTempEnv(), dct)
if res[0]:
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 user in item.users.all():

View File

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