Exemple #1
0
def submit_ajax(request):
    """ Handles ajax paste submits.
        Reads json data from request and handles accordingly.
        These requests must come from the welbornprod site.
    """
    # Submits should always be ajax/POST.
    if not request.is_ajax():
        remoteip = get_remote_ip(request)
        if not remoteip:
            remoteip = '<Unknown IP>'
        log.error('Received non-ajax request from: {}'.format(remoteip))
        return responses.error500(request,
                                  msgs=('Invalid request.', ),
                                  user_error=' '.join(
                                      ('Try entering a valid url,',
                                       'or using the forms/buttons provided.',
                                       '-Cj')))

    # Get the request args for this submit (JSON only).
    submitdata = responses.json_get_request(request)
    if (not submitdata) or (not submitdata.get('content', False)):
        # No valid submit data.
        exc = ValueError('Invalid data submitted.')
        return responses.json_response_err(exc)

    # Add the user's ip address to the paste data.
    submitdata['author_ip'] = get_remote_ip(request)

    # Try building a paste, and return a JSON response.
    return process_submit(submitdata)
Exemple #2
0
def submit_ajax(request):
    """ Handles ajax paste submits.
        Reads json data from request and handles accordingly.
        These requests must come from the welbornprod site.
    """
    # Submits should always be ajax/POST.
    if not request.is_ajax():
        remoteip = get_remote_ip(request)
        if not remoteip:
            remoteip = '<Unknown IP>'
        log.error('Received non-ajax request from: {}'.format(remoteip))
        return responses.error500(
            request,
            msgs=('Invalid request.', ),
            user_error=' '.join((
                'Try entering a valid url,',
                'or using the forms/buttons provided.',
                '-Cj'
            ))
        )

    # Get the request args for this submit (JSON only).
    submitdata = responses.json_get_request(request)
    if (not submitdata) or (not submitdata.get('content', False)):
        # No valid submit data.
        exc = ValueError('Invalid data submitted.')
        return responses.json_response_err(exc)

    # Add the user's ip address to the paste data.
    submitdata['author_ip'] = get_remote_ip(request)

    # Try building a paste, and return a JSON response.
    return process_submit(submitdata)
Exemple #3
0
def submit_public(request):
    """ A public paste submission
        (may have to pass a gauntlet of checks)
    """

    # Get the request args for this submit.
    submitdata = responses.json_get_request(request, suppress_errors=True)
    # Try using GET/POST..
    if not submitdata:
        submitdata = responses.get_request_args(request)
        # Using multiple content args, but first for the rest.
        submitdata['content'] = '\n'.join(submitdata.getlist('content', []))
        # Parse a few args that string values would break.
        onhold = parse_bool(submitdata.get('onhold', ''))
        private = parse_bool(submitdata.get('private', ''))
        submitdata.update({'onhold': onhold, 'private': private})

    if (not submitdata) or (not submitdata.get('content', False)):
        # No valid submit data.
        exc = ValueError('Invalid data submitted.')
        return responses.json_response_err(exc)

    # Add author's ip to the paste info.
    submitdata['author_ip'] = get_remote_ip(request)

    invalidsubmit = invalidate_submit(submitdata)
    if invalidsubmit:
        # User is not allowed to paste again right now.
        log.debug('User paste invalidated: '
                  '{} - {}'.format(submitdata['author_ip'], invalidsubmit))
        err = ValueError(invalidsubmit)
        return responses.json_response_err(err)

    # Try building a paste, and return JSON response.
    return process_submit(submitdata, apisubmit=True)
Exemple #4
0
def clean_response(template_name, context_dict, **kwargs):
    """ same as render_response, except does code cleanup (no comments, etc.)
        returns cleaned HttpResponse.

        Keyword Args:
            see htmltools.render_clean()...
    """
    if context_dict is None:
        context_dict = {}
    request = kwargs.get('request', None) or context_dict.get('request', None)

    # Add request to context if available.
    if request:
        context_dict.update({'request': request})
        # Add server name, remote ip to context if not added already.
        if not context_dict.get('server_name', False):
            context_dict['server_name'] = get_server(request)
        if not context_dict.get('remote_ip', False):
            context_dict['remote_ip'] = get_remote_ip(request)

    # Add new context dict to kwargs for render_clean().
    kwargs['context_dict'] = context_dict
    
    try:
        rendered = htmltools.render_clean(template_name, **kwargs)
    except Exception as ex:
        _log.error('Unable to render template: '
                   '{}\n{}'.format(template_name, ex))
        return alert_message(request,
                             'Sorry, there was an error loading this page.')
    else:
        return HttpResponse(rendered)
