mirror of
https://gitlab.com/megazordpobeda/DataRush.git
synced 2026-05-22 23:17:09 +00:00
add bearerauth class
This commit is contained in:
@@ -0,0 +1,27 @@
|
|||||||
|
import datetime
|
||||||
|
from typing import Optional, Any
|
||||||
|
|
||||||
|
import jwt
|
||||||
|
from django.conf import settings
|
||||||
|
from django.http import HttpRequest
|
||||||
|
from ninja.security import HttpBearer
|
||||||
|
|
||||||
|
from apps.users.models import User
|
||||||
|
|
||||||
|
|
||||||
|
class BearerAuth(HttpBearer):
|
||||||
|
def authenticate(self, request: HttpRequest, token: str) -> Optional[Any]:
|
||||||
|
data = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
|
||||||
|
if data["exp"] < datetime.datetime.now().timestamp():
|
||||||
|
return None
|
||||||
|
|
||||||
|
user = User.objects.get(id=data["id"])
|
||||||
|
return user
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def generate_jwt(user: User) -> str:
|
||||||
|
data = {
|
||||||
|
"exp": (datetime.datetime.now() + datetime.timedelta(days=365)).timestamp(),
|
||||||
|
"id": user.id
|
||||||
|
}
|
||||||
|
return jwt.encode(data, settings.SECRET_KEY, algorithm="HS256")
|
||||||
Reference in New Issue
Block a user