adjunct.totp¶
Adjunct has a TOTP implementation, providing a second factor of authentication.
from adjunct import totp
# Instantiate a TOTP object with a reasonable set of defaults
t = totp.TOTP()
# Generate a token
print(t.generate())
To allow the object to be stored in a user's profile, you can use the to_dict
method so you can serialise it as JSON or another format, and subsequently
recreate the object using the from_dict class method.
import json
# Dump it as JSON
t1 = totp.TOTP()
as_json = json.dumps(t1.to_dict())
# Take some previously serialised JSON and recreate the object.
t2 = totp.TOTP.from_dict(json.loads(as_json))
It can also be converted into an OTP key URI, which can be presented to the user so they can add it to their OTP generator.
Finally, to check a code, pass it to check method to validate a code provided by the user.
while True:
otp = input("Enter your TOTP: ")
if t1.check(otp):
break
print("Invalid! Try again.")
print("Valid")
By default it uses the current window and the previous one. You can use the window named argument to change this from the default.
TOTP
¶
An implementation of TOTP (RFC 6238).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
bytes | None
|
A buffer of random bytes acting as a key. Will be generated if None. |
None
|
alg
|
str
|
Hash algorithm to use for the OTP. Defaults to "sha1", but supports sha256 and sha512. |
'sha1'
|
digits
|
int
|
Length of the OTP. Defaults to 6 digits. |
6
|
period
|
int
|
Validity period in seconds of the OTP. Defaults to 30. |
30
|
key_size
|
int
|
If no key is given, the length in bytes of the key go generate. Default to 16. |
16
|
Raises:
| Type | Description |
|---|---|
UnknownHashAlgorithmError
|
If the hash algorithm given is not recognised. |
check(otp, *, window=2, now=None)
¶
Check a TOTP against the current expected TOTP and the previous one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
otp
|
str
|
OTP to check. |
required |
window
|
int
|
Number of windows back in time to use when checking checking the OTP. |
2
|
now
|
int | None
|
A Unix timestamp. Defaults to the current time. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if the OTP matched, False otherwise. |
from_dict(src)
classmethod
¶
Extract the state from a dictionary.
generate(now=None)
¶
to_dict()
¶
Write the state to a dictionary for serialisation.