Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use uuid.uuid4() or secrets.token_urlsafe() for hard to guess url and quick select in Postgresql?

I am generating "hard to guess" URL by:

import uuid
url = uuid.uuid4()

URL is stored in Postgres database in field with ordinary index (for quick searching). Datatype of field is uuid: https://www.postgresql.org/docs/9.1/datatype-uuid.html

Another possibility for creating "hard to guess" URL is use secrets module and store it in some Postgres string datatype:

import secrets
url = secrets.token_urlsafe()

What is better for quick searching in database and for safety of random generated url?

Thanks

like image 539
user13978 Avatar asked Nov 07 '22 17:11

user13978


1 Answers

Unlike secrets.token_urlsafe, there is no guarantee about the quality of uuid4. secrets.token_urlsafe is meant for generating a shared secret. uuid4 is meant for generating a likely universally unique identifier.

The thing is you should probably use them both: a secret token and an identifier that you look up in the database:

create table foo (
    id uuid primary key,
    token text not null
);

Notice that the length of the token_urlsafe is supposed to change over time, so that future Python versions are likely to generate a longer string.