tags:

views:

643

answers:

5

Wondering if there is a good way to generate temporary URLs that expire in X days. Would like to email out a URL that the recipient can click to access a part of the site that then is inaccessible via that URL after some time period. No idea how to do this, with Django, or Python, or otherwise.

A: 

You could set this up with URLs like:

http://yoursite.com/temp/1a5h21j32

Your URLconf would look something like this:

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^temp/(?P<hash>\w+)/$', 'yoursite.views.tempurl'),
)

...where tempurl is a view handler that fetches the appropriate page based on the hash. Or, sends a 404 if the page is expired.

bigmattyh
+1  A: 

It depends on what you want to do - one-shot things like account activation or allowing a file to be downloaded could be done with a view which looks up a hash, checks a timestamp and performs an action or provides a file.

More complex stuff such as providing arbitrary data would also require the model containing some reference to that data so that you can decide what to send back. Finally, allowing access to multiple pages would probably involve setting something in the user's session and then using that to determine what they can see, followed by a redirect.

If you could provide more detail about what you're trying to do and how well you know Django, I can make a more specific reply.

Dial Z
What I want to do is provide access to a form via the temporary URL, so the targeted visitor could go to the URL within X days (before link expires) and it would bring up the form. The form would be prepopulated with data that would differ with each URL generated. So same form, different data per URL.
chacmool
+1  A: 

models

class TempUrl(models.Model):
    url_hash = models.CharField("Url", blank=False, max_length=32, unique=True)
    expires = models.DateTimeField("Expires")

views

def generate_url(request):
    # do actions that result creating the object and mailing it

def load_url(request, hash):
    url = get_object_or_404(TempUrl, url_hash=hash, expires__gte=datetime.now())
    data = get_some_data_or_whatever()
    return render_to_response('some_template.html', {'data':data}, 
                              context_instance=RequestContext(request))

urls

urlpatterns = patterns('', url(r'^temp/(?P<hash>\w+)/$', 'your.views.load_url', name="url"),)

//of course you need some imports and templates

zalew
+3  A: 

If you don't expect to get a large response rate, then you should try to store all of the data in the URL itself. This way, you don't need to store anything in the database, and will have data storage proportional to the responses rather than the emails sent.

Updated: Let's say you had two strings that were unique for each user. You can pack them and unpack them with a protecting hash like this:

import hashlib, zlib
import cPickle as pickle

my_secret = "michnorts"

def encode_data(data):
    """Turn `data` into a hash and an encoded string, suitable for use with `decode_data`."""
    text = zlib.compress(pickle.dumps(data, 0)).encode('base64').replace('\n', '')
    m = hashlib.md5(my_secret + text).hexdigest()[:12]
    return m, text

def decode_data(hash, enc):
    """The inverse of `encode_data`."""
    text = urllib.unquote(enc)
    m = hashlib.md5(my_secret + text).hexdigest()[:12]
    if m != hash:
        raise Exception("Bad hash!")
    data = pickle.loads(zlib.decompress(text.decode('base64')))
    return data

hash, enc = encode_data(['Hello', 'Goodbye'])
print hash, enc
print decode_data(hash, enc)

This produces:

849e77ae1b3c eJzTyCkw5ApW90jNyclX5yow4koMVnfPz09JqkwFco25EvUAqXwJnA==
['Hello', 'Goodbye']

In your email, include a URL that has both the hash and enc values (properly url-quoted). In your view function, use those two values with decode_data to retrieve the original data.

The zlib.compress may not be that helpful, depending on your data, you can experiment to see what works best for you.

Ned Batchelder
Basically each URL would be for one user to access, so not a large response rate. This idea sounds interesting but I'm not quite getting it 100%--a small example would be great!
chacmool
+1  A: 

I think the solution lies within a combination of all the suggested solutions. I'd suggest using an expiring session so the link will expire within the time period you specify in the model. Combined with a redirect and middleware to check if a session attribute exists and the requested url requires it you can create somewhat secure parts of your site that can have nicer URLs that reference permanent parts of the site. I use this for demonstrating design/features for a limited time. This works to prevent forwarding... I don't do it but you could remove the temp url after first click so only the session attribute will provide access thus more effectively limiting to one user. I personally don't mind if the temp url gets forwarded knowing it will only last for a certain amount of time. Works well in a modified form for tracking invited visits as well.

mogga
Interesting. Not sure I get the method to prevent forwarding, would love to hear more detail on that approach.
chacmool
what i mean by forwarding is someone sending a link to someone else. You set the cookie once and flag it set in your app such that anyone else accessing the URL won't have access because they don't have the cookie.
mogga