Start learning free

LESSON 16 OF 20 · SECURITY: INTERVIEW QUESTIONS

A Guessable Token in Python

Practice

An interviewer shows you how the shop used to make invite codes for new staff and asks: "Could someone else join with this invite?"

random.seed(int(time.time()))
code = str(random.randint(100000, 999999))
INVITES[code] = email

Yes. Python's random only looks random: from the same seed it gives the same numbers every time, and here the seed is the clock in whole seconds. An attacker who knows roughly when the invite was made (say, the minute the new hire was announced) runs these two lines once for each second of that minute. In 60 tries they hold the code, and they join the staff team in the new hire's place.

Secret values need the secrets module. It takes its randomness from the operating system: there is no seed to guess, and no earlier code tells you the next one. For example, a one-time download link can use secrets.token_hex(8), which gives 16 random hex characters like "3f9a0c1d7b2e8a45". For invite codes, secrets.token_urlsafe(16) turns 16 random bytes into 22 letters, digits, - and _.

The check's requests carry X-Test-Clock: 1767258000 (9:00:00 on 1 January 2026, UTC), which sets the shop's clock. GET /check/guess plays the attacker: it seeds random with that clock and answers the code the old lines would have made.

POST /invites  {"email": "new.staff@example.com"}  →  201  {"code": "…22 random characters…", "email": "new.staff@example.com"}
GET /check/guess                                   →  200  {"guess": "839697"}
POST /join  {"code": "839697"}                     →  400  {"error": "Invalid invite code"}
POST /join  {"code": "…the invite's code…"}        →  201  {"email": "new.staff@example.com", "message": "Welcome to the team"}
POST /join  {"code": "…the invite's code…"}        →  400  {"error": "Invalid invite code"}

Your task: finish create_invite: make the code with secrets.token_urlsafe(16), store it in INVITES with the email as its value, and answer the email and the code with status 201.


Assignment
Follow the Coding Tutorial to make invite codes nobody can predict and to send them back to the admin.


Hint
join already looks codes up in INVITES, so the key is the code and the value is the email. Return a (body, status) tuple: jsonify({...}), 201.


STEP 1 OF 3
    Ctrl + Enter to check

    Secq Weak Random in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free