Esempio n. 1
0
def error(request, idError):
    '''
    Error view, responsible of error display
    :param request:
    :param idError:
    '''
    return render_to_response(theme.template('error.html'), {'errorString': errorString(idError)}, context_instance=RequestContext(request))
Esempio n. 2
0
def error(request, idError):
    '''
    Error view, responsible of error display
    :param request:
    :param idError:
    '''
    return render_to_response(theme.template('error.html'),
                              {'errorString': errorString(idError)},
                              context_instance=RequestContext(request))
Esempio n. 3
0
def about(request):
    """
    Shows the about page
    :param request: http request
    """
    return render(request, theme.template('about.html'), {
        'version': VERSION,
        'version_stamp': VERSION_STAMP
    })
Esempio n. 4
0
def download(request, idDownload):
    '''
    Downloadables management
    '''
    if idDownload == '':
        files = [{'id': key, 'name': val['name'], 'comment': _(val['comment'])} for key, val in DownloadsManager.manager().getDownloadables().items()]
        logger.debug('Files: {0}'.format(files))
        return render(request, theme.template('downloads.html'), {'files': files})

    return DownloadsManager.manager().send(request, idDownload)
Esempio n. 5
0
def client_downloads(request, os=None):
    '''
    Download page for UDS plugins
    '''
    if os not in desktopOss:
        os = request.os['OS']
    logger.debug('User: {}'.format(request.user))
    os = os.lower()
    return render(request, theme.template('download_client.html'),
                              {'os': os, 'user': request.user})
Esempio n. 6
0
def download(request, idDownload):
    """
    Downloadables management
    """
    if idDownload == '':
        files = [{'id': key, 'name': val['name'], 'comment': _(val['comment'])} for key, val in DownloadsManager.manager().getDownloadables().items()]
        logger.debug('Files: {0}'.format(files))
        return render(request, theme.template('downloads.html'), {'files': files})

    return DownloadsManager.manager().send(request, idDownload)
Esempio n. 7
0
def download(request, idDownload):
    '''
    Downloadables management
    '''
    if idDownload == '':
        files = [{'id': key, 'name': val['name'], 'comment': _(val['comment'])} for key, val in DownloadsManager.manager().getDownloadables().items()]
        logger.debug('Files: {0}'.format(files))
        return render_to_response(theme.template('downloads.html'), {'files': files}, context_instance=RequestContext(request))

    return DownloadsManager.manager().send(request, idDownload)
Esempio n. 8
0
def service(request, idService, idTransport):
    try:
        res = getService(request, idService, idTransport)
        if res is not None:
            ip, ads, iads, trans, itrans = res

            transportHtml = itrans.renderAsHtml(ads, trans, ip, request)
            return render_to_response(theme.template('show_transport.html'), {'transport': transportHtml, 'nolang': True}, context_instance=RequestContext(request))
    except Exception, e:
        logger.exception("Exception")
        return errors.exceptionView(request, e)
Esempio n. 9
0
def client_downloads(request, os=None):
    '''
    Download page for UDS plugins
    '''
    if os not in desktopOss:
        os = request.os['OS']
    logger.debug('User: {}'.format(request.user))
    os = os.lower()
    return render_to_response(theme.template('download_client.html'),
                              {'os': os, 'user': request.user},
                              context_instance=RequestContext(request))
Esempio n. 10
0
def about(request):
    """
    Shows the about page
    :param request: http request
    """
    return render(request,
        theme.template('about.html'),
        {
            'version': VERSION,
            'version_stamp': VERSION_STAMP
        }
    )
Esempio n. 11
0
def about(request):
    '''
    Shows the about page
    :param request: http request
    '''
    return render_to_response(
        theme.template('about.html'),
        {
            'version': VERSION,
        },
        context_instance=RequestContext(request)
    )
Esempio n. 12
0
def client_downloads(request, os=None):
    """
    Download page for UDS plugins
    """
    if os not in desktopOss:
        os = request.os['OS']
    logger.debug('User: {}'.format(request.user))
    os = os.lower()
    return render(request, theme.template('download_client.html'), {
        'os': os,
        'user': request.user
    })
