Skip to content

Commit c825c16

Browse files
AsifArmanRahmankinguardohereisamara
committed
fix(storage): proper link generate with 𝘨𝘦𝘡_𝘢𝘳𝘭
1️⃣ 𝘡𝘰𝘬𝘦𝘯 param is now optional. 2️⃣ 𝘦𝘹𝘱π˜ͺ𝘳𝘒𝘡π˜ͺ𝘰𝘯_𝘩𝘰𝘢𝘳, an optional param added which works only for link generated with admin credentials. 3️⃣ resolves proper link generation with the use of 𝘡𝘰𝘬𝘦𝘯 param. 4️⃣ resolves link generation of any user protected file, instead of links for public to anyone contents. Co-Authored-By: Daniel Marconi <[email protected]> Co-Authored-By: Khin Eaindray Htun <[email protected]>
1 parent 399a917 commit c825c16

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

β€Žfirebase/storage/__init__.pyβ€Ž

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
https://firebase.google.com/docs/reference/rest/storage/rest
1313
"""
1414

15+
import datetime
1516
import requests
1617
from gcloud import storage
1718
from urllib.parse import quote
@@ -224,26 +225,46 @@ def download(self, filename, token=None):
224225
for chunk in r:
225226
f.write(chunk)
226227

227-
def get_url(self, token):
228+
def get_url(self, token=None, expiration_hour=24):
228229
""" Fetches URL for file.
229230
230231
231232
:type token: str
232-
:param token: Firebase Auth User ID Token.
233+
:param token: (Optional) Firebase Auth User ID Token, defaults
234+
to :data:`None`.
233235
236+
:type expiration_hour: int
237+
:param expiration_hour: (Optional) time in ``hour`` for URL to
238+
expire after, defaults to 24 hours. Works only for links
239+
generated with admin credentials.
234240
235241
:return: URL for the file.
236242
:rtype: str
237243
"""
238244

245+
# reset path
239246
path = self.path
240247
self.path = None
241248

249+
# remove leading backlash
242250
if path.startswith('/'):
243251
path = path[1:]
244252

245-
if token:
246-
return "{0}/o/{1}?alt=media&token={2}".format(self.storage_bucket, quote(path, safe=''), token)
253+
if self.credentials:
254+
blob = self.bucket.get_blob(path)
255+
if blob:
256+
return blob.generate_signed_url(datetime.timedelta(hours=expiration_hour), method='GET')
257+
258+
elif token:
259+
260+
# retrieve download tokens first
261+
headers = {"Authorization": "Bearer " + token}
262+
request_ref = "{0}/o/{1}".format(self.storage_bucket, quote(path, safe=''))
263+
request_object = self.requests.get(request_ref, headers=headers)
264+
265+
raise_detailed_error(request_object)
266+
267+
return "{0}/o/{1}?alt=media&token={2}".format(self.storage_bucket, quote(path, safe=''), request_object.json()['downloadTokens'])
247268

248269
return "{0}/o/{1}?alt=media".format(self.storage_bucket, quote(path, safe=''))
249270

0 commit comments

Comments
Β (0)