-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmain.py
81 lines (62 loc) · 2.33 KB
/
main.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
from fastapi import FastAPI, HTTPException
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel, EmailStr
from redis import Redis
from rq import Queue
import jwt
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
from pydantic import parse_obj_as
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
INVALID_IDENTIFIER = 'Please, check identifier.'
INVALID_JWT = 'Of course! You shall not pass!'
JWT_SECRET = os.environ.get('JWT_SECRET')
app = FastAPI()
redis_conn = Redis()
magic_link_queue = Queue('send_magic_links', connection=redis_conn)
class MagicLink(BaseModel):
identifier: EmailStr
payload: dict
def confirm_identifier(magic: MagicLink):
encoded = jwt.encode(jsonable_encoder(magic.dict()), JWT_SECRET, algorithm='HS256').decode('utf-8')
print(f'Payload enconded to JWT: {encoded}')
print(f'sending confirmation to: {magic.identifier}')
message = Mail(
from_email = os.environ.get('SENDGRID_SENDER'),
to_emails = magic.identifier,
subject = 'Are you a bot?',
html_content = f'<a href="http://127.0.0.1:8000/validate/?token={encoded}">Confirm you are human or a super smart bot: </a>'
)
try:
sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(e.body)
return magic.payload
@app.get('/validate/', status_code=204)
def validate(token: str):
try:
magic_link = parse_obj_as(
MagicLink,
jwt.decode(token, JWT_SECRET, algorithms=['HS256'])
)
cred = credentials.Certificate('./serviceAccountKey.json')
firebase_admin.initialize_app(cred)
db = firestore.client()
doc_ref = db.collection('users').document(magic_link.identifier)
doc_ref.set(magic_link.payload)
except Exception as e:
print(e)
error_detail = jsonable_encoder({
'message': INVALID_JWT
})
raise HTTPException(status_code=400, detail=error_detail)
@app.post('/send/', status_code=204)
def send(magic: MagicLink):
magic_link_queue.enqueue(confirm_identifier, magic)