Beispiel #1
0
def index(request):
    """
    Renders the main page.
    :param request: http request
    """
    if request.session.get('ticket') == '1':
        return webLogout(request)

    # Session data
    os = request.os

    # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
    groups = list(request.user.getGroups())
    availServices = DeployedService.getDeployedServicesForGroups(groups)
    availUserServices = UserService.getUserAssignedServices(request.user)

    # Information for administrators
    nets = ''
    validTrans = ''

    logger.debug('OS: {0}'.format(os['OS']))

    if request.user.isStaff():
        nets = ','.join([n.name for n in Network.networksFor(request.ip)])
        tt = []
        for t in Transport.objects.all():
            if t.validForIp(request.ip):
                tt.append(t.name)
        validTrans = ','.join(tt)

    # Extract required data to show to user
    services = []
    # Select assigned user services (manually assigned)
    for svr in availUserServices:
        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if t.validForIp(request.ip) and typeTrans.supportsOs(
                    os['OS']) and t.validForOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink',
                                   args=('A' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'A' + svr.uuid, t.uuid)
                trans.append({'id': t.uuid, 'name': t.name, 'link': link})

        servicePool = svr.deployed_service

        if servicePool.image is not None:
            imageId = servicePool.image.uuid
        else:
            imageId = 'x'  # Invalid

        # Extract app group
        group = servicePool.servicesPoolGroup if servicePool.servicesPoolGroup is not None else ServicesPoolGroup.default(
        ).as_dict

        services.append({
            'id': 'A' + svr.uuid,
            'name': servicePool.name,
            'visual_name': servicePool.visual_name,
            'description': servicePool.comments,
            'group': group,
            'transports': trans,
            'imageId': imageId,
            'show_transports': servicePool.show_transports,
            'allow_users_remove': servicePool.allow_users_remove,
            'allow_users_reset': servicePool.allow_users_reset,
            'maintenance': servicePool.isInMaintenance(),
            'not_accesible': not servicePool.isAccessAllowed(),
            'in_use': svr.in_use,
            'to_be_replaced':
            False,  # Manually assigned will not be autoremoved never
            'comments': servicePool.comments,
        })

    logger.debug(services)

    # Now generic user service
    for svr in availServices:
        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if typeTrans is None:  # This may happen if we "remove" a transport type but we have a transport of that kind on DB
                continue
            if t.validForIp(request.ip) and typeTrans.supportsOs(
                    os['OS']) and t.validForOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink',
                                   args=('F' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'F' + svr.uuid, t.uuid)
                trans.append({'id': t.uuid, 'name': t.name, 'link': link})
        if svr.image is not None:
            imageId = svr.image.uuid
        else:
            imageId = 'x'

        # Locate if user service has any already assigned user service for this
        ads = UserServiceManager.manager().getExistingAssignationForUser(
            svr, request.user)
        if ads is None:
            in_use = False
        else:
            in_use = ads.in_use

        group = svr.servicesPoolGroup.as_dict if svr.servicesPoolGroup is not None else ServicesPoolGroup.default(
        ).as_dict

        tbr = svr.toBeReplaced()
        if tbr is not None:
            tbr = formats.date_format(tbr, "SHORT_DATETIME_FORMAT")
            tbrt = ugettext(
                'This service is about to be replaced by a new version. Please, close the session before {} and save all your work to avoid loosing it.'
            ).format(tbr)
        else:
            tbrt = ''

        services.append({
            'id': 'F' + svr.uuid,
            'name': svr.name,
            'visual_name': svr.visual_name,
            'description': svr.comments,
            'group': group,
            'transports': trans,
            'imageId': imageId,
            'show_transports': svr.show_transports,
            'allow_users_remove': svr.allow_users_remove,
            'allow_users_reset': svr.allow_users_reset,
            'maintenance': svr.isInMaintenance(),
            'not_accesible': not svr.isAccessAllowed(),
            'in_use': in_use,
            'to_be_replaced': tbr,
            'to_be_replaced_text': tbrt,
            'comments': svr.comments,
        })

    logger.debug('Services: {0}'.format(services))

    services = sorted(services, key=lambda s: s['name'].upper())

    autorun = False
    if len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.getBool(
            True) and len(services[0]['transports']) > 0:
        if request.session.get('autorunDone', '0') == '0':
            request.session['autorunDone'] = '1'
            autorun = True
            # return redirect('uds.web.views.service', idService=services[0]['id'], idTransport=services[0]['transports'][0]['id'])

    # List of services groups
    allGroups = [
        v for v in sorted([ser['group'] for ser in services],
                          key=lambda s: s['priority'])
    ]
    # Now remove duplicates
    groups = []
    already = []
    for g in allGroups:
        if g['name'] not in already:
            already.append(g['name'])
            groups.append(g)

    logger.debug('Groups: {}'.format(groups))

    response = render(
        request, theme.template('index.html'), {
            'groups': groups,
            'services': services,
            'ip': request.ip,
            'nets': nets,
            'transports': validTrans,
            'autorun': autorun
        })
    return response
Beispiel #2
0
def index(request):
    '''
    Renders the main page.
    :param request: http request
    '''
    # Session data
    os = request.os

    # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
    groups = list(request.user.getGroups())
    availServices = DeployedService.getDeployedServicesForGroups(groups)
    availUserServices = UserService.getUserAssignedServices(request.user)

    # Information for administrators
    nets = ''
    validTrans = ''

    logger.debug('OS: {0}'.format(os['OS']))

    if request.user.isStaff():
        nets = ','.join([n.name for n in Network.networksFor(request.ip)])
        tt = []
        for t in Transport.objects.all():
            if t.validForIp(request.ip):
                tt.append(t.name)
        validTrans = ','.join(tt)

    # Extract required data to show to user
    services = []
    # Select assigned user services
    for svr in availUserServices:
        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink',
                                   args=('A' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'A' + svr.uuid, t.uuid)
                trans.append({'id': t.uuid, 'name': t.name, 'link': link})
        if svr.deployed_service.image is not None:
            imageId = svr.deployed_service.image.uuid
        else:
            imageId = 'x'  # Invalid

        services.append({
            'id': 'A' + svr.uuid,
            'name': svr['name'],
            'transports': trans,
            'imageId': imageId,
            'show_transports': svr.deployed_service.show_transports,
            'maintenance':
            svr.deployed_service.service.provider.maintenance_mode,
            'in_use': svr.in_use,
        })

    logger.debug(services)

    # Now generic user service
    for svr in availServices:
        # Generate ticket

        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink',
                                   args=('F' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'F' + svr.uuid, t.uuid)
                trans.append({'id': t.uuid, 'name': t.name, 'link': link})
        if svr.image is not None:
            imageId = svr.image.uuid
        else:
            imageId = 'x'

        # Locate if user service has any already assigned user service for this
        ads = UserServiceManager.manager().getExistingAssignationForUser(
            svr, request.user)
        if ads is None:
            in_use = False
        else:
            in_use = ads.in_use

        services.append({
            'id': 'F' + svr.uuid,
            'name': svr.name,
            'transports': trans,
            'imageId': imageId,
            'show_transports': svr.show_transports,
            'maintenance': svr.service.provider.maintenance_mode,
            'in_use': in_use,
        })

    logger.debug('Services: {0}'.format(services))

    services = sorted(services, key=lambda s: s['name'].upper())

    if len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.get(
            True) == '1' and len(services[0]['transports']) > 0:
        if request.session.get('autorunDone', '0') == '0':
            request.session['autorunDone'] = '1'
            # TODO: Make this to redirect to uds link directly
            return redirect('uds.web.views.service',
                            idService=services[0]['id'],
                            idTransport=services[0]['transports'][0]['id'])

    response = render_to_response(theme.template('index.html'), {
        'services': services,
        'ip': request.ip,
        'nets': nets,
        'transports': validTrans,
    },
                                  context_instance=RequestContext(request))
    return response
