uotp/uotp/helper.py

35 lines
933 B
Python
Raw Normal View History

2019-10-07 17:13:42 +00:00
import pyotp
import requests
2019-12-03 16:34:44 +00:00
2019-10-07 17:13:42 +00:00
from os.path import join
2019-12-03 16:34:44 +00:00
from .config import env_vars
2019-10-07 17:13:42 +00:00
def is_valid_otp(etcd_client, name, realm, token):
2019-12-03 16:34:44 +00:00
_key = join(env_vars.get("BASE_PREFIX"), name)
2019-10-07 17:13:42 +00:00
entry = etcd_client.get(_key, value_in_json=True)
if entry:
if realm not in entry.value["realm"]:
return False
2019-10-08 18:07:28 +00:00
totp = pyotp.TOTP(entry.value["seed"])
2019-10-07 17:13:42 +00:00
try:
is_token_valid = totp.verify(token)
2019-12-03 16:34:44 +00:00
except Exception:
2019-10-07 17:13:42 +00:00
return False
else:
return is_token_valid
2019-10-08 18:07:28 +00:00
return False
def create_admin_if_dont_exists(etcd_client):
2019-12-03 16:34:44 +00:00
_key = join(env_vars.get("BASE_PREFIX"), "admin")
2019-10-08 18:07:28 +00:00
if etcd_client.get(_key) is None:
print("admin does not exists!. So, creating one")
_value = {
"seed": pyotp.random_base32(),
2019-12-03 16:34:44 +00:00
"realm": [env_vars.get("ADMIN_REALM")],
}
2019-10-08 18:07:28 +00:00
etcd_client.put(_key, _value, value_in_json=True)