pythonauthenticationdownloadflasksession-timeout

How to provide temporary download url in Flask?


Currently, my index.html file contains

<a href="static/file.ext">Download</a>

I want to change this so that the download url is only valid for a certain time. For example, how would I change it to

<a href="get_file?file=file.ext&token=TEMPORARYTOKEN">Download</a>

In my Flask file, I could then have

@app.route('/get_file')
def get_file():
    filename = request.args.get('file')
    token = request.args.get('token')
    if token is valid: # what can be done here
        return send_from_directory('static', filename)

How can I generate and handle the token? Or am I approaching this completely wrong?


Solution

  • There are a couple ways you can do this.

    1. Generate a UUID for your token and store it in a db table along with the desired expiration datetime. Then when someone calls the URL with the token, you can just check it against the db for validity and expiration.

    2. If you don't want to use a db to store the tokens, you can use GPG to encrypt a string that contains the expiration datetime and use the resulting encrypted string as your token. This means your token will be a lot longer than a UUID, but you'd avoid having to use a db.

    I recommend using UUID and a db table.