-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth_functions.py
156 lines (125 loc) · 7.23 KB
/
auth_functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import json
import requests
import streamlit as st
## -------------------------------------------------------------------------------------------------
## Firebase Auth API -------------------------------------------------------------------------------
## -------------------------------------------------------------------------------------------------
def sign_in_with_email_and_password(email, password):
request_ref = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key={0}".format(st.secrets['FIREBASE_WEB_API_KEY'])
headers = {"content-type": "application/json; charset=UTF-8"}
data = json.dumps({"email": email, "password": password, "returnSecureToken": True})
request_object = requests.post(request_ref, headers=headers, data=data)
raise_detailed_error(request_object)
return request_object.json()
def get_account_info(id_token):
request_ref = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo?key={0}".format(st.secrets['FIREBASE_WEB_API_KEY'])
headers = {"content-type": "application/json; charset=UTF-8"}
data = json.dumps({"idToken": id_token})
request_object = requests.post(request_ref, headers=headers, data=data)
raise_detailed_error(request_object)
return request_object.json()
def send_email_verification(id_token):
request_ref = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/getOobConfirmationCode?key={0}".format(st.secrets['FIREBASE_WEB_API_KEY'])
headers = {"content-type": "application/json; charset=UTF-8"}
data = json.dumps({"requestType": "VERIFY_EMAIL", "idToken": id_token})
request_object = requests.post(request_ref, headers=headers, data=data)
raise_detailed_error(request_object)
return request_object.json()
def send_password_reset_email(email):
request_ref = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/getOobConfirmationCode?key={0}".format(st.secrets['FIREBASE_WEB_API_KEY'])
headers = {"content-type": "application/json; charset=UTF-8"}
data = json.dumps({"requestType": "PASSWORD_RESET", "email": email})
request_object = requests.post(request_ref, headers=headers, data=data)
raise_detailed_error(request_object)
return request_object.json()
def create_user_with_email_and_password(email, password):
request_ref = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key={0}".format(st.secrets['FIREBASE_WEB_API_KEY'])
headers = {"content-type": "application/json; charset=UTF-8" }
data = json.dumps({"email": email, "password": password, "returnSecureToken": True})
request_object = requests.post(request_ref, headers=headers, data=data)
raise_detailed_error(request_object)
return request_object.json()
def delete_user_account(id_token):
request_ref = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/deleteAccount?key={0}".format(st.secrets['FIREBASE_WEB_API_KEY'])
headers = {"content-type": "application/json; charset=UTF-8"}
data = json.dumps({"idToken": id_token})
request_object = requests.post(request_ref, headers=headers, data=data)
raise_detailed_error(request_object)
return request_object.json()
def raise_detailed_error(request_object):
try:
request_object.raise_for_status()
except requests.exceptions.HTTPError as error:
raise requests.exceptions.HTTPError(error, request_object.text)
## -------------------------------------------------------------------------------------------------
## Authentication functions ------------------------------------------------------------------------
## -------------------------------------------------------------------------------------------------
def sign_in(email:str, password:str) -> None:
try:
# Attempt to sign in with email and password
id_token = sign_in_with_email_and_password(email,password)['idToken']
# Get account information
user_info = get_account_info(id_token)["users"][0]
# If email is not verified, send verification email and do not sign in
if not user_info["emailVerified"]:
send_email_verification(id_token)
st.session_state.auth_warning = 'Check your email to verify your account'
# Save user info to session state and rerun
else:
st.session_state.user_info = user_info
st.experimental_rerun()
except requests.exceptions.HTTPError as error:
error_message = json.loads(error.args[1])['error']['message']
if error_message in {"INVALID_EMAIL","EMAIL_NOT_FOUND","INVALID_PASSWORD","MISSING_PASSWORD"}:
st.session_state.auth_warning = 'Error: Use a valid email and password'
else:
st.session_state.auth_warning = 'Error: Please try again later'
except Exception as error:
print(error)
st.session_state.auth_warning = 'Error: Please try again later'
def create_account(email:str, password:str) -> None:
try:
# Create account (and save id_token)
id_token = create_user_with_email_and_password(email,password)['idToken']
# Create account and send email verification
send_email_verification(id_token)
st.session_state.auth_success = 'Check your inbox to verify your email'
except requests.exceptions.HTTPError as error:
error_message = json.loads(error.args[1])['error']['message']
if error_message == "EMAIL_EXISTS":
st.session_state.auth_warning = 'Error: Email belongs to existing account'
elif error_message in {"INVALID_EMAIL","INVALID_PASSWORD","MISSING_PASSWORD","MISSING_EMAIL","WEAK_PASSWORD"}:
st.session_state.auth_warning = 'Error: Use a valid email and password'
else:
st.session_state.auth_warning = 'Error: Please try again later'
except Exception as error:
print(error)
st.session_state.auth_warning = 'Error: Please try again later'
def reset_password(email:str) -> None:
try:
send_password_reset_email(email)
st.session_state.auth_success = 'Password reset link sent to your email'
except requests.exceptions.HTTPError as error:
error_message = json.loads(error.args[1])['error']['message']
if error_message in {"MISSING_EMAIL","INVALID_EMAIL","EMAIL_NOT_FOUND"}:
st.session_state.auth_warning = 'Error: Use a valid email'
else:
st.session_state.auth_warning = 'Error: Please try again later'
except Exception:
st.session_state.auth_warning = 'Error: Please try again later'
def sign_out() -> None:
st.session_state.clear()
st.session_state.auth_success = 'You have successfully signed out'
def delete_account(password:str) -> None:
try:
# Confirm email and password by signing in (and save id_token)
id_token = sign_in_with_email_and_password(st.session_state.user_info['email'],password)['idToken']
# Attempt to delete account
delete_user_account(id_token)
st.session_state.clear()
st.session_state.auth_success = 'You have successfully deleted your account'
except requests.exceptions.HTTPError as error:
error_message = json.loads(error.args[1])['error']['message']
print(error_message)
except Exception as error:
print(error)