Exemple #5
0
def clean_response_req(template_name, context_dict, **kwargs):
    """ handles responses with RequestContext instead of Context,
        otherwise it's the same as clean_response
    """
    
    if not context_dict:
        context_dict = {}
    request = kwargs.get('request', None)
    if request:
        # Add server name, remote ip to context if not added already.
        if not context_dict.get('server_name', False):
            context_dict['server_name'] = get_server(request)
        if not context_dict.get('remote_ip', False):
            context_dict['remote_ip'] = get_remote_ip(request)
        # Turn this into a request context.
        context_dict = RequestContext(request, context_dict)
    else:
        _log.error('No request passed to clean_response_req!\n'
                   'template: {}\n'.format(template_name) +
                   'context: {}\n'.format(repr(context_dict)))

    kwargs['context_dict'] = context_dict

    try:
        rendered = htmltools.render_clean(template_name, **kwargs)
    except Exception as ex:
        _log.error('Unable to render template with request context: '
                   '{}\n{}'.format(template_name, ex))
        return alert_message(request,
                             'Sorry, there was an error loading this page.')
    else:
        return HttpResponse(rendered)
Exemple #6
0
def submit_public(request):
    """ A public paste submission
        (may have to pass a gauntlet of checks)
    """

    # Get the request args for this submit.
    submitdata = responses.json_get_request(request, suppress_errors=True)
    # Try using GET/POST..
    if not submitdata:
        submitdata = responses.get_request_args(request)
        # Using multiple content args, but first for the rest.
        submitdata['content'] = '\n'.join(submitdata.getlist('content', []))
        # Parse a few args that string values would break.
        onhold = parse_bool(submitdata.get('onhold', ''))
        private = parse_bool(submitdata.get('private', ''))
        submitdata.update({'onhold': onhold, 'private': private})

    if (not submitdata) or (not submitdata.get('content', False)):
        # No valid submit data.
        exc = ValueError('Invalid data submitted.')
        return responses.json_response_err(exc)

    # Add author's ip to the paste info.
    submitdata['author_ip'] = get_remote_ip(request)

    invalidsubmit = invalidate_submit(submitdata)
    if invalidsubmit:
        # User is not allowed to paste again right now.
        log.debug('User paste invalidated: '
                  '{} - {}'.format(submitdata['author_ip'], invalidsubmit))
        err = ValueError(invalidsubmit)
        return responses.json_response_err(err)

    # Try building a paste, and return JSON response.
    return process_submit(submitdata, apisubmit=True)
Exemple #7
0
def clean_response(
        template_name, context=None, request=None, status=200, **kwargs):
    """ same as render_response, except does code cleanup (no comments, etc.)
        returns cleaned HttpResponse.
        Arguments:
            template_name   : Known template name to render.
            context         : Context dict.
            request         : Request() object (or None).
            status          : Status code for the HttpResponse().

        Keyword Args:
            link_list       : Auto link list for render_html()
            auto_link_args  : Keyword arguments dict for render_html() and
                              auto_link()
    """
    context = context or {}
    # Check kwargs for a request obj, then check the context if it's not
    # there.
    request = request or context.get('request', None)

    # Add request to context if available.
    if request:
        # Add server name, remote ip to context if not added already.
        if not context.get('server_name', False):
            context['server_name'] = get_server(request)
        if not context.get('remote_ip', False):
            context['remote_ip'] = get_remote_ip(request)

    try:
        rendered = htmltools.render_clean(
            template_name,
            context=context,
            request=request,
            link_list=kwargs.get('link_list', None),
            auto_link_args=kwargs.get('auto_link_args', None)
        )
    except Exception:
        logtraceback(
            log.error,
            message='Unable to render: {}, context: {}, request: {}'.format(
                template_name,
                context,
                request
            )
        )
        # 500 page.
        return error500(request, msgs=('Error while building that page.',))

    if rendered:
        # Return final page response.
        return HttpResponse(rendered, status=status or 200)

    # Something went wrong in the render chain.
    # It catches most errors, logs them, and returns ''.
    msgs = [
        'Unable to build that page right now, sorry.',
        'The error has been logged and emailed to me.'
    ]
    return error500(request, msgs=msgs)
