Ejemplo n.º 1
0
 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]
Ejemplo n.º 2
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
Ejemplo n.º 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
    }
Ejemplo n.º 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
Ejemplo n.º 5
0
def ticketAuth(request: 'HttpRequest', ticketId: str) -> HttpResponse:  # pylint: disable=too-many-locals,too-many-branches,too-many-statements
    """
    Used to authenticate an user via a ticket
    """
    try:
        data = TicketStore.get(ticketId, invalidate=True)

        try:
            # Extract ticket.data from ticket.data storage, and remove it if success
            username = data['username']
            groups = data['groups']
            auth = data['auth']
            realname = data['realname']
            servicePool = data['servicePool']
            password = cryptoManager().decrypt(data['password'])
            transport = data['transport']
        except Exception:
            logger.error('Ticket stored is not valid')
            raise auths.exceptions.InvalidUserException()

        auth = Authenticator.objects.get(uuid=auth)
        # If user does not exists in DB, create it right now
        # Add user to groups, if they exists...
        grps: typing.List = []
        for g in groups:
            try:
                grps.append(auth.groups.get(uuid=g))
            except Exception:
                logger.debug('Group list has changed since ticket assignment')

        if not grps:
            logger.error('Ticket has no valid groups')
            raise Exception('Invalid ticket authentication')

        usr = auth.getOrCreateUser(username, realname)
        if usr is None or State.isActive(
                usr.state) is False:  # If user is inactive, raise an exception
            raise auths.exceptions.InvalidUserException()

        # Add groups to user (replace existing groups)
        usr.groups.set(grps)

        # Force cookie generation
        webLogin(request, None, usr, password)

        request.user = usr  # Temporarily store this user as "authenticated" user, next requests will be done using session
        request.session[
            'ticket'] = '1'  # Store that user access is done using ticket

        # Override and recalc transport based on current os
        transport = None

        logger.debug("Service & transport: %s, %s", servicePool, transport)

        # Check if servicePool is part of the ticket
        if servicePool:
            # If service pool is in there, also is transport
            res = userServiceManager().getService(request.user, request.os,
                                                  request.ip,
                                                  'F' + servicePool, transport,
                                                  False)
            _, userService, _, transport, _ = res

            transportInstance = transport.getInstance()
            if transportInstance.ownLink is True:
                link = reverse('TransportOwnLink',
                               args=('A' + userService.uuid, transport.uuid))
            else:
                link = html.udsAccessLink(request, 'A' + userService.uuid,
                                          transport.uuid)

            request.session['launch'] = link
            response = HttpResponseRedirect(reverse('page.ticket.launcher'))
        else:
            response = HttpResponseRedirect(reverse('page.index'))

        # Now ensure uds cookie is at response
        getUDSCookie(request, response, True)
        return response
    except ServiceNotReadyError as e:
        return errors.errorView(request, errors.SERVICE_NOT_READY)
    except TicketStore.InvalidTicket:
        return errors.errorView(request, errors.RELOAD_NOT_SUPPORTED)
    except Authenticator.DoesNotExist:
        logger.error('Ticket has an non existing authenticator')
        return errors.errorView(request, errors.ACCESS_DENIED)
    except ServicePool.DoesNotExist:
        logger.error('Ticket has an invalid Service Pool')
        return errors.errorView(request, errors.SERVICE_NOT_FOUND)
    except Exception as e:
        logger.exception('Exception')
        return errors.exceptionView(request, e)
Ejemplo n.º 6
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
Ejemplo n.º 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 = 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
    }
