# This is a slightly modified version of django.contrib.syndication.views
from django.contrib.syndication import feeds
from django.http import HttpResponse, HttpResponseRedirect, Http404

# Define which feeds require authentication
auth_required = ['mystuff']

def feed(request, url, feed_dict=None):
    if not feed_dict:
        raise Http404, "No feeds are registered."

    try:
        slug, param = url.split('/', 1)
    except ValueError:
        slug, param = url, ''

    # Check if feed requires authentication
    if slug in auth_required:
        # Yes: check authentication
        if request.user.is_authenticated():
            try:
                f = feed_dict[slug]
            except KeyError:
                raise Http404, "Slug %r isn't registered." % slug

            try:
                feedgen = f(slug, request).get_feed(param)
            except feeds.FeedDoesNotExist:
                raise Http404, "Invalid feed parameters. Slug %r is valid, but other parameters, or lack thereof, are not." % slug

            response = HttpResponse(mimetype=feedgen.mime_type)
            feedgen.write(response, 'utf-8')
            return response
        # No: redirect to login page
        else:
            # Redirect User to login page, and send them back to their feed after the provide their credentials
            return HttpResponseRedirect('/accounts/login/?next=%s' % request.path)
    # No authentication required
    else:
        try:
            f = feed_dict[slug]
        except KeyError:
            raise Http404, "Slug %r isn't registered." % slug

        try:
            feedgen = f(slug, request).get_feed(param)
        except feeds.FeedDoesNotExist:
            raise Http404, "Invalid feed parameters. Slug %r is valid, but other parameters, or lack thereof, are not." % slug

        response = HttpResponse(mimetype=feedgen.mime_type)
        feedgen.write(response, 'utf-8')
        return response