Exemple #8
0
def view_index(request):
    """ List all uploaded images, or an album's images (GET /img?album=<name>).
        Present the upload button to staff.
    """
    alert_msg = None
    alert_class = None
    imagefilter = {'disabled': False}
    album = request.GET.get('album', None)
    if album:
        # Filter by album. TODO: This may need it's own view.
        if album == 'none':
            # Grab all image without an album set.
            album = ''
        if album == 'all':
            # Grab all images.
            album = None
        else:
            # Filter on user-specified album.
            imagefilter['album'] = album
    else:
        # View a single image by id. TODO: Needs it's own url pattern.
        imageid = request.GET.get('id', None)
        if imageid:
            return view_image_id(request, imageid)

    if request.user.is_staff:
        if request.FILES:
            # Handle file upload.
            alert_class, alert_msg = handle_files(request)
    else:
        if request.FILES:
            log.error('Non-staff tried to upload files: {}'.format(
                utilities.get_remote_ip(request)))
        # No private images for the public.
        imagefilter['private'] = False

    images = wp_image.objects.filter(**imagefilter)

    if album and (not images):
        alert_msg = 'No album by that name.'
        alert_class = 'error'
        album = None

    if images:
        images = images.order_by('-publish_date')
        # Allow user sort by album.
        if request.GET.get('sort', None) == 'album':
            images = images.order_by('album')

    context = {
        'images': images,
        'album': album,
        'alert_message': alert_msg,
        'alert_class': alert_class
    }
    return responses.clean_response(template_name='img/index.html',
                                    context=context,
                                    request=request)
Exemple #9
0
def error500(request, msgs=None):
    """ Fake-raise a 500 error. I say fake because no exception is
        raised, but the user is directed to the 500-error page.
        If a message is passed, it is sent via the messages framework.
        Arguments:
            request  : Request object from view.
            message  : Optional message for the messages framework.
    """
    if msgs and isinstance(msgs, str):
        msgs = [msgs]

    if msgs:
        # Send messages using the message framework.
        for m in msgs:
            messages.error(request, m)

    context = {'request': request,
               'server_name': get_server(request),
               'remote_ip': get_remote_ip(request),
               }
    try:
        rendered = htmltools.render_clean('home/500.html',
                                          context_dict=context,
                                          request=request)
    except Exception as ex:
        _log.error('Unable to render template: home/500.html\n'
                   '{}'.format(ex))
        if msgs:
            # Send message manually.
            errmsgfmt = '<html><body>\n{}</body></html>'
            # Style each message.
            msgfmt = '<div style="color: darkred;">{}</div>'
            errmsgs = '\n'.join((msgfmt.format(m) for m in msgs))
            # Build final html page.
            errmsg = errmsgfmt.format(errmsgs)
        else:
            errmsg = 'There was an error while building this page.'
        return HttpResponseServerError(errmsg)

    # Successfully rendered 500.html page.
    return HttpResponse(rendered)
Exemple #10
0
def view_scriptkids(request):
    """ return my script kiddie view
        for people trying to access wordpress-login pages and stuff like that.
    """

    # get ip if possible.
    ip_address = utilities.get_remote_ip(request)
    try:
        path = request.path
    except AttributeError:
        path = '<error getting path>'
    log.error('ScriptKid Access from: {} -> {}'.format(ip_address, path))

    # get insulting image to display
    scriptkid_img = hometools.get_scriptkid_image()
    if scriptkid_img is not None:
        scriptkid_img = utilities.get_relative_path(scriptkid_img)
    use_img = (scriptkid_img is not None)
    use_ip = (ip_address is not None)
    context = {
        'use_img': use_img,
        'scriptkid_img': scriptkid_img,
        'use_ip': use_ip,
        'ip_address': ip_address,
    }
    # Try banning the ip.
    ban_ip = use_ip and (ip_address != '127.0.0.1')
    if ban_ip:
        if utilities.ban_add(request):
            log.error('Banned script kid: {}'.format(ip_address))
        else:
            log.error('Could not ban script kid: {}'.format(ip_address))
    else:
        log.debug('Not banning scriptkid: {}'.format(ip_address))

    # return formatted template.
    return responses.clean_response(
        'home/scriptkids.html',
        context=context,
        request=request)
Exemple #11
0
def view_loader(request):
    """ accepts GET/POST request containing a filename 'file'.
        uses ajax in loader.html to pass that filename to ajax_contents().
        everything after that is handled in loader.html's javascript
        with the help of wpviewer.js.
        raises 404 on error or file not found..
    """
    rawpath = request.POST.get('file', request.GET.get('file', ''))
    if rawpath:
        file_path = utilities.strip_chars(rawpath, ('"', "'"))
        context = {
            'file': file_path,
        }

        return responses.clean_response(
            'viewer/loader.html',
            context=context,
            request=request)

    log.error('Empty file name given: {}'.format(
        utilities.get_remote_ip(request))
    )
    raise Http404('No file name given.')