Esempio n. 13
0
def prefs(request):
    """
    Preferences form
    :param request:
    """
    # Redirects to index if no preferences change allowed
    if GlobalConfig.PREFERENCES_ALLOWED.getBool(True) is False:
        return redirect('uds.web.views.index')
    if request.method == 'POST':
        UserPrefsManager.manager().processRequestForUserPreferences(request.user, request.POST)
        return redirect('uds.web.views.index')
    prefs_form = UserPrefsManager().manager().getHtmlForUserPreferences(request.user)
    return render(request, theme.template('prefs.html'), {'prefs_form': prefs_form})
Esempio n. 14
0
def prefs(request):
    '''
    Preferences form
    :param request:
    '''
    # Redirects to index if no preferences change allowed
    if GlobalConfig.PREFERENCES_ALLOWED.getBool(True) is False:
        return redirect('uds.web.views.index')
    if request.method == 'POST':
        UserPrefsManager.manager().processRequestForUserPreferences(request.user, request.POST)
        return redirect('uds.web.views.index')
    prefs_form = UserPrefsManager().manager().getHtmlForUserPreferences(request.user)
    return render_to_response(theme.template('prefs.html'), {'prefs_form': prefs_form}, context_instance=RequestContext(request))
Esempio n. 15
0
def about(request):
    '''
    Shows the about page
    :param request: http request
    '''
    return render_to_response(
        theme.template('about.html'),
        {
            'version': VERSION,
            'version_stamp': VERSION_STAMP
        },
        context_instance=RequestContext(request)
    )
Esempio n. 16
0
def prefs(request):
    """
    Preferences form
    :param request:
    """
    # Redirects to index if no preferences change allowed
    if GlobalConfig.PREFERENCES_ALLOWED.getBool(True) is False:
        return redirect("uds.web.views.index")
    if request.method == "POST":
        UserPrefsManager.manager().processRequestForUserPreferences(request.user, request.POST)
        return redirect("uds.web.views.index")
    prefs_form = UserPrefsManager().manager().getHtmlForUserPreferences(request.user)
    return render_to_response(
        theme.template("prefs.html"), {"prefs_form": prefs_form}, context_instance=RequestContext(request)
    )
Esempio n. 17
0
def service(request, idService, idTransport):
    try:
        res = getService(request, idService, idTransport)
        if res is not None:
            ip, ads, iads, trans, itrans = res

            transportHtml = itrans.renderAsHtml(ads, trans, ip, request)
            return render_to_response(theme.template('show_transport.html'), {
                'transport': transportHtml,
                'nolang': True
            },
                                      context_instance=RequestContext(request))
    except Exception, e:
        logger.exception("Exception")
        return errors.exceptionView(request, e)
Esempio n. 18
0
def error(request, idError):
    '''
    Error view, responsible of error display
    :param request:
    :param idError:
    '''
    idError = int(idError)
    code = idError >> 8
    idError &= 0xFF

    errStr = errorString(idError)
    if code != 0:
        errStr += ' (code {0:04X})'.format(code)

    return render(request, theme.template('error.html'), {'errorString': errStr})
Esempio n. 19
0
def error(request, idError):
    '''
    Error view, responsible of error display
    :param request:
    :param idError:
    '''
    idError = int(idError)
    code = idError >> 8
    idError = idError & 0xFF

    errStr = errorString(idError)
    if code != 0:
        errStr += ' (code {0:04X})'.format(code)

    return render_to_response(theme.template('error.html'), {'errorString': errStr}, context_instance=RequestContext(request))
Esempio n. 20
0
def error(request, idError):
    """
    Error view, responsible of error display
    :param request:
    :param idError:
    """
    idError = int(idError)
    code = idError >> 8
    idError &= 0xFF

    errStr = errorString(idError)
    if code != 0:
        errStr += ' (code {0:04X})'.format(code)

    return render(request, theme.template('error.html'),
                  {'errorString': errStr})