Beispiel #3
0
def getServicesData(
    request: 'ExtendedHttpRequestWithUser',
) -> typing.Dict[str, typing.Any]:  # pylint: disable=too-many-locals, too-many-branches, too-many-statements
    """Obtains the service data dictionary will all available services for this request

    Arguments:
        request {ExtendedHttpRequest} -- request from where to xtract credentials

    Returns:
        typing.Dict[str, typing.Any] --  Keys has this:
            'services': services,
            'ip': request.ip,
            'nets': nets,
            'transports': validTrans,
            'autorun': autorun

    """
    # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
    groups = list(request.user.getGroups())
    availServicePools = list(
        ServicePool.getDeployedServicesForGroups(
            groups,
            request.user))  # Pass in user to get "number_assigned" to optimize
    availMetaPools = list(MetaPool.getForGroups(
        groups,
        request.user))  # Pass in user to get "number_assigned" to optimize
    now = getSqlDatetime()

    # Information for administrators
    nets = ''
    validTrans = ''

    osName = request.os['OS']
    logger.debug('OS: %s', osName)

    if request.user.isStaff():
        nets = ','.join([n.name for n in Network.networksFor(request.ip)])
        tt = []
        t: Transport
        for t in Transport.objects.all().prefetch_related('networks'):
            if t.validForIp(request.ip):
                tt.append(t.name)
        validTrans = ','.join(tt)

    logger.debug('Checking meta pools: %s', availMetaPools)
    services = []

    # Metapool helpers
    def transportIterator(member) -> typing.Iterable[Transport]:
        for t in member.pool.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if (typeTrans and t.validForIp(request.ip)
                    and typeTrans.supportsOs(osName) and t.validForOs(osName)):
                yield t

    def buildMetaTransports(
        transports: typing.Iterable[Transport],
        isLabel: bool,
    ) -> typing.List[typing.Mapping[str, typing.Any]]:
        idd = lambda i: i.uuid if not isLabel else 'LABEL:' + i.label
        return [{
            'id': idd(i),
            'name': i.name,
            'link': html.udsAccessLink(request, 'M' + meta.uuid, idd(i)),
            'priority': 0,
        } for i in transports]

    # Preload all assigned user services for this user
    # Add meta pools data first
    for meta in availMetaPools:
        # Check that we have access to at least one transport on some of its children
        metaTransports: typing.List[typing.Mapping[str, typing.Any]] = []
        in_use = meta.number_in_use > 0  # type: ignore # anotated value

        inAll: typing.Optional[typing.Set[str]] = None
        tmpSet: typing.Set[str]
        if (meta.transport_grouping == MetaPool.COMMON_TRANSPORT_SELECT
            ):  # If meta.use_common_transports
            # only keep transports that are in ALL members
            for member in meta.members.all().order_by('priority'):
                tmpSet = set()
                # if first pool, get all its transports and check that are valid
                for t in transportIterator(member):
                    if inAll is None:
                        tmpSet.add(t.uuid)
                    elif t.uuid in inAll:  # For subsequent, reduce...
                        tmpSet.add(t.uuid)

                inAll = tmpSet
            # tmpSet has ALL common transports
            metaTransports = buildMetaTransports(
                Transport.objects.filter(uuid__in=inAll or []), isLabel=False)
        elif meta.transport_grouping == MetaPool.LABEL_TRANSPORT_SELECT:
            ltrans: typing.MutableMapping[str, Transport] = {}
            for member in meta.members.all().order_by('priority'):
                tmpSet = set()
                # if first pool, get all its transports and check that are valid
                for t in transportIterator(member):
                    if not t.label:
                        continue
                    if t.label not in ltrans or ltrans[
                            t.label].priority > t.priority:
                        ltrans[t.label] = t
                    if inAll is None:
                        tmpSet.add(t.label)
                    elif t.label in inAll:  # For subsequent, reduce...
                        tmpSet.add(t.label)

                inAll = tmpSet
            # tmpSet has ALL common transports
            metaTransports = buildMetaTransports(
                (v for k, v in ltrans.items() if k in (inAll or set())),
                isLabel=True)
        else:
            for member in meta.members.all():
                # if pool.isInMaintenance():
                #    continue
                for t in member.pool.transports.all():
                    typeTrans = t.getType()
                    if (typeTrans and t.validForIp(request.ip)
                            and typeTrans.supportsOs(osName)
                            and t.validForOs(osName)):
                        metaTransports = [{
                            'id':
                            'meta',
                            'name':
                            'meta',
                            'link':
                            html.udsAccessLink(request, 'M' + meta.uuid, None),
                            'priority':
                            0,
                        }]
                        break

                # if not in_use and meta.number_in_use:  # Only look for assignation on possible used
                #     assignedUserService = userServiceManager().getExistingAssignationForUser(pool, request.user)
                #     if assignedUserService:
                #         in_use = assignedUserService.in_use

                # Stop when 1 usable pool is found (metaTransports is filled)
                if metaTransports:
                    break

        # If no usable pools, this is not visible
        if metaTransports:
            group = (meta.servicesPoolGroup.as_dict if meta.servicesPoolGroup
                     else ServicePoolGroup.default().as_dict)

            services.append({
                'id': 'M' + meta.uuid,
                'name': meta.name,
                'visual_name': meta.visual_name,
                'description': meta.comments,
                'group': group,
                'transports': metaTransports,
                'imageId': meta.image and meta.image.uuid or 'x',
                'show_transports': len(metaTransports) > 1,
                'allow_users_remove': False,
                'allow_users_reset': False,
                'maintenance': meta.isInMaintenance(),
                'not_accesible': not meta.isAccessAllowed(now),
                'in_use': in_use,
                'to_be_replaced': None,
                'to_be_replaced_text': '',
                'custom_calendar_text': meta.calendar_message,
            })

    # Now generic user service
    for sPool in availServicePools:
        # Skip pools that are part of meta pools
        if sPool.owned_by_meta:
            continue

        use_percent = str(sPool.usage(
            sPool.usage_count)) + '%'  # type: ignore # anotated value
        use_count = str(sPool.usage_count)  # type: ignore # anotated value
        left_count = str(sPool.max_srvs -
                         sPool.usage_count)  # type: ignore # anotated value

        trans: typing.List[typing.MutableMapping[str, typing.Any]] = []
        for t in sorted(
                sPool.transports.all(), key=lambda x: x.priority
        ):  # In memory sort, allows reuse prefetched and not too big array
            try:
                typeTrans = t.getType()
            except Exception:
                continue
            if (t.validForIp(request.ip) and typeTrans.supportsOs(osName)
                    and t.validForOs(osName)):
                if typeTrans.ownLink:
                    link = reverse('TransportOwnLink',
                                   args=('F' + sPool.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'F' + sPool.uuid,
                                              t.uuid)
                trans.append({
                    'id': t.uuid,
                    'name': t.name,
                    'link': link,
                    'priority': t.priority
                })

        # If empty transports, do not include it on list
        if not trans:
            continue

        if sPool.image:
            imageId = sPool.image.uuid
        else:
            imageId = 'x'

        # Locate if user service has any already assigned user service for this. Use "pre cached" number of assignations in this pool to optimize
        in_use = typing.cast(typing.Any, sPool).number_in_use > 0
        # if svr.number_in_use:  # Anotated value got from getDeployedServicesForGroups(...). If 0, no assignation for this user
        #     ads = userServiceManager().getExistingAssignationForUser(svr, request.user)
        #     if ads:
        #         in_use = ads.in_use

        group = (sPool.servicesPoolGroup.as_dict if sPool.servicesPoolGroup
                 else ServicePoolGroup.default().as_dict)

        # Only add toBeReplaced info in case we allow it. This will generate some "overload" on the services
        toBeReplaced = (sPool.toBeReplaced(request.user)
                        if typing.cast(typing.Any, sPool).pubs_active > 0
                        and GlobalConfig.NOTIFY_REMOVAL_BY_PUB.getBool(False)
                        else None)
        # tbr = False
        if toBeReplaced:
            toBeReplaced = formats.date_format(toBeReplaced,
                                               'SHORT_DATETIME_FORMAT')
            toBeReplacedTxt = ugettext(
                'This service is about to be replaced by a new version. Please, close the session before {} and save all your work to avoid loosing it.'
            ).format(toBeReplaced)
        else:
            toBeReplacedTxt = ''

        # Calculate max deployed
        maxDeployed = str(sPool.max_srvs)

        # if sPool.service.getType().usesCache is False:
        #    maxDeployed = sPool.service.getInstance().maxDeployed

        def datator(x) -> str:
            return (x.replace('{use}', use_percent).replace(
                '{total}',
                str(sPool.max_srvs)).replace('{usec}', use_count).replace(
                    '{left}', left_count))

        services.append({
            'id':
            'F' + sPool.uuid,
            'name':
            datator(sPool.name),
            'visual_name':
            datator(
                sPool.visual_name.replace('{use}', use_percent).replace(
                    '{total}', maxDeployed)),
            'description':
            sPool.comments,
            'group':
            group,
            'transports':
            trans,
            'imageId':
            imageId,
            'show_transports':
            sPool.show_transports,
            'allow_users_remove':
            sPool.allow_users_remove,
            'allow_users_reset':
            sPool.allow_users_reset,
            'maintenance':
            sPool.isInMaintenance(),
            'not_accesible':
            not sPool.isAccessAllowed(now),
            'in_use':
            in_use,
            'to_be_replaced':
            toBeReplaced,
            'to_be_replaced_text':
            toBeReplacedTxt,
            'custom_calendar_text':
            sPool.calendar_message,
        })

    # logger.debug('Services: %s', services)

    # Sort services and remove services with no transports...
    services = [
        s for s in sorted(services, key=lambda s: s['name'].upper())
        if s['transports']
    ]

    autorun = False
    if (len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.getBool(False)
            and services[0]['transports']):
        if request.session.get('autorunDone', '0') == '0':
            request.session['autorunDone'] = '1'
            autorun = True

    return {
        'services': services,
        'ip': request.ip,
        'nets': nets,
        'transports': validTrans,
        'autorun': autorun
    }
Beispiel #4
0
def index(request):
    '''
    Renders the main page.
    :param request: http request
    '''
    # Session data
    os = request.os

    # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
    groups = list(request.user.getGroups())
    availServices = DeployedService.getDeployedServicesForGroups(groups)
    availUserServices = UserService.getUserAssignedServices(request.user)

    # Information for administrators
    nets = ''
    validTrans = ''

    logger.debug('OS: {0}'.format(os['OS']))

    if request.user.isStaff():
        nets = ','.join([n.name for n in Network.networksFor(request.ip)])
        tt = []
        for t in Transport.objects.all():
            if t.validForIp(request.ip):
                tt.append(t.name)
        validTrans = ','.join(tt)

    # Extract required data to show to user
    services = []
    # Select assigned user services
    for svr in availUserServices:
        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink', args=('A' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'A' + svr.uuid, t.uuid)
                trans.append(
                    {
                        'id': t.uuid,
                        'name': t.name,
                        'link': link
                    }
                )
        if svr.deployed_service.image is not None:
            imageId = svr.deployed_service.image.uuid
        else:
            imageId = 'x'  # Invalid

        services.append({
            'id': 'A' + svr.uuid,
            'name': svr['name'],
            'transports': trans,
            'imageId': imageId,
            'show_transports': svr.deployed_service.show_transports,
            'maintenance': svr.deployed_service.service.provider.maintenance_mode,
            'in_use': svr.in_use,
        })

    logger.debug(services)

    # Now generic user service
    for svr in availServices:
        # Generate ticket

        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink', args=('F' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'F' + svr.uuid, t.uuid)
                trans.append(
                    {
                        'id': t.uuid,
                        'name': t.name,
                        'link': link
                    }
                )
        if svr.image is not None:
            imageId = svr.image.uuid
        else:
            imageId = 'x'

        # Locate if user service has any already assigned user service for this
        ads = UserServiceManager.manager().getExistingAssignationForUser(svr, request.user)
        if ads is None:
            in_use = False
        else:
            in_use = ads.in_use

        services.append({
            'id': 'F' + svr.uuid,
            'name': svr.name,
            'transports': trans,
            'imageId': imageId,
            'show_transports': svr.show_transports,
            'maintenance': svr.service.provider.maintenance_mode,
            'in_use': in_use,
        })

    logger.debug('Services: {0}'.format(services))

    services = sorted(services, key=lambda s: s['name'].upper())

    if len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.get(True) == '1' and len(services[0]['transports']) > 0:
        if request.session.get('autorunDone', '0') == '0':
            request.session['autorunDone'] = '1'
            # TODO: Make this to redirect to uds link directly
            return redirect('uds.web.views.service', idService=services[0]['id'], idTransport=services[0]['transports'][0]['id'])

    response = render_to_response(
        theme.template('index.html'),
        {
            'services': services,
            'ip': request.ip,
            'nets': nets,
            'transports': validTrans,
        },
        context_instance=RequestContext(request)
    )
    return response
Beispiel #5
0
def getServicesData(request: 'HttpRequest') -> typing.Dict[str, typing.Any]:  # pylint: disable=too-many-locals, too-many-branches, too-many-statements
    """Obtains the service data dictionary will all available services for this request

    Arguments:
        request {HttpRequest} -- request from where to xtract credentials

    Returns:
        typing.Dict[str, typing.Any] --  Keys has this:
            'services': services,
            'ip': request.ip,
            'nets': nets,
            'transports': validTrans,
            'autorun': autorun

    """
    # Session data
    os: typing.Dict[str, str] = request.os

    # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
    groups = list(request.user.getGroups())
    availServicePools = ServicePool.getDeployedServicesForGroups(groups)
    availMetaPools = MetaPool.getForGroups(groups)

    # Information for administrators
    nets = ''
    validTrans = ''

    logger.debug('OS: %s', os['OS'])

    if request.user.isStaff():
        nets = ','.join([n.name for n in Network.networksFor(request.ip)])
        tt = []
        for t in Transport.objects.all():
            if t.validForIp(request.ip):
                tt.append(t.name)
        validTrans = ','.join(tt)

    logger.debug('Checking meta pools: %s', availMetaPools)
    services = []
    # Add meta pools data first
    for meta in availMetaPools:
        # Check that we have access to at least one transport on some of its children
        hasUsablePools = False
        in_use = False
        for pool in meta.pools.all():
            # if pool.isInMaintenance():
            #    continue
            for t in pool.transports.all():
                typeTrans = t.getType()
                if t.getType() and t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']) and t.validForOs(os['OS']):
                    hasUsablePools = True
                    break

            if not in_use:
                assignedUserService = userServiceManager().getExistingAssignationForUser(pool, request.user)
                if assignedUserService:
                    in_use = assignedUserService.in_use

            # Stop when 1 usable pool is found
            if hasUsablePools:
                break

        # If no usable pools, this is not visible
        if hasUsablePools:
            group = meta.servicesPoolGroup.as_dict if meta.servicesPoolGroup else ServicePoolGroup.default().as_dict

            services.append({
                'id': 'M' + meta.uuid,
                'name': meta.name,
                'visual_name': meta.visual_name,
                'description': meta.comments,
                'group': group,
                'transports': [{
                    'id': 'meta',
                    'name': 'meta',
                    'link': html.udsMetaLink(request, 'M' + meta.uuid),
                    'priority': 0
                }],
                'imageId': meta.image and meta.image.uuid or 'x',
                'show_transports': False,
                'allow_users_remove': False,
                'allow_users_reset': False,
                'maintenance': meta.isInMaintenance(),
                'not_accesible': not meta.isAccessAllowed(),
                'in_use': in_use,
                'to_be_replaced': None,
                'to_be_replaced_text': '',
            })

    # Now generic user service
    for svr in availServicePools:
        # Skip pools that are part of meta pools
        if svr.is_meta:
            continue

        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if typeTrans is None:  # This may happen if we "remove" a transport type but we have a transport of that kind on DB
                continue
            if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']) and t.validForOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink', args=('F' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'F' + svr.uuid, t.uuid)
                trans.append(
                    {
                        'id': t.uuid,
                        'name': t.name,
                        'link': link,
                        'priority': t.priority
                    }
                )

        # If empty transports, do not include it on list
        if not trans:
            continue

        if svr.image is not None:
            imageId = svr.image.uuid
        else:
            imageId = 'x'

        # Locate if user service has any already assigned user service for this
        ads = userServiceManager().getExistingAssignationForUser(svr, request.user)
        if ads is None:
            in_use = False
        else:
            in_use = ads.in_use

        group = svr.servicesPoolGroup.as_dict if svr.servicesPoolGroup else ServicePoolGroup.default().as_dict

        tbr = svr.toBeReplaced(request.user)
        if tbr:
            tbr = formats.date_format(tbr, "SHORT_DATETIME_FORMAT")
            tbrt = ugettext('This service is about to be replaced by a new version. Please, close the session before {} and save all your work to avoid loosing it.').format(tbr)
        else:
            tbrt = ''

        services.append({
            'id': 'F' + svr.uuid,
            'name': svr.name,
            'visual_name': svr.visual_name,
            'description': svr.comments,
            'group': group,
            'transports': trans,
            'imageId': imageId,
            'show_transports': svr.show_transports,
            'allow_users_remove': svr.allow_users_remove,
            'allow_users_reset': svr.allow_users_reset,
            'maintenance': svr.isInMaintenance(),
            'not_accesible': not svr.isAccessAllowed(),
            'in_use': in_use,
            'to_be_replaced': tbr,
            'to_be_replaced_text': tbrt,
        })

    logger.debug('Services: %s', services)

    # Sort services and remove services with no transports...
    services = [s for s in sorted(services, key=lambda s: s['name'].upper()) if s['transports']]

    autorun = False
    if len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.getBool(True) and services[0]['transports']:
        if request.session.get('autorunDone', '0') == '0':
            request.session['autorunDone'] = '1'
            autorun = True
            # return redirect('uds.web.views.service', idService=services[0]['id'], idTransport=services[0]['transports'][0]['id'])

    return {
        'services': services,
        'ip': request.ip,
        'nets': nets,
        'transports': validTrans,
        'autorun': autorun
    }
Beispiel #6
0
def udsJs(request: 'HttpRequest') -> str:
    auth_host = request.META.get('HTTP_HOST') or request.META.get(
        'SERVER_NAME'
    ) or 'auth_host'  # Last one is a placeholder in case we can't locate host name

    profile = {
        'user': None if not request.user else request.user.name,
        'role':
        'staff' if request.user and request.user.staff_member else 'user',
    }

    # Gets csrf token
    csrf_token = csrf.get_token(request)
    if csrf_token is not None:
        csrf_token = str(csrf_token)

    tag = request.session.get('tag', None)

    if GlobalConfig.DISALLOW_GLOBAL_LOGIN.getBool(False) is True:
        try:
            authenticators = [Authenticator.objects.get(small_name=auth_host)]
        except Exception:
            try:
                authenticators = [
                    Authenticator.objects.order_by('priority')[0].small_name
                ]
            except Exception:  # There is no authenticators yet...
                authenticators = []
    else:
        authenticators = Authenticator.objects.all().exclude(visible=False)

    if tag:
        authenticators = [x for x in authenticators if x.small_name == tag]

    # the auths for client
    def getAuthInfo(auth: Authenticator):
        theType = auth.getType()
        return {
            'id': auth.uuid,
            'name': auth.name,
            'label': auth.small_name,
            'priority': auth.priority,
            'is_custom': theType.isCustom()
        }

    config = {
        'version':
        VERSION,
        'version_stamp':
        VERSION_STAMP,
        'language':
        get_language(),
        'available_languages': [{
            'id': k,
            'name': gettext(v)
        } for k, v in settings.LANGUAGES],
        'authenticators':
        [getAuthInfo(auth) for auth in authenticators if auth.getType()],
        'os':
        request.os['OS'],
        'csrf_field':
        CSRF_FIELD,
        'csrf':
        csrf_token,
        'image_size':
        Image.MAX_IMAGE_SIZE,
        'experimental_features':
        GlobalConfig.EXPERIMENTAL_FEATURES.getBool(),
        'reload_time':
        GlobalConfig.RELOAD_TIME.getInt(True),
        'site_name':
        GlobalConfig.SITE_NAME.get(),
        'site_copyright_info':
        GlobalConfig.SITE_COPYRIGHT.get(),
        'site_copyright_link':
        GlobalConfig.SITE_COPYRIGHT_LINK.get(),
        'site_logo_name':
        GlobalConfig.SITE_LOGO_NAME.get(),
        'messages': {
            # Calendar denied message
            'calendarDenied':
            GlobalConfig.LIMITED_BY_CALENDAR_TEXT.get().strip()
            or gettext('Access limited by calendar')
        },
        'urls': {
            'changeLang':
            reverse('set_language'),
            'login':
            reverse('page.login'),
            'logout':
            reverse('page.logout'),
            'user':
            reverse('page.index'),
            'customAuth':
            reverse('uds.web.views.customAuth', kwargs={'idAuth': ''}),
            'services':
            reverse('webapi.services'),
            'enabler':
            reverse('webapi.enabler',
                    kwargs={
                        'idService': 'param1',
                        'idTransport': 'param2'
                    }),
            'action':
            reverse('webapi.action',
                    kwargs={
                        'idService': 'param1',
                        'actionString': 'param2'
                    }),
            'galleryImage':
            reverse('webapi.galleryImage', kwargs={'idImage': 'param1'}),
            'transportIcon':
            reverse('webapi.transportIcon', kwargs={'idTrans': 'param1'}),
            'static':
            static(''),
            # Launcher URL if exists
            'launch':
            request.session.get('launch', ''),
        }
    }

    info: typing.Optional[typing.MutableMapping] = None
    if request.user and request.user.isStaff():
        info = {
            'networks': [n.name for n in Network.networksFor(request.ip)],
            'transports': [
                t.name for t in Transport.objects.all()
                if t.validForIp(request.ip)
            ],
            'ip':
            request.ip,
            'ip_proxy':
            request.ip_proxy
        }

    # all plugins are under url clients...
    plugins = [{
        'url': static('clients/' + url.format(version=CLIENT_VERSION)),
        'description': description,
        'name': name
    } for url, description, name in (
        ('UDSClientSetup-{version}.exe', gettext('Windows client'), 'Windows'),
        ('UDSClient-{version}.pkg', gettext('Mac OS X client'), 'MacOS'),
        ('udsclient3_{version}_all.deb', gettext('Debian based Linux client') +
         ' ' + gettext('(requires Python-3.6 or newer)'),
         'Linux'), ('udsclient_{version}_all.deb',
                    gettext('Debian based Python 2.7 Linux client (legacy)') +
                    ' ' + gettext('(requires Python-2.7)'), 'Linux'),
        ('udsclient-{version}-1.noarch.rpm',
         gettext('Red Hat based Linux client (RH, Fedora, Centos, ...)') +
         ' ' + gettext('(requires Python-2.7)'),
         'Linux'), ('udsclient-opensuse-{version}-1.noarch.rpm',
                    gettext('Suse based Linux client') + ' ' +
                    gettext('(requires Python-2.7)'),
                    'Linux'), ('udsclient-{version}.tar.gz',
                               gettext('Generic .tar.gz Linux client') + ' ' +
                               gettext('(requires Python-2.7)'), 'Linux'))]

    actors: typing.List[typing.Dict[str, str]] = []

    if profile['role'] == 'staff':  # Add staff things
        # If is admin (informational, REST api checks users privileges anyway...)
        profile['admin'] = True
        # REST auth
        config['auth_token'] = request.session.session_key
        config['auth_header'] = AUTH_TOKEN_HEADER
        # Actors
        actors = [{
            'url':
            reverse('utility.downloader', kwargs={'idDownload': key}),
            'name':
            val['name'],
            'description':
            gettext(val['comment'])
        } for key, val in downloadsManager().getDownloadables().items()]
        # URLS
        config['urls']['admin'] = reverse('uds.admin.views.index')
        config['urls']['rest'] = reverse('REST', kwargs={'arguments': ''})

    errors: typing.List = []
    if 'errors' in request.session:
        errors = request.session['errors']
        del request.session['errors']
        request.session.modified = True  # Ensure saves it

    uds = {
        'profile': profile,
        'config': config,
        'info': info,
        'plugins': plugins,
        'actors': actors,
        'errors': errors,
        'data': request.session.get('data')
    }

    # Reset some 1 time values...
    request.session['launch'] = ''

    return 'var udsData = ' + json.dumps(uds) + ';\n'
Beispiel #7
0
def getServicesData(request: 'HttpRequest') -> typing.Dict[str, typing.Any]:  # pylint: disable=too-many-locals, too-many-branches, too-many-statements
    """Obtains the service data dictionary will all available services for this request

    Arguments:
        request {HttpRequest} -- request from where to xtract credentials

    Returns:
        typing.Dict[str, typing.Any] --  Keys has this:
            'services': services,
            'ip': request.ip,
            'nets': nets,
            'transports': validTrans,
            'autorun': autorun

    """
    # Session data
    os: typing.Dict[str, str] = request.os

    # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
    groups = list(request.user.getGroups())
    availServicePools = list(
        ServicePool.getDeployedServicesForGroups(
            groups,
            request.user))  # Pass in user to get "number_assigned" to optimize
    availMetaPools = list(MetaPool.getForGroups(
        groups,
        request.user))  # Pass in user to get "number_assigned" to optimize
    now = getSqlDatetime()

    # Information for administrators
    nets = ''
    validTrans = ''

    logger.debug('OS: %s', os['OS'])

    if request.user.isStaff():
        nets = ','.join([n.name for n in Network.networksFor(request.ip)])
        tt = []
        t: Transport
        for t in Transport.objects.all().prefetch_related('networks'):
            if t.validForIp(request.ip):
                tt.append(t.name)
        validTrans = ','.join(tt)

    logger.debug('Checking meta pools: %s', availMetaPools)
    services = []
    meta: MetaPool
    # Preload all assigned user services for this user

    # Add meta pools data first
    for meta in availMetaPools:
        # Check that we have access to at least one transport on some of its children
        hasUsablePools = False
        in_use = meta.number_in_use > 0  # False
        for pool in meta.pools.all():
            # if pool.isInMaintenance():
            #    continue
            for t in pool.transports.all():
                typeTrans = t.getType()
                if t.getType() and t.validForIp(
                        request.ip) and typeTrans.supportsOs(
                            os['OS']) and t.validForOs(os['OS']):
                    hasUsablePools = True
                    break

            # if not in_use and meta.number_in_use:  # Only look for assignation on possible used
            #     assignedUserService = userServiceManager().getExistingAssignationForUser(pool, request.user)
            #     if assignedUserService:
            #         in_use = assignedUserService.in_use

            # Stop when 1 usable pool is found
            if hasUsablePools:
                break

        # If no usable pools, this is not visible
        if hasUsablePools:
            group = meta.servicesPoolGroup.as_dict if meta.servicesPoolGroup else ServicePoolGroup.default(
            ).as_dict

            services.append({
                'id':
                'M' + meta.uuid,
                'name':
                meta.name,
                'visual_name':
                meta.visual_name,
                'description':
                meta.comments,
                'group':
                group,
                'transports': [{
                    'id':
                    'meta',
                    'name':
                    'meta',
                    'link':
                    html.udsMetaLink(request, 'M' + meta.uuid),
                    'priority':
                    0
                }],
                'imageId':
                meta.image and meta.image.uuid or 'x',
                'show_transports':
                False,
                'allow_users_remove':
                False,
                'allow_users_reset':
                False,
                'maintenance':
                meta.isInMaintenance(),
                'not_accesible':
                not meta.isAccessAllowed(now),
                'in_use':
                in_use,
                'to_be_replaced':
                None,
                'to_be_replaced_text':
                '',
                'custom_calendar_text':
                meta.calendar_message,
            })

    # Now generic user service
    svr: ServicePool
    for svr in availServicePools:
        # Skip pools that are part of meta pools
        if svr.is_meta:
            continue

        use = str(svr.usage(svr.usage_count)) + '%'

        trans = []
        for t in sorted(
                svr.transports.all(), key=lambda x: x.priority
        ):  # In memory sort, allows reuse prefetched and not too big array
            try:
                typeTrans = t.getType()
            except Exception:
                continue
            if t.validForIp(request.ip) and typeTrans.supportsOs(
                    os['OS']) and t.validForOs(os['OS']):
                if typeTrans.ownLink:
                    link = reverse('TransportOwnLink',
                                   args=('F' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'F' + svr.uuid, t.uuid)
                trans.append({
                    'id': t.uuid,
                    'name': t.name,
                    'link': link,
                    'priority': t.priority
                })

        # If empty transports, do not include it on list
        if not trans:
            continue

        if svr.image:
            imageId = svr.image.uuid
        else:
            imageId = 'x'

        # Locate if user service has any already assigned user service for this. Use "pre cached" number of assignations in this pool to optimize
        in_use = svr.number_in_use > 0
        # if svr.number_in_use:  # Anotated value got from getDeployedServicesForGroups(...). If 0, no assignation for this user
        #     ads = userServiceManager().getExistingAssignationForUser(svr, request.user)
        #     if ads:
        #         in_use = ads.in_use

        group = svr.servicesPoolGroup.as_dict if svr.servicesPoolGroup else ServicePoolGroup.default(
        ).as_dict

        # Only add toBeReplaced info in case we allow it. This will generate some "overload" on the services
        toBeReplaced = svr.toBeReplaced(
            request.user
        ) if svr.pubs_active > 0 and GlobalConfig.NOTIFY_REMOVAL_BY_PUB.getBool(
            False) else None
        # tbr = False
        if toBeReplaced:
            toBeReplaced = formats.date_format(toBeReplaced,
                                               "SHORT_DATETIME_FORMAT")
            toBeReplacedTxt = ugettext(
                'This service is about to be replaced by a new version. Please, close the session before {} and save all your work to avoid loosing it.'
            ).format(toBeReplaced)
        else:
            toBeReplacedTxt = ''

        datator = lambda x: x.replace('{use}', use).replace(
            '{total}', str(svr.max_srvs))

        services.append({
            'id':
            'F' + svr.uuid,
            'name':
            datator(svr.name),
            'visual_name':
            datator(
                svr.visual_name.replace('{use}',
                                        use).replace('{total}',
                                                     str(svr.max_srvs))),
            'description':
            svr.comments,
            'group':
            group,
            'transports':
            trans,
            'imageId':
            imageId,
            'show_transports':
            svr.show_transports,
            'allow_users_remove':
            svr.allow_users_remove,
            'allow_users_reset':
            svr.allow_users_reset,
            'maintenance':
            svr.isInMaintenance(),
            'not_accesible':
            not svr.isAccessAllowed(now),
            'in_use':
            in_use,
            'to_be_replaced':
            toBeReplaced,
            'to_be_replaced_text':
            toBeReplacedTxt,
            'custom_calendar_text':
            svr.calendar_message,
        })

    # logger.debug('Services: %s', services)

    # Sort services and remove services with no transports...
    services = [
        s for s in sorted(services, key=lambda s: s['name'].upper())
        if s['transports']
    ]

    autorun = False
    if len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.getBool(
            False) and services[0]['transports']:
        if request.session.get('autorunDone', '0') == '0':
            request.session['autorunDone'] = '1'
            autorun = True
            # return redirect('uds.web.views.service', idService=services[0]['id'], idTransport=services[0]['transports'][0]['id'])

    return {
        'services': services,
        'ip': request.ip,
        'nets': nets,
        'transports': validTrans,
        'autorun': autorun
    }
Beispiel #8
0
def udsJs(request: 'ExtendedHttpRequest') -> str:
    auth_host = request.META.get('HTTP_HOST') or request.META.get(
        'SERVER_NAME'
    ) or 'auth_host'  # Last one is a placeholder in case we can't locate host name

    role: str = 'user'
    user: typing.Optional['User'] = request.user

    if user:
        role = 'staff' if user.isStaff(
        ) and not user.is_admin else 'admin' if user.is_admin else 'user'
        if request.session.get('restricted', False):
            role = 'restricted'

    profile: typing.Dict[str, typing.Any] = {
        'user': user.name if user else None,
        'role': role,
    }

    # Gets csrf token
    csrf_token = csrf.get_token(request)
    if csrf_token is not None:
        csrf_token = str(csrf_token)

    tag = request.session.get('tag', None)
    logger.debug('Tag config: %s', tag)
    if GlobalConfig.DISALLOW_GLOBAL_LOGIN.getBool():
        try:
            # Get authenticators with auth_host or tag. If tag is None, auth_host, if exists
            # tag, later will remove "auth_host"
            authenticators = Authenticator.objects.filter(
                small_name__in=[auth_host, tag])[:]
        except Exception as e:
            authenticators = []
    else:
        authenticators = Authenticator.objects.all().exclude(visible=False)

    # logger.debug('Authenticators PRE: %s', authenticators)

    if tag and authenticators:  # Refilter authenticators, visible and with this tag if required
        authenticators = [
            x for x in authenticators if x.small_name == tag or (
                tag == 'disabled' and x.getType().isCustom() is False)
        ]

    if not authenticators:
        try:
            authenticators = [Authenticator.objects.order_by('priority')[0]]
        except Exception:  # There is no authenticators yet...
            authenticators = []

    if not tag and authenticators:
        tag = authenticators[0].small_name

    # logger.debug('Authenticators: %s', authenticators)

    # the auths for client
    def getAuthInfo(auth: Authenticator):
        theType = auth.getType()
        return {
            'id': auth.uuid,
            'name': auth.name,
            'label': auth.small_name,
            'priority': auth.priority,
            'is_custom': theType.isCustom()
        }

    config = {
        'version':
        VERSION,
        'version_stamp':
        VERSION_STAMP,
        'language':
        get_language(),
        'available_languages': [{
            'id': k,
            'name': gettext(v)
        } for k, v in settings.LANGUAGES],
        'authenticators':
        [getAuthInfo(auth) for auth in authenticators if auth.getType()],
        'tag':
        tag,
        'os':
        request.os['OS'],
        'csrf_field':
        CSRF_FIELD,
        'csrf':
        csrf_token,
        'image_size':
        Image.MAX_IMAGE_SIZE,
        'experimental_features':
        GlobalConfig.EXPERIMENTAL_FEATURES.getBool(),
        'reload_time':
        GlobalConfig.RELOAD_TIME.getInt(True),
        'site_name':
        GlobalConfig.SITE_NAME.get(),
        'site_copyright_info':
        GlobalConfig.SITE_COPYRIGHT.get(),
        'site_copyright_link':
        GlobalConfig.SITE_COPYRIGHT_LINK.get(),
        'site_logo_name':
        GlobalConfig.SITE_LOGO_NAME.get(),
        'site_information':
        GlobalConfig.SITE_INFO.get(),
        'site_filter_on_top':
        GlobalConfig.SITE_FILTER_ONTOP.getBool(True),
        'launcher_wait_time':
        5000,
        'messages': {
            # Calendar denied message
            'calendarDenied':
            GlobalConfig.LIMITED_BY_CALENDAR_TEXT.get().strip()
            or gettext('Access limited by calendar')
        },
        'urls': {
            'changeLang':
            reverse('set_language'),
            'login':
            reverse('page.login'),
            'logout':
            reverse('page.logout'),
            'user':
            reverse('page.index'),
            'customAuth':
            reverse('uds.web.views.customAuth', kwargs={'idAuth': ''}),
            'services':
            reverse('webapi.services'),
            'enabler':
            reverse('webapi.enabler',
                    kwargs={
                        'idService': 'param1',
                        'idTransport': 'param2'
                    }),
            'action':
            reverse('webapi.action',
                    kwargs={
                        'idService': 'param1',
                        'actionString': 'param2'
                    }),
            'galleryImage':
            reverse('webapi.galleryImage', kwargs={'idImage': 'param1'}),
            'transportIcon':
            reverse('webapi.transportIcon', kwargs={'idTrans': 'param1'}),
            'static':
            static(''),
            # Launcher URL if exists
            'launch':
            request.session.get('launch', ''),
        }
    }

    info: typing.Optional[typing.MutableMapping] = None
    if user and user.isStaff():
        info = {
            'networks': [n.name for n in Network.networksFor(request.ip)],
            'transports': [
                t.name for t in Transport.objects.all()
                if t.validForIp(request.ip)
            ],
            'ip':
            request.ip,
            'ip_proxy':
            request.ip_proxy
        }

    # all plugins are under url clients...
    plugins = [{
        'url': static('clients/' + url.format(version=CLIENT_VERSION)),
        'description': description,
        'name': name,
        'legacy': legacy,
    } for url, description, name, legacy in (
        ('UDSClientSetup-{version}.exe', gettext('Windows client'), 'Windows',
         False),
        ('UDSClient-{version}.pkg', gettext('Mac OS X client'), 'MacOS',
         False),
        ('udsclient3_{version}_all.deb', gettext('Debian based Linux client') +
         ' ' + gettext('(requires Python-3.6 or newer)'), 'Linux', False),
        ('udsclient3-{version}-1.noarch.rpm',
         gettext('RPM based Linux client (Fedora, Suse, ...)') + ' ' +
         gettext('(requires Python-3.6 or newer)'), 'Linux', False),
        ('udsclient3-{version}.tar.gz',
         gettext('Generic .tar.gz Linux client') + ' ' +
         gettext('(requires Python-3.6 or newer)'), 'Linux', False),
        ('udsclient_{version}_all.deb',
         gettext('Legacy Debian based Python 2.7 Linux client') + ' ' +
         gettext('(requires outdated Python-2.7)'), 'Linux', True),
        ('udsclient-{version}-1.noarch.rpm',
         gettext('Legacy RH based Linux client (Fedora, Centos, Suse, ...)') +
         ' ' + gettext('(requires outdated Python-2.7)'), 'Linux', True),
        ('udsclient-opensuse-{version}-1.noarch.rpm',
         gettext('Legacy OpenSuse based Linux client)') + ' ' +
         gettext('(requires outdated Python-2.7)'), 'Linux', True),
    )]

    # We can add here custom downloads with something like this:
    # plugins.append({
    #     'url': 'http://www.google.com/coche.exe',
    #     'description': 'Cliente SPICE for download',  # Text that appears on download
    #     'name': 'Linux', # Can be 'Linux', 'Windows', o 'MacOS'. Sets the icon.
    #     'legacy': False  # True = Gray, False = White
    #})

    actors: typing.List[typing.Dict[str, str]] = []

    if user and user.isStaff():  # Add staff things
        # If is admin (informational, REST api checks users privileges anyway...)
        profile['admin'] = True
        # REST auth
        config['auth_token'] = request.session.session_key
        config['auth_header'] = AUTH_TOKEN_HEADER
        # Actors
        actors = [{
            'url':
            reverse('utility.downloader', kwargs={'idDownload': key}),
            'name':
            val['name'],
            'description':
            gettext(val['comment'])
        } for key, val in downloadsManager().getDownloadables().items()]
        # URLS
        config['urls']['admin'] = reverse('uds.admin.views.index')
        config['urls']['rest'] = reverse('REST', kwargs={'arguments': ''})
        # Admin config
        page_size = GlobalConfig.ADMIN_PAGESIZE.getInt(True)
        # Fix page size to razonable usable values
        page_size = 10 if page_size < 10 else 100 if page_size > 100 else page_size
        config['admin'] = {
            'page_size': page_size,
        }

    errors: typing.List = []
    if 'errors' in request.session:
        errors = request.session['errors']
        del request.session['errors']
        request.session.modified = True  # Ensure saves it

    uds = {
        'profile': profile,
        'config': config,
        'info': info,
        'plugins': plugins,
        'actors': actors,
        'errors': errors,
        'data': request.session.get('data')
    }

    # Reset some 1 time values...
    request.session['launch'] = ''

    return 'var udsData = ' + json.dumps(uds) + ';\n'
Beispiel #9
0
def getServicesData(request):
    # Session data
    os = request.os

    # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
    groups = list(request.user.getGroups())
    availServices = DeployedService.getDeployedServicesForGroups(groups)
    availMetas = MetaPool.getForGroups(groups)

    # Information for administrators
    nets = ''
    validTrans = ''

    logger.debug('OS: {0}'.format(os['OS']))

    if request.user.isStaff():
        nets = ','.join([n.name for n in Network.networksFor(request.ip)])
        tt = []
        for t in Transport.objects.all():
            if t.validForIp(request.ip):
                tt.append(t.name)
        validTrans = ','.join(tt)

    logger.debug('Checking meta pools: %s', availMetas)
    services = []
    # Add meta pools data first
    for meta in availMetas:
        # Check that we have access to at least one transport on some of its children
        hasUsablePools = False
        in_use = False
        for pool in meta.pools.all():
            # if pool.isInMaintenance():
            #    continue
            for t in pool.transports.all():
                typeTrans = t.getType()
                if t.getType() and t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']) and t.validForOs(os['OS']):
                    hasUsablePools = True
                    break

            if not in_use:
                assignedUserService = UserServiceManager.manager().getExistingAssignationForUser(pool, request.user)
                if assignedUserService:
                    in_use = assignedUserService.in_use

            # Stop when 1 usable pool is found
            if hasUsablePools:
                break

        # If no usable pools, this is not visible
        if hasUsablePools:
            group = meta.servicesPoolGroup.as_dict if meta.servicesPoolGroup else ServicesPoolGroup.default().as_dict

            services.append({
                'id': 'M' + meta.uuid,
                'name': meta.name,
                'visual_name': meta.visual_name,
                'description': meta.comments,
                'group': group,
                'transports': [{
                    'id': 'meta',
                    'name': 'meta',
                    'link': html.udsMetaLink(request, 'M' + meta.uuid),
                    'priority': 0
                }],
                'imageId': meta.image and meta.image.uuid or 'x',
                'show_transports': False,
                'allow_users_remove': False,
                'allow_users_reset': False,
                'maintenance': meta.isInMaintenance(),
                'not_accesible': not meta.isAccessAllowed(),
                'in_use': in_use,
                'to_be_replaced': None,
                'to_be_replaced_text': '',
            })

    # Now generic user service
    for svr in availServices:
        # Skip pools that are part of meta pools
        if svr.is_meta:
            continue

        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if typeTrans is None:  # This may happen if we "remove" a transport type but we have a transport of that kind on DB
                continue
            if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']) and t.validForOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink', args=('F' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'F' + svr.uuid, t.uuid)
                trans.append(
                    {
                        'id': t.uuid,
                        'name': t.name,
                        'link': link,
                        'priority': t.priority
                    }
                )

        # If empty transports, do not include it on list
        if not trans:
            continue

        if svr.image is not None:
            imageId = svr.image.uuid
        else:
            imageId = 'x'

        # Locate if user service has any already assigned user service for this
        ads = UserServiceManager.manager().getExistingAssignationForUser(svr, request.user)
        if ads is None:
            in_use = False
        else:
            in_use = ads.in_use

        group = svr.servicesPoolGroup.as_dict if svr.servicesPoolGroup else ServicesPoolGroup.default().as_dict

        tbr = svr.toBeReplaced(request.user)
        if tbr:
            tbr = formats.date_format(tbr, "SHORT_DATETIME_FORMAT")
            tbrt = ugettext('This service is about to be replaced by a new version. Please, close the session before {} and save all your work to avoid loosing it.').format(tbr)
        else:
            tbrt = ''

        services.append({
            'id': 'F' + svr.uuid,
            'name': svr.name,
            'visual_name': svr.visual_name,
            'description': svr.comments,
            'group': group,
            'transports': trans,
            'imageId': imageId,
            'show_transports': svr.show_transports,
            'allow_users_remove': svr.allow_users_remove,
            'allow_users_reset': svr.allow_users_reset,
            'maintenance': svr.isInMaintenance(),
            'not_accesible': not svr.isAccessAllowed(),
            'in_use': in_use,
            'to_be_replaced': tbr,
            'to_be_replaced_text': tbrt,
        })

    logger.debug('Services: {0}'.format(services))

    # Sort services and remove services with no transports...
    services = [s for s in sorted(services, key=lambda s: s['name'].upper()) if len(s['transports']) > 0]

    autorun = False
    if len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.getBool(True) and len(services[0]['transports']) > 0:
        if request.session.get('autorunDone', '0') == '0':
            request.session['autorunDone'] = '1'
            autorun = True
            # return redirect('uds.web.views.service', idService=services[0]['id'], idTransport=services[0]['transports'][0]['id'])

    return {
            'services': services,
            'ip': request.ip,
            'nets': nets,
            'transports': validTrans,
            'autorun': autorun
    }
Beispiel #10
0
def index(request):
    """
    Renders the main page.
    :param request: http request
    """
    if request.session.get('ticket') == '1':
        return webLogout(request)

    # Session data
    os = request.os

    # We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
    groups = list(request.user.getGroups())
    availServices = DeployedService.getDeployedServicesForGroups(groups)
    availUserServices = UserService.getUserAssignedServices(request.user)

    # Information for administrators
    nets = ''
    validTrans = ''

    logger.debug('OS: {0}'.format(os['OS']))

    if request.user.isStaff():
        nets = ','.join([n.name for n in Network.networksFor(request.ip)])
        tt = []
        for t in Transport.objects.all():
            if t.validForIp(request.ip):
                tt.append(t.name)
        validTrans = ','.join(tt)

    # Extract required data to show to user
    services = []
    # Select assigned user services (manually assigned)
    for svr in availUserServices:
        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']) and t.validForOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink', args=('A' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'A' + svr.uuid, t.uuid)
                trans.append(
                    {
                        'id': t.uuid,
                        'name': t.name,
                        'link': link
                    }
                )

        servicePool = svr.deployed_service

        if servicePool.image is not None:
            imageId = servicePool.image.uuid
        else:
            imageId = 'x'  # Invalid

        # Extract app group
        group = servicePool.servicesPoolGroup if servicePool.servicesPoolGroup is not None else ServicesPoolGroup.default().as_dict

        services.append({
            'id': 'A' + svr.uuid,
            'name': servicePool.name,
            'visual_name': servicePool.visual_name,
            'description': servicePool.comments,
            'group': group,
            'transports': trans,
            'imageId': imageId,
            'show_transports': servicePool.show_transports,
            'allow_users_remove': servicePool.allow_users_remove,
            'maintenance': servicePool.isInMaintenance(),
            'not_accesible': not servicePool.isAccessAllowed(),
            'in_use': svr.in_use,
            'to_be_replaced': False,  # Manually assigned will not be autoremoved never
            'comments': servicePool.comments,
        })

    logger.debug(services)

    # Now generic user service
    for svr in availServices:
        trans = []
        for t in svr.transports.all().order_by('priority'):
            typeTrans = t.getType()
            if typeTrans is None:  # This may happen if we "remove" a transport type but we have a transport of that kind on DB
                continue
            if t.validForIp(request.ip) and typeTrans.supportsOs(os['OS']) and t.validForOs(os['OS']):
                if typeTrans.ownLink is True:
                    link = reverse('TransportOwnLink', args=('F' + svr.uuid, t.uuid))
                else:
                    link = html.udsAccessLink(request, 'F' + svr.uuid, t.uuid)
                trans.append(
                    {
                        'id': t.uuid,
                        'name': t.name,
                        'link': link
                    }
                )
        if svr.image is not None:
            imageId = svr.image.uuid
        else:
            imageId = 'x'

        # Locate if user service has any already assigned user service for this
        ads = UserServiceManager.manager().getExistingAssignationForUser(svr, request.user)
        if ads is None:
            in_use = False
        else:
            in_use = ads.in_use

        group = svr.servicesPoolGroup.as_dict if svr.servicesPoolGroup is not None else ServicesPoolGroup.default().as_dict

        tbr = svr.toBeReplaced()
        if tbr is not None:
            tbr = formats.date_format(tbr, "SHORT_DATETIME_FORMAT")
            tbrt = ugettext('This service is about to be replaced by a new version. Please, close the session before {} and save all your work to avoid loosing it.').format(tbr)
        else:
            tbrt = ''

        services.append({
            'id': 'F' + svr.uuid,
            'name': svr.name,
            'visual_name': svr.visual_name,
            'description': svr.comments,
            'group': group,
            'transports': trans,
            'imageId': imageId,
            'show_transports': svr.show_transports,
            'allow_users_remove': svr.allow_users_remove,
            'maintenance': svr.isInMaintenance(),
            'not_accesible': not svr.isAccessAllowed(),
            'in_use': in_use,
            'to_be_replaced': tbr,
            'to_be_replaced_text': tbrt,
            'comments': svr.comments,
        })

    logger.debug('Services: {0}'.format(services))

    services = sorted(services, key=lambda s: s['name'].upper())

    autorun = False
    if len(services) == 1 and GlobalConfig.AUTORUN_SERVICE.getBool(True) and len(services[0]['transports']) > 0:
        if request.session.get('autorunDone', '0') == '0':
            request.session['autorunDone'] = '1'
            autorun = True
            # return redirect('uds.web.views.service', idService=services[0]['id'], idTransport=services[0]['transports'][0]['id'])

    # List of services groups
    allGroups = [v for v in sorted([ser['group'] for ser in services], key=lambda s: s['priority'])]
    # Now remove duplicates
    groups = []
    already = []
    for g in allGroups:
        if g['name'] not in already:
            already.append(g['name'])
            groups.append(g)

    logger.debug('Groups: {}'.format(groups))

    response = render(
        request,
        theme.template('index.html'),
        {
            'groups': groups,
            'services': services,
            'ip': request.ip,
            'nets': nets,
            'transports': validTrans,
            'autorun': autorun
        }
    )
    return response