Exemple #12
0
def get_remote_ip(request):
    """ Make the convenience function available for templates. """
    
    return utilities.get_remote_ip(request)
Exemple #13
0
def view_ip_simple(request):
    """ returns the remote ip in plain text. """
    ip = '{}\n'.format(utilities.get_remote_ip(request))
    return responses.text_response(ip)
Exemple #14
0
def view_index(request):
    """ List all uploaded images, or an album's images (GET /img?album=<name>).
        Present the upload button to staff.
    """
    alert_msg = None
    alert_class = None
    imagefilter = {
        'disabled': False
    }
    album = request.GET.get('album', None)
    if album:
        # Filter by album. TODO: This may need it's own view.
        if album == 'none':
            # Grab all image without an album set.
            album = ''
        if album == 'all':
            # Grab all images.
            album = None
        else:
            # Filter on user-specified album.
            imagefilter['album'] = album
    else:
        # View a single image by id. TODO: Needs it's own url pattern.
        imageid = request.GET.get('id', None)
        if imageid:
            return view_image_id(request, imageid)

    if request.user.is_staff:
        if request.FILES:
            # Handle file upload.
            alert_class, alert_msg = handle_files(request)
    else:
        if request.FILES:
            log.error(
                'Non-staff tried to upload files: {}'.format(
                    utilities.get_remote_ip(request)))
        # No private images for the public.
        imagefilter['private'] = False

    images = wp_image.objects.filter(**imagefilter)

    if album and (not images):
        alert_msg = 'No album by that name.'
        alert_class = 'error'
        album = None

    if images:
        images = images.order_by('-publish_date')
        # Allow user sort by album.
        if request.GET.get('sort', None) == 'album':
            images = images.order_by('album')

    context = {
        'images': images,
        'album': album,
        'alert_message': alert_msg,
        'alert_class': alert_class
    }
    return responses.clean_response(
        template_name='img/index.html',
        context=context,
        request=request
    )
Exemple #15
0
def error_response(request=None, errnum=500, msgs=None, user_error=None):
    """ Error Response, with optional messages through the messages framework.
        errnum can be 403, 404, or 500,
        (or any other number with a template in /home)

        If msgs is passed, it is sent via the messages framework.
        Arguments:
            request     : Request object from view.
            errnum      : Int, error number (decides which template to use).
            msgs        : Optional error messages for the messages framework.
                          Accepts a list.
            user_error  : Friendly msg to show to the user, usually because it
                          was their fault (invalid request/url).
                          Without it, the default 'sorry, this was my fault..'
                          msg is shown.
    """
    if msgs and isinstance(msgs, str):
        log.warn('Received str for msgs!: {}'.format(msgs))
        msgs = [msgs]

    if not request:
        # This happens when the request isn't passed from the original view.
        return text_response('\n'.join((
            'A developer error occurred.',
            'The Request() object was lost somewhere down the line.',
            'This error has been emailed to me, and I will fix it asap.',
            'Thanks for your patience, -Cj',
            '\nOriginal message:\n{}'.format('\n'.join(msgs)) if msgs else ''
        )))

    # Send messages using the message framework.
    for s in msgs:
        messages.error(request, s)

    context = {
        'server_name': get_server(request),
        'remote_ip': get_remote_ip(request),
        'user_error': user_error,
    }
    templatefile = 'home/{}.html'.format(errnum)
    try:
        rendered = htmltools.render_clean(
            templatefile,
            context=context,
            request=request
        )
    except Exception as ex:
        logmsg = 'Unable to render template: {}\n{}'.format(templatefile, ex)
        log.error(logmsg)
        # Send message manually.
        errmsgfmt = '<html><body>\n{}</body></html>'
        # Style each message.
        msgfmt = '<div style="color: darkred;">{}</div>'
        if msgs:
            errmsgs = '\n'.join((msgfmt.format(m) for m in msgs))
            # Build final html page.
            errmsg = errmsgfmt.format(errmsgs)
        else:
            msgerrnum = 'Error: {}'.format(errnum)
            msgerrtxt = 'There was an error while building this page.'
            errmsg = errmsgfmt.format(
                msgfmt.format('<br>'.join((msgerrnum, msgerrtxt))))
        return HttpResponseServerError(errmsg, status=errnum)
    if not rendered:
        rendered = htmltools.fatal_error_page(
            'Unable to build that page, sorry.'
        )
    # Successfully rendered {errnum}.html page.
    return HttpResponse(rendered, status=errnum)
Exemple #16
0
def get_remote_ip(request):
    """ Make the convenience function available for templates. """

    return utilities.get_remote_ip(request)