-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb.py
More file actions
66 lines (49 loc) · 1.77 KB
/
web.py
File metadata and controls
66 lines (49 loc) · 1.77 KB
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
import collections
import hashlib
import hmac
from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from starlette.responses import Response
from config import BOT_TOKEN, ENVIRONMENT
from fake_db import FakeRepo
from models import TelegramAuthModel
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.on_event("startup")
async def startup_event():
...
def check_user_data(data: TelegramAuthModel, token):
secret = hashlib.sha256()
secret.update(token.encode('utf-8'))
sorted_params = collections.OrderedDict(sorted(data.dict().items()))
msg = "\n".join(["{}={}".format(k, v)
for k, v in sorted_params.items() if k != 'hash'])
return data.hash == hmac.new(secret.digest(), msg.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()
async def login_route(request: Request, user: TelegramAuthModel = Depends()) -> Response:
if (ENVIRONMENT.lower().strip() == "production"):
if (not check_user_data(user, BOT_TOKEN)):
raise HTTPException(status_code=401, detail="Nice try hacker :D")
user_from_database = FakeRepo().get_user(user.id)
if (user_from_database["role_id"] == 2):
raise HTTPException(
status_code=401, detail="Sorry you don't have permission")
return templates.TemplateResponse("login.html", {
"request": request,
**user.dict()
})
templates = Jinja2Templates(directory="templates")
app.add_api_route(
'/auth',
login_route,
tags=['Authorize'],
methods=['GET'],
response_class=HTMLResponse,
)