问题
I’m using flask to build a web app and I store data in a table called Orders.
I want buyers to have access to a template that will display their order data, like tracking, status, etc. Also I want to give them some actions like the ability to return the order.
For convenience and user experience purposes, I don’t want buyers to register. I want to email them a link that will directly give them access to their order information. So I will create a dynamic route for each order with a token. I also don’t want that token to be really obvious, like order number or something similar, because then anyone can guess an url and return a order that’s not theirs for instance. So it must be unique and a long string of random characters. How should I do it and is this a good approach or bad design?
Thank you!
回答1:
Yes you can do it using Variable Rules from flask, you can put a path in url like this:
@app.route('/user/<path:dinamicPath>')
def show_subpath(dinamicPath):
if dinamicPath == 'order':
order = Order.get() #get your orderns from db or files
return render_template('order.html', order=order)
elif dinamicPath == 'otherStuff':
...
return
"So I will create a dynamic route for each order with a token. I also don’t want that token to be really obvious, like order number or something similar" you can use a UUID, its supported in Variable Rules too, you can look this link enter link description here
回答2:
Try using UUID
's perhaps, for your orders - that can be passed as a query param in your relevant routes. You can create them as:
import uuid
hard_to_guess_string = uuid.uuid4()
another_string = uuid.uuid4()
回答3:
The documentation for uuid.uuid4() says only: "Generate a random UUID", with no guarantees on whether it uses a cryptographic random generator (that is, whether the random values are hard to guess). Even RFC 4122, which specifies UUIDs, says version 4 UUIDs are meant to be generated from "truly-random or pseudo-random numbers", again without any guarantees on cryptographic quality.
For the purposes of generating—
- hard-to-guess values,
- that have to be typed in by end users, and
- serve as bearer credentials whose mere possession grants access to the resource it identifies (a use case explicitly discouraged by RFC 4122 section 6),
a UUID is not appropriate. Instead import the secrets module and generate a random string as follows:secrets.token_hex(16)
or even secrets.token_hex(20)
. Note that unlike uuid
, the secrets
module is documented to generate cryptographically random values. See also Unique Random Identifiers.
Also you should consider adding some form of authorization, such as confirming email address or the like, if you feel you can do so without burdening users. Also, you should consider the temporary nature of order and tracking information.
来源:https://stackoverflow.com/questions/60039972/how-can-i-generate-an-unique-url-for-a-specific-user