-
Notifications
You must be signed in to change notification settings - Fork 324
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
8be1d9e
commit 7013dab
Showing
26 changed files
with
738 additions
and
158 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import json | ||
from dataclasses import asdict, dataclass | ||
from datetime import datetime | ||
from typing import Annotated, Any, Self | ||
|
||
import jwt | ||
from fastapi import Header, HTTPException | ||
|
||
JWT_SECRET = 'secret' | ||
|
||
|
||
@dataclass | ||
class User: | ||
email: str | None | ||
extra: dict[str, Any] | ||
|
||
def encode_token(self) -> str: | ||
return jwt.encode(asdict(self), JWT_SECRET, algorithm='HS256', json_encoder=CustomJsonEncoder) | ||
|
||
@classmethod | ||
async def from_request(cls, authorization: Annotated[str, Header()] = '') -> Self | None: | ||
try: | ||
token = authorization.split(' ', 1)[1] | ||
except IndexError: | ||
return None | ||
|
||
try: | ||
return cls(**jwt.decode(token, JWT_SECRET, algorithms=['HS256'])) | ||
except jwt.DecodeError: | ||
raise HTTPException(status_code=401, detail='Invalid token') | ||
|
||
|
||
class CustomJsonEncoder(json.JSONEncoder): | ||
def default(self, obj: Any) -> Any: | ||
if isinstance(obj, datetime): | ||
return obj.isoformat() | ||
else: | ||
return super().default(obj) |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.