Commits

Anonymous committed 11dff85

[svn r19] Added secures3.py file

Comments (0)

Files changed (1)

+import hmac
+import time
+import base64
+import urllib
+import hashlib
+
+
+def gen_signature(secret_key, string_to_sign):
+    return base64.b64encode(
+        hmac.new(
+            secret_key,
+            string_to_sign,
+            hashlib.sha1
+        ).digest()
+    )
+
+
+def return_secure_link(key, secret_key, bucket, 
+                                filename, expires=300, timestamp=None):
+    ''' Return a secure S3 link with an expiration on the download.
+
+        key: S3 Access Key (login)
+        secret_key: S3 Secret Access Key (password)
+        bucket: Bucket name
+        filename: file path
+        expires: Seconds from NOW the link expires
+        timestamp: Epoch timestamp. If present, "expires" will not be used.
+    '''
+    filename = urllib.quote_plus(filename)
+    filename = filename.replace('%2F', '/')
+    path = '/%s/%s' % (bucket, filename)
+
+    if timestamp is not None:
+        expire_time = timestamp
+    else:
+        expire_time = time.time() + expires
+
+    string_to_sign = 'GET\n\n\n%f\n%s' % (expire_time, path)
+    params = {
+        'AWSAccessKeyId': key,
+        'Expires': '%.0f' % (expire_time),
+        'Signature': gen_signature(secret_key, string_to_sign),
+    }
+
+    return 'http://%s.s3.amazonaws.com/%s?%s' % (
+                                    bucket, filename, urllib.urlencode(params))