Added auth

This commit is contained in:
2022-05-29 00:31:32 +02:00
parent 36bb9eeefa
commit 23d514050d
19 changed files with 815 additions and 59 deletions

35
api/token.py Normal file
View File

@@ -0,0 +1,35 @@
import os
import typing
from datetime import datetime
from datetime import timedelta
from datetime import timezone
import jwt
from fastapi import Request
from starlette.datastructures import Headers
from api.models import UserModel
if typing.TYPE_CHECKING:
UserTokenData = dict[str, typing.Any]
JWT_SECRET = os.getenv("JWT_SECRET", "")
def encode_user_token(
user: UserModel, expire_in: timedelta = timedelta(hours=6)
) -> str:
payload = {}
payload["id"] = user.id
payload["exp"] = datetime.now(tz=timezone.utc) + expire_in
return jwt.encode(payload, JWT_SECRET)
def decode_user_token(token: str) -> "UserTokenData":
return jwt.decode(token, JWT_SECRET, ["HS256"])
def token_from_headers(headers: Headers) -> tuple[str, str]:
auth_header: str = headers.get("authorization", "")
scheme, _, auth_token = auth_header.partition(" ")
return scheme, auth_token