freeleaps-service-hub/apps/authentication/tests/util/temporary_email.py

77 lines
2.0 KiB
Python

import re
from time import sleep
import requests
from faker import Faker
TEMPORARY_EMAIL_DOMAIN = "https://api.mail.cx/api/v1"
def generate_email() -> str:
fake = Faker('en_US')
while True:
name = fake.name().replace(' ', '_')
if len(name) <= 10:
break
return f"{name}@nqmo.com"
def get_auth_email_token() -> str:
url = TEMPORARY_EMAIL_DOMAIN + "/auth/authorize_token"
headers = {
'accept': 'application/json',
'Authorization': 'Bearer undefined',
}
response = requests.post(url, headers=headers)
return str(response.json())
def get_mail_id(address, token):
url = TEMPORARY_EMAIL_DOMAIN + f"/mailbox/{address}"
headers = {
'accept': 'application/json',
'Authorization': f'Bearer {token}',
}
response = requests.get(url, headers=headers)
body = response.json()
return body[0]['id'] if len(body) and len(body[0]['id']) > 0 else None
def get_auth_code(email):
# get token
token = get_auth_email_token()
print(f"token: {token}")
# Waiting for verification code email
id_ = None
for _ in range(30):
id_ = get_mail_id(email, token)
if id_ is not None:
break
sleep(1)
if id_ is None:
raise Exception(f"Could not get auth code for {email}")
# get code
url = TEMPORARY_EMAIL_DOMAIN + f'/mailbox/{email}/{id_}'
headers = {
'accept': 'application/json',
'Authorization': f'Bearer {token}',
}
response = requests.get(url, headers=headers)
print(response.json())
# Regular matching captcha, here the regular expression matching captcha is changed to its own
captcha = re.search(r'The auth code is:\s+(\d+)', response.json()['body']['html'])
if captcha:
print("code:", captcha.group(1))
else:
print("Unable to find verification code")
return captcha.group(1)
if __name__ == '__main__':
email = generate_email()
code = get_auth_code(email)
print(code)