-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.py
213 lines (173 loc) · 5.91 KB
/
routes.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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
from typing import Optional
from fastapi import APIRouter
from pathlib import Path
import sys
import os
from pydantic import BaseModel
import base64
from dotenv import load_dotenv
load_dotenv()
ENV = os.getenv("ENV", "development")
SELF_URL = os.getenv('SELF_URL')
FRONTEND_URL = os.getenv('FRONTEND_URL')
if not SELF_URL or not FRONTEND_URL:
raise ValueError('SELF_URL or FRONTEND_URL not found in .env file')
if ENV == "development":
path_root = Path(__file__).parents[1]
sys.path.append(os.path.join(path_root))
sys.path.append(os.path.join(path_root, 'backend'))
else:
print("Production")
print(os.getcwd())
print(os.path.dirname(__file__))
print(os.listdir('/'))
sys.path.append('/')
sys.path.append('/backend')
from backend.signer import Signer, SignatureType, SMTPConfig, UserConfig, EmailConfig
from backend.rsa import RSA, verify_by_base64_key
router = APIRouter()
class EmailVerifyModel(BaseModel):
email: str
ps_message: str
ps_signature: str
class KeyVerifyModel(BaseModel):
base64_key: str
ps_message: str
ps_signature: str
class SendModel(BaseModel):
name: str
role: str
email: str
latin_name: str
latin_role: str
password: str
recipients: Optional[str | list[str]] = None
cc: Optional[str | list[str]] = None
bcc: Optional[str | list[str]] = None
subject: str
message_body: str
reply_to: Optional[str] = None
def convert_recipients(recipients):
if isinstance(recipients, str):
return [recipients]
elif isinstance(recipients, list):
return recipients
return None
def verify_by_email(email: str, ps_message: str, ps_signature: str) -> bool:
rsa = RSA(email)
return rsa.verify(ps_signature, ps_message)
@router.get("/")
def read_root():
return {"message": "Hello World"}
@router.get("/key")
def get_public_key(user_email: str):
try:
if not RSA.is_user_key_present(user_email):
return {"status": "notfound", "error": "No key found for user", "public_key": ""}
rsa = RSA(user_email)
key_str = rsa.get_public_key()
return {"status": "ok", "public_key": key_str, "error": ""}
except Exception as e:
return {"status": "error", "error": str(e), "public_key": ""}
@router.post("/verify/email")
def verify_email(verify_model: EmailVerifyModel):
result = verify_by_email(verify_model.email, verify_model.ps_message, verify_model.ps_signature)
if result:
return {"verified": True}
return {"verified": False}
@router.get("/verify/email")
def verify_email(email: str, ps_message: str, ps_signature: str):
try:
result = verify_by_email(email, ps_message, ps_signature)
if result:
return {
"email": email,
"ps_message": ps_message,
"signature": {
'status': 'valid',
"ps": ps_signature,
},
"comment": {
"jp": "この電子メールは正しいです。",
"en": "This email is valid."
}
}
return {
"email": email,
"ps_message": ps_message,
"signature": {
'status': 'invalid',
"ps": ps_signature,
},
"comment": {
"jp": "この電子メールは無効です。",
"en": "This email is invalid."
}
}
except Exception as e:
print(f"Error verifying email: {e}")
return {
"email": email,
"ps_message": ps_message,
"signature": {
'status': 'error/invalid',
"ps": ps_signature,
},
"comment": {
"en": "An error occurred. The email most likely is invalid.",
"jp": "エラーが発生しました。おそらく電子メールは無効です。"
}
}
@router.post("/verify/key")
def verify_key(verify_model: KeyVerifyModel):
result = verify_by_base64_key(verify_model.base64_key, verify_model.ps_message, verify_model.ps_signature)
if result:
return {"verified": True}
return {"verified": False}
@router.post("/send/{provider}")
def send_email(provider: str, send_model: SendModel):
if provider not in ['gmail', 'outlook']:
print(f"Invalid provider: {provider}")
return {"error": "Invalid provider"}
server = 'smtp.gmail.com' if provider == 'gmail' else 'smtp.office365.com'
user_config = UserConfig(
send_model.name,
send_model.email,
send_model.password,
send_model.role,
send_model.latin_name,
send_model.latin_role
)
recipients = convert_recipients(send_model.recipients)
cc = convert_recipients(send_model.cc)
bcc = convert_recipients(send_model.bcc)
subject = send_model.subject
message_body = send_model.message_body
email_config = EmailConfig(
subject,
message_body,
[recipients] if isinstance(recipients, str) else recipients,
[cc] if isinstance(cc, str) else cc,
[bcc] if isinstance(bcc, str) else bcc,
send_model.reply_to
)
if not email_config.is_valid():
print(f"Invalid email configuration: {email_config}")
return {"error": "Invalid email configuration"}
smp_config = SMTPConfig(server, 587)
signer = Signer(
user_config,
smp_config,
os.path.join('backend', 'email.html'),
FRONTEND_URL,
SignatureType.SIMPLE
)
if ENV == "dev":
print("Development mode")
print("Message: ", email_config.message_body)
print(f"Sending email: {email_config}")
return {"sent": True, "message": "TEST Email sent"}
result = signer.send_email(email_config)
if result.success:
return {"sent": True, "message": result.response}
return {"sent": False, "error": result.error}