Esempio n. 21
0
def error(request, idError):
    '''
    Error view, responsible of error display
    :param request:
    :param idError:
    '''
    idError = int(idError)
    code = idError >> 8
    idError = idError & 0xFF

    errStr = errorString(idError)
    if code != 0:
        errStr += ' (code {0:04X})'.format(code)

    return render_to_response(theme.template('error.html'),
                              {'errorString': errStr},
                              context_instance=RequestContext(request))
Esempio n. 22
0
def transportOwnLink(request, idService, idTransport):
    try:
        res = userServiceManager().getService(request.user, request.ip,
                                              idService, idTransport)
        ip, userService, iads, trans, itrans = res  # @UnusedVariable
        # This returns a response object in fact
        return itrans.getLink(userService, trans, ip, request.os, request.user,
                              webPassword(request), request)
    except ServiceNotReadyError as e:
        return render(request, theme.template('service_not_ready.html'), {
            'fromLauncher': False,
            'code': e.code
        })
    except Exception as e:
        logger.exception("Exception")
        return errors.exceptionView(request, e)

    # Will never reach this
    raise RuntimeError('Unreachable point reached!!!')
Esempio n. 23
0
def transportOwnLink(request, idService, idTransport):
    try:
        res = userServiceManager().getService(request.user, request.ip, idService, idTransport)
        ip, userService, iads, trans, itrans = res  # @UnusedVariable
        # This returns a response object in fact
        return itrans.getLink(userService, trans, ip, request.os, request.user, webPassword(request), request)
    except ServiceNotReadyError as e:
        return render(request,
            theme.template('service_not_ready.html'),
            {
                'fromLauncher': False,
                'code': e.code
            }
        )
    except Exception as e:
        logger.exception("Exception")
        return errors.exceptionView(request, e)

    # Will never reach this
    raise RuntimeError('Unreachable point reached!!!')
Esempio n. 24
0
def login(request, tag=None):
    """
    View responsible of logging in an user
    :param request:  http request
    :param tag: tag of login auth
    """
    # request.session.set_expiry(GlobalConfig.USER_SESSION_LENGTH.getInt())
    response = None

    # Default empty form
    form = LoginForm(tag=tag)

    if request.method == 'POST':
        form = LoginForm(request.POST, tag=tag)
        user, data = checkLogin(request, form, tag)
        if user:
            response = HttpResponseRedirect(reverse('uds.web.views.index'))
            webLogin(request, response, user, data)  # data is user password here
        else:  # error, data = error
            if isinstance(data, int):
                return errors.errorView(request, data)
            # Error to notify
            form.add_error(None, data)

    if response is None:
        response = render(request,
            theme.template('login.html'),
            {
                'form': form,
                'authenticators': Authenticator.getByTag(tag),
                'customHtml': GlobalConfig.CUSTOM_HTML_LOGIN.get(True),
                'version': VERSION

            }
        )

    getUDSCookie(request, response)

    return response
Esempio n. 25
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
Esempio n. 26
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
Esempio n. 27
0
def about(request):
    '''
    Shows the about page
    :param request: http request
    '''
    return render(request, theme.template('about.html'))