Ejemplo n.º 8
0
def ticketAuth(request, ticketId):
    """
    Used to authenticate an user via a ticket
    """
    try:
        data = TicketStore.get(ticketId, invalidate=True)

        try:
            # Extract ticket.data from ticket.data storage, and remove it if success
            username = data['username']
            groups = data['groups']
            auth = data['auth']
            realname = data['realname']
            servicePool = data['servicePool']
            password = cryptoManager().decrypt(data['password'])
            transport = data['transport']
        except Exception:
            logger.error('Ticket stored is not valid')
            raise InvalidUserException()

        auth = Authenticator.objects.get(uuid=auth)
        # If user does not exists in DB, create it right now
        # Add user to groups, if they exists...
        grps = []
        for g in groups:
            try:
                grps.append(auth.groups.get(uuid=g))
            except Exception:
                logger.debug('Group list has changed since ticket assignment')

        if len(grps) == 0:
            logger.error('Ticket has no valid groups')
            raise Exception('Invalid ticket authentication')

        usr = auth.getOrCreateUser(username, realname)
        if usr is None or State.isActive(usr.state) is False:  # If user is inactive, raise an exception
            raise InvalidUserException()

        # Add groups to user (replace existing groups)
        usr.groups.set(grps)

        # Force cookie generation
        webLogin(request, None, usr, password)

        request.user = usr  # Temporarily store this user as "authenticated" user, next requests will be done using session
        request.session['ticket'] = '1'  # Store that user access is done using ticket

        logger.debug("Service & transport: {}, {}".format(servicePool, transport))
        for v in DeployedService.objects.all():
            logger.debug("{} {}".format(v.uuid, v.name))

        # Check if servicePool is part of the ticket
        if servicePool is not None:
            # If service pool is in there, also is transport
            res = userServiceManager().getService(request.user, request.ip, 'F' + servicePool, transport, False)
            _x, userService, _x, transport, _x = res

            transportInstance = transport.getInstance()
            if transportInstance.ownLink is True:
                link = reverse('TransportOwnLink', args=('A' + userService.uuid, transport.uuid))
            else:
                link = html.udsAccessLink(request, 'A' + userService.uuid, transport.uuid)

            response = render(
                request,
                theme.template('simpleLauncher.html'),
                {
                    'link': link
                }
            )
        else:
            response = HttpResponsePermanentRedirect(reverse('uds.web.views.index'))

        # Now ensure uds cookie is at response
        getUDSCookie(request, response, True)
        return response
    except ServiceNotReadyError as e:
        return render(
            request,
            theme.template('service_not_ready.html'),
            {
                'fromLauncher': True,
                'code': e.code
            }
        )

    except TicketStore.InvalidTicket:
        return render(
            request,
            theme.template('simpleLauncherAlreadyLaunched.html')
        )
    except Authenticator.DoesNotExist:
        logger.error('Ticket has an non existing authenticator')
        return errors.exceptionView(request, InvalidUserException())
    except DeployedService.DoesNotExist:
        logger.error('Ticket has an invalid Service Pool')
        return errors.exceptionView(request, InvalidServiceException())
    except Exception as e:
        logger.exception('Exception')
        return errors.exceptionView(request, e)
Ejemplo n.º 9
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
    }
Ejemplo n.º 10
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
    }
Ejemplo n.º 11
0
def ticketAuth(request, ticketId):
    """
    Used to authenticate an user via a ticket
    """
    try:
        data = TicketStore.get(ticketId, invalidate=True)

        try:
            # Extract ticket.data from ticket.data storage, and remove it if success
            username = data['username']
            groups = data['groups']
            auth = data['auth']
            realname = data['realname']
            servicePool = data['servicePool']
            password = data['password']
            transport = data['transport']
        except Exception:
            logger.error('Ticket stored is not valid')
            raise InvalidUserException()

        auth = Authenticator.objects.get(uuid=auth)
        # If user does not exists in DB, create it right now
        # Add user to groups, if they exists...
        grps = []
        for g in groups:
            try:
                grps.append(auth.groups.get(uuid=g))
            except Exception:
                logger.debug('Group list has changed since ticket assignment')

        if len(grps) == 0:
            logger.error('Ticket has no valid groups')
            raise Exception('Invalid ticket authentication')

        usr = auth.getOrCreateUser(username, realname)
        if usr is None or State.isActive(usr.state) is False:  # If user is inactive, raise an exception
            raise InvalidUserException()

        # Add groups to user (replace existing groups)
        usr.groups.set(grps)

        # Force cookie generation
        webLogin(request, None, usr, password)

        request.user = usr  # Temporarily store this user as "authenticated" user, next requests will be done using session
        request.session['ticket'] = '1'  # Store that user access is done using ticket

        logger.debug("Service & transport: {}, {}".format(servicePool, transport))
        for v in DeployedService.objects.all():
            logger.debug("{} {}".format(v.uuid, v.name))

        # Check if servicePool is part of the ticket
        if servicePool is not None:
            # If service pool is in there, also is transport
            res = userServiceManager().getService(request.user, request.ip, 'F' + servicePool, transport, False)
            _x, userService, _x, transport, _x = res

            transportInstance = transport.getInstance()
            if transportInstance.ownLink is True:
                link = reverse('TransportOwnLink', args=('A' + userService.uuid, transport.uuid))
            else:
                link = html.udsAccessLink(request, 'A' + userService.uuid, transport.uuid)

            response = render(
                request,
                theme.template('simpleLauncher.html'),
                {
                    'link': link
                }
            )
        else:
            response = HttpResponsePermanentRedirect(reverse('uds.web.views.index'))

        # Now ensure uds cookie is at response
        getUDSCookie(request, response, True)
        return response
    except ServiceNotReadyError as e:
        return render(
            request,
            theme.template('service_not_ready.html'),
            {
                'fromLauncher': True,
                'code': e.code
            }
        )

    except TicketStore.InvalidTicket:
        return render(
            request,
            theme.template('simpleLauncherAlreadyLaunched.html')
        )
    except Authenticator.DoesNotExist:
        logger.error('Ticket has an non existing authenticator')
        return errors.exceptionView(request, InvalidUserException())
    except DeployedService.DoesNotExist:
        logger.error('Ticket has an invalid Service Pool')
        return errors.exceptionView(request, InvalidServiceException())
    except Exception as e:
        logger.exception('Exception')
        return errors.exceptionView(request, e)
Ejemplo n.º 12
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