views:

81

answers:

2

Hello. I am working on a project that requires password protected downloading, but I'm not exactly sure how to implement that. If the target file has a specific extension (.exe, .mp3, .mp4, etc), I want to prompt the user for a username and password. Any ideas on this?

I am using Python 26 on Windows XP.

+2  A: 

This is best implemented at the web server level.

If you are using Apache, this can be done by placing the files you desire to protect in a directory with an htaccess file which requires user authentication.

Then, implement HTTP Basic Auth in your Python script to download the files. Make sure to use an SSL connection; basic auth sends the user's password over the wire in the clear.

Borealid
Without the trick of the ever-changing realm as per my answer below, the user will need to enter their credentials only once, then their browser will remember and automatically resend them -- that does not seem to match the OP's specs. (I don't know enough Apache black magic to know if the ever-changing realm can be implemented there easily -- if so, seems an issue for serverfault.com anyway;-).
Alex Martelli
+1  A: 

Use HTTP's basic authentication (shown in the URL I've quoted from the client side):

  1. whenever a "sensitive" page or file is requested, and no Authorization header is part of the request (or it's invalid, see below), return a 401 status code instead, with a header WWW-Authenticate: Basic realm=XXXX (where XXXX is a hash of the URL, e.g. with MD5 or SHA1, to make it essentially unique per-file)
  2. the user will then need to enter username and password at his browser, which will send them back to the server you're implementing with the simple algorithm shown at that URL, namely:

    import base64 base64string = base64.encodestring('%s:%s' % (username, password))[:-1] req.add_header("Authorization", "Basic %s" % base64string)

  3. when the Authorization header is present in the request, decode the base64 string it presents after 'Basic ' and check that it has the username:password you want

You can use more sophisticated authentication, of course, but this may get you started unless the user's connection can (or so you suspect) be "sniffed" by evil third parties (in which case you'll want to use HTTPS anyway, so that basic auth becomes OK again;-).

Alex Martelli
"decode the base53 string it presents" you mean the base64 string?
Technofreak
@Techno, oops, yes, off-by-one typo from fast typing w/wrong parallax, fixing now, tx!-)
Alex Martelli
Just trying to prove you are not a bot, eh :)
gnibbler
@gnibbler, darn, you caught my new subtle masking strategy, I'll have to reset and try a new one!
Alex Martelli