Esempio n. 28
0
def login(request, tag=None):
    '''
    View responsible of logging in an user
    :param request:  http request
    :param tag: tag of login auth
    '''
    # request.session.set_expiry(GlobalConfig.USER_SESSION_LENGTH.getInt())

    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

    # Get Authenticators limitation
    logger.debug('Host: {0}'.format(host))
    if GlobalConfig.DISALLOW_GLOBAL_LOGIN.getBool(True) is True:
        if tag is None:
            try:
                Authenticator.objects.get(small_name=host)
                tag = host
            except Exception:
                try:
                    tag = Authenticator.objects.order_by('priority')[0].small_name
                except Exception:  # There is no authenticators yet, simply allow global login to nowhere.. :-)
                    tag = None

    logger.debug('Tag: {0}'.format(tag))

    logger.debug(request.method)
    if request.method == 'POST':
        if 'uds' not in request.COOKIES:
            logger.debug('Request does not have uds cookie')
            return errors.errorView(request, errors.COOKIES_NEEDED)  # We need cookies to keep session data
        request.session.cycle_key()
        form = LoginForm(request.POST, tag=tag)
        if form.is_valid():
            os = OsDetector.getOsFromUA(request.META.get('HTTP_USER_AGENT'))
            try:
                authenticator = Authenticator.objects.get(pk=form.cleaned_data['authenticator'])
            except Exception:
                authenticator = Authenticator()
            userName = form.cleaned_data['user']

            cache = Cache('auth')
            cacheKey = str(authenticator.id) + userName
            tries = cache.get(cacheKey)
            if tries is None:
                tries = 0
            if authenticator.getInstance().blockUserOnLoginFailures is True and tries >= GlobalConfig.MAX_LOGIN_TRIES.getInt():
                form.add_form_error('Too many authentication errors. User temporarily  blocked.')
                authLogLogin(request, authenticator, userName, 'Temporarily blocked')
            else:
                user = authenticate(userName, form.cleaned_data['password'], authenticator)
                logger.debug('User: {}'.format(user))

                if user is None:
                    logger.debug("Invalid credentials for user {0}".format(userName))
                    tries += 1
                    cache.put(cacheKey, tries, GlobalConfig.LOGIN_BLOCK.getInt())
                    form.add_form_error('Invalid credentials')
                    authLogLogin(request, authenticator, userName, 'Invalid credentials')
                else:
                    logger.debug('User {} has logged in'.format(userName))
                    cache.remove(cacheKey)  # Valid login, remove cached tries
                    response = HttpResponseRedirect(reverse('uds.web.views.index'))
                    webLogin(request, response, user, form.cleaned_data['password'])
                    # Add the "java supported" flag to session
                    request.session['OS'] = os
                    authLogLogin(request, authenticator, user.name)
                    return response
    else:
        form = LoginForm(tag=tag)

    response = render_to_response(theme.template('login.html'), {'form': form, 'customHtml': GlobalConfig.CUSTOM_HTML_LOGIN.get(True)},
                                  context_instance=RequestContext(request))

    getUDSCookie(request, response)

    return response
Esempio n. 29
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)
Esempio n. 30
0
@webLoginRequired(admin=False)
def service(request, idService, idTransport):
    try:
        res = getService(request, idService, idTransport)
        if res is not None:
            ip, ads, iads, trans, itrans = res

            transportHtml = itrans.renderAsHtml(ads, trans, ip, request)
            return render_to_response(theme.template('show_transport.html'), {'transport': transportHtml, 'nolang': True}, context_instance=RequestContext(request))
    except Exception, e:
        logger.exception("Exception")
        return errors.exceptionView(request, e)

    # Not ready, show message and return to this page in a while
    return render_to_response(theme.template('service_not_ready.html'), context_instance=RequestContext(request))


@webLoginRequired(admin=False)
def trans(request, idService, idTransport):
    try:
        res = getService(request, idService, idTransport)
        if res is not None:
            ip, ads, iads, trans, itrans = res
            return itrans.getLink(ads, trans, ip, request.os, request.user, webPassword(request), request)
    except Exception, e:
        logger.exception("Exception")
        return errors.exceptionView(request, e)

    return render_to_response(theme.template('service_not_ready.html'), context_instance=RequestContext(request))
Esempio n. 31
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
Esempio n. 32
0
def about(request):
    '''
    Shows the about page
    :param request: http request
    '''
    return render(request, theme.template('about.html'))
Esempio n. 33
0
        res = getService(request, idService, idTransport)
        if res is not None:
            ip, ads, iads, trans, itrans = res

            transportHtml = itrans.renderAsHtml(ads, trans, ip, request)
            return render_to_response(theme.template('show_transport.html'), {
                'transport': transportHtml,
                'nolang': True
            },
                                      context_instance=RequestContext(request))
    except Exception, e:
        logger.exception("Exception")
        return errors.exceptionView(request, e)

    # Not ready, show message and return to this page in a while
    return render_to_response(theme.template('service_not_ready.html'),
                              context_instance=RequestContext(request))


