Initial commit
This commit is contained in:
48
folkugat_web/services/auth.py
Normal file
48
folkugat_web/services/auth.py
Normal file
@@ -0,0 +1,48 @@
|
||||
import datetime
|
||||
from typing import Annotated, Optional
|
||||
|
||||
import jwt
|
||||
from fastapi import Cookie, Depends, HTTPException
|
||||
from folkugat_web.config import auth as config
|
||||
from folkugat_web.log import logger
|
||||
|
||||
|
||||
def login(value):
|
||||
if value and value.lower() == config.ADMIN_PASSWORD:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def logged_in(nota_folkugat: Annotated[Optional[str], Cookie()] = None) -> bool:
|
||||
if not nota_folkugat:
|
||||
return False
|
||||
try:
|
||||
payload = jwt.decode(nota_folkugat, config.JWT_SECRET, algorithms=["HS256"])
|
||||
except Exception as exc:
|
||||
logger.error("Exception: ", exc)
|
||||
return False
|
||||
|
||||
return payload.get('user') == 'admin'
|
||||
|
||||
|
||||
LoggedIn = Annotated[bool, Depends(logged_in)]
|
||||
|
||||
|
||||
def require_login(logged_in: LoggedIn) -> bool:
|
||||
if not logged_in:
|
||||
raise HTTPException(status_code=403, detail="Must be logged in")
|
||||
return True
|
||||
|
||||
|
||||
RequireLogin = Annotated[bool, Depends(require_login)]
|
||||
|
||||
|
||||
def build_payload():
|
||||
return {
|
||||
'user': 'admin',
|
||||
'exp': datetime.datetime.now(tz=datetime.timezone.utc) + config.SESSION_DURATION
|
||||
}
|
||||
|
||||
|
||||
def build_token():
|
||||
return jwt.encode(build_payload(), config.JWT_SECRET, algorithm="HS256")
|
||||
Reference in New Issue
Block a user