Skip to content

Commit

Permalink
fix: generating signed url without needing access to a private key
Browse files Browse the repository at this point in the history
  • Loading branch information
Muchogoc committed Feb 28, 2022
1 parent 084d29a commit 6e8654a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
4 changes: 2 additions & 2 deletions mycarehub/templates/wagtailmedia/media/add.html
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,9 @@ <h3 id="uploadStatus"></h3>

try {
if (url === '') {
_('fileForm').submit();
_('fileForm').submit();
} else {
uploadFile(url);
uploadFile(url);
}
} catch (err) {
console.log(err);
Expand Down
31 changes: 24 additions & 7 deletions mycarehub/utils/signed_url.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,40 @@
import datetime

from google.auth import compute_engine
from google.auth.exceptions import TransportError
from google.auth.transport import requests
from google.cloud import storage # type: ignore[attr-defined]


def generate_signed_upload_url(bucket_name, blob_name, content_type):
"""
Generates a v4 signed URL for uploading a blob using HTTP PUT.
"""
auth_request = requests.Request()
storage_client = storage.Client()

bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(blob_name)

url = blob.generate_signed_url(
version="v4",
# TODO: set shorter time or get from config
expiration=datetime.timedelta(hours=1),
method="PUT",
content_type=content_type,
)
url = ""

# Retrieve credentials from within the cloudrun environment using a try block
try: # pragma: nocover
signing_credentials = compute_engine.IDTokenCredentials(auth_request, "")
url = blob.generate_signed_url(
version="v4",
credentials=signing_credentials,
expiration=datetime.timedelta(hours=1),
method="PUT",
content_type=content_type,
)
except TransportError:
url = blob.generate_signed_url(
version="v4",
expiration=datetime.timedelta(hours=1),
method="PUT",
content_type=content_type,
)

return url

Expand Down

0 comments on commit 6e8654a

Please sign in to comment.