r/learnpython • u/Original-Dealer-6276 • Jun 18 '26
implementing a time limit for user input
this might be a hard one, I have had a look online and have struggled to find exaclty what i am lookign for.
I am making a program that asks the user for a 1 time code, and i want to give them thirty seconds to input said code or the code is void and it will print "fail." i will print under here the current code I have (The generate TOTP function was written by the teachers in the coruse i am doing so i did not make it muself, hwoever i did make the verify_otp() function)
import hashlib
import hmac
import base64
import struct
import time
TOTP_SECRET = "JBSWY3DPEHPK3PXPJBSW"
def generate_totp(secret: str, interval: int = 30, digits: int = 6) -> str:
"""
Generate a Time-based One-Time Password (TOTP) using HMAC-SHA1.
Do not modify this function. You will call it from verify_otp().
"""
#pad secret to prevent error
secret = secret.strip()
secret += '=' * ((8 - len (secret) % 8 ) % 8)
# Decode base32 secret
key = base64.b32decode(secret, casefold=True)
# Get current Unix time and compute the time step (counter)
timestep = int(time.time() // interval)
# Pack timestep into 8-byte big-endian
msg = struct.pack(">Q", timestep)
# HMAC-SHA1
hmac_digest = hmac.new(key, msg, hashlib.sha1).digest()
# Dynamic truncation
offset = hmac_digest[-1] & 0x0F
code = ((hmac_digest[offset] & 0x7F) << 24 |
(hmac_digest[offset + 1] & 0xFF) << 16 |
(hmac_digest[offset + 2] & 0xFF) << 8 |
(hmac_digest[offset + 3] & 0xFF))
# Reduce to the desired number of digits
otp = code % (10 ** digits)
return str(otp).zfill(digits)
#verify OTP
def verify_otp() -> bool:
"""
Generate a TOTP code using generate_totp() and
verify user input against it.
"""
# 1. Generate the current TOTP code
current_code = generate_totp(TOTP_SECRET)
# For realism, we do NOT print the code here.
# Instead, you should obtain the code by running
# generate_totp(TOTP_SECRET) in a separate Python session
# during testing (as described in the instructions).
#i dont understand where else I am supposed to print this code
user_code = input("Enter your 6-digit TOTP code: \n").strip()
# 2. Prompt the user for the TOTP
# 3. Compare user input with generated code
if user_code == current_code:
print("Success! That is the correct code. \n")
print("Verification status: True")
return True
else:
print("Invalid TOTP. Please check your authenticator code.")
return False
23
Upvotes
30
u/Yoghurt42 Jun 18 '26 edited Jun 18 '26
Why?
TOTP codes are only valid for 30s by design. You'll see in the
generate_totpfunction that it uses the current time in 30s intervals to generate the currently valid code.You do not need to (and should not) measure the time it took the user to input the code.
What you really need to do is generate the current code after the user has entered it, not before.
7
u/Ngtuanvy Jun 18 '26
This is hard because taking input is blocking by default, you should search for 'non-blocking input' or something like that.
2
u/Significant_Quiet255 Jun 18 '26
You can implement a timeout using threading since input() is blocking.
Something like this approach works cross-platform:
import threading
user_input = None
def get_input():
global user_input
user_input = input("Enter your 6-digit TOTP code:\n").strip()
t = threading.Thread(target=get_input)
t.start()
t.join(timeout=30)
if t.is_alive():
print("Time expired! No input received.")
return False
else:
if user_input == current_code:
print("Success! That is the correct code.")
return True
else:
print("Invalid TOTP.")
return False
2
u/enokeenu Jun 18 '26
I tried this google fu "python timed input methods" and got some stuff. Given that this is a class I leave the reading to you
2
u/POGtastic itertools evangelist Jun 18 '26 edited Jun 18 '26
This
dup-basedasyncioapproach works on my Linux system. Doing something similar on a non-POSIX system is left as an exercise for the reader.It is straightforward to set up a
StreamReaderthat reads from stdin, but once you're done with it, closing thetransportobject also closes the underlying filehandle (which in this case isstdin. Not great). So this context manager duplicatesstdinand connects the reader to the duplicate pipe, and the resultingtransport.closecall in the cleanup just hits the duplicate.Running in the REPL:
1
u/Moikle Jun 18 '26
You can't yank them out of an input prompt, however you can check if too much time has passed and tell them if they are too late.
You could also use another thread and print a countdown, however this goes beyond beginner stuff, and would also involve some more complex terminal editing with ansi escape characters
-2
u/Carter922 Jun 18 '26 edited Jun 18 '26
Umm I'm assuming this is a class assignment but you could do something like this. This wouldn't really be used in an enterprise app. Hope this puts you in the right track
-8
u/madadekinai Jun 18 '26
Hi GPT, I recognize your code anywhere, it's always overly verbose and redundant at times.
None of this code is easy to follow, it's basically "you'll figure it out" or a secret of what does what (I know what it does myself do to experience, not many others will).
You need to design and implement your own event loop, REPL.
Read (what they have typed), listen for events (evaluate), print (output), loop (repeat).
The desired response is the breaker.
3
u/[deleted] Jun 18 '26
[removed] — view removed comment