@webLoginRequired(admin=False)
def trans(request, idService, idTransport):
    try:
        res = getService(request, idService, idTransport)
        if res is not None:
            ip, ads, iads, trans, itrans = res
            return itrans.getLink(ads, trans, ip, request.os, request.user,
                                  webPassword(request), request)
    except Exception, e:
        logger.exception("Exception")
        return errors.exceptionView(request, e)
Esempio n. 34
0
def login(request, tag=None):
    '''
    View responsible of logging in an user
    :param request:  http request
    :param tag: tag of login auth
    '''
    # request.session.set_expiry(GlobalConfig.USER_SESSION_LENGTH.getInt())

    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

    # Get Authenticators limitation
    logger.debug('Host: {0}'.format(host))
    if GlobalConfig.DISALLOW_GLOBAL_LOGIN.getBool(False) is True:
        if tag is None:
            try:
                Authenticator.objects.get(small_name=host)
                tag = host
            except Exception:
                try:
                    tag = Authenticator.objects.order_by('priority')[0].small_name
                except Exception:  # There is no authenticators yet, simply allow global login to nowhere.. :-)
                    tag = None

    logger.debug('Tag: {0}'.format(tag))

    logger.debug(request.method)
    if request.method == 'POST':
        if 'uds' not in request.COOKIES:
            logger.debug('Request does not have uds cookie')
            return errors.errorView(request, errors.COOKIES_NEEDED)  # We need cookies to keep session data
        request.session.cycle_key()
        form = LoginForm(request.POST, tag=tag)
        if form.is_valid():
            os = request.os
            try:
                authenticator = Authenticator.objects.get(pk=form.cleaned_data['authenticator'])
            except Exception:
                authenticator = Authenticator()
            userName = form.cleaned_data['user']
            if GlobalConfig.LOWERCASE_USERNAME.getBool(True) is True:
                userName = userName.lower()

            cache = Cache('auth')
            cacheKey = str(authenticator.id) + userName
            tries = cache.get(cacheKey)
            if tries is None:
                tries = 0
            if authenticator.getInstance().blockUserOnLoginFailures is True and tries >= GlobalConfig.MAX_LOGIN_TRIES.getInt():
                form.add_error(None, 'Too many authentication errors. User temporarily  blocked.')
                authLogLogin(request, authenticator, userName, 'Temporarily blocked')
            else:
                password = form.cleaned_data['password']
                user = None
                if password == '':
                    password = '******'
                user = authenticate(userName, password, authenticator)
                logger.debug('User: {}'.format(user))

                if user is None:
                    logger.debug("Invalid credentials for user {0}".format(userName))
                    tries += 1
                    cache.put(cacheKey, tries, GlobalConfig.LOGIN_BLOCK.getInt())
                    form.add_error(None, ugettext('Invalid credentials'))
                    authLogLogin(request, authenticator, userName, 'Invalid credentials')
                else:
                    logger.debug('User {} has logged in'.format(userName))
                    cache.remove(cacheKey)  # Valid login, remove cached tries
                    response = HttpResponseRedirect(reverse('uds.web.views.index'))
                    webLogin(request, response, user, form.cleaned_data['password'])
                    # Add the "java supported" flag to session
                    request.session['OS'] = os
                    if form.cleaned_data['logouturl'] != '':
                        logger.debug('The logoout url will be {}'.format(form.cleaned_data['logouturl']))
                        request.session['logouturl'] = form.cleaned_data['logouturl']
                    authLogLogin(request, authenticator, user.name)
                    return response
        else:
            logger.info('Invalid form received')
    else:
        form = LoginForm(tag=tag)

    response = render_to_response(
        theme.template('login.html'),
        {
            'form': form,
            'customHtml': GlobalConfig.CUSTOM_HTML_LOGIN.get(True),
            'version': VERSION

        },
        context_instance=RequestContext(request)
    )

    getUDSCookie(request, response)

    return response
Esempio n. 35
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
Esempio n. 36
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)