You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
1.7 KiB
Python
67 lines
1.7 KiB
Python
10 months ago
|
from typing import Union
|
||
|
|
||
|
import uvicorn
|
||
|
|
||
|
from fastapi import FastAPI
|
||
|
from fastapi.responses import RedirectResponse
|
||
|
|
||
|
import config
|
||
|
import database
|
||
|
|
||
|
app = FastAPI()
|
||
|
|
||
|
|
||
|
@app.get("/login")
|
||
|
async def login(token: str):
|
||
|
return RedirectResponse(
|
||
|
f"{config.OAUTH_AUTH_URL}?client_id={config.OAUTH_CLIENT_ID}&redirect_uri={config.OAUTH_REDIRECT_URL}&response_type=code&scope=email&state={token}"
|
||
|
)
|
||
|
|
||
|
|
||
|
@app.get("/callback")
|
||
|
async def oauth_callback(code: str, state: str):
|
||
|
# get the telegram id from the database using the state token
|
||
|
telegram_id = database.get_telegram_id(state)
|
||
|
|
||
|
# do a user info request to get the email address
|
||
|
import requests
|
||
|
|
||
|
response = requests.post(
|
||
|
config.OAUTH_TOKEN_HOST + config.OAUTH_TOKEN_PATH,
|
||
|
data={
|
||
|
"code": code,
|
||
|
"client_id": config.OAUTH_CLIENT_ID,
|
||
|
"client_secret": config.OAUTH_CLIENT_SECRET,
|
||
|
"redirect_uri": config.OAUTH_REDIRECT_URL,
|
||
|
"grant_type": "authorization_code",
|
||
|
},
|
||
|
)
|
||
|
|
||
|
print(response.json())
|
||
|
|
||
|
access_token = response.json()["access_token"]
|
||
|
|
||
|
response = requests.get(
|
||
|
config.OAUTH_USER_INFO_URL,
|
||
|
headers={"Authorization": f"Bearer {access_token}"},
|
||
|
)
|
||
|
|
||
|
print(response.json())
|
||
|
|
||
|
email = response.json()["email"]
|
||
|
|
||
|
# store the username in the database, split at "@" and take the first part
|
||
|
username = email.split("@")[0]
|
||
|
telegram_id = database.get_telegram_id(state)
|
||
|
|
||
|
database.create_user(telegram_id, username)
|
||
|
|
||
|
# redirect to the bot
|
||
|
return RedirectResponse(f"https://t.me/MyBot", status_code=303)
|
||
|
|
||
|
|
||
|
async def start():
|
||
|
config = uvicorn.Config(app=app, port=8000, log_level="info", loop="asyncio")
|
||
|
server = uvicorn.Server(config)
|
||
|
await server.serve()
|