add authentication
add built-in cleanup general refactor
This commit is contained in:
parent
20ee543ab4
commit
ba2e896813
15 changed files with 313 additions and 106 deletions
|
|
@ -5,6 +5,7 @@ from fastapi.security import HTTPBearer
|
|||
import config
|
||||
from fastapi import Request, HTTPException
|
||||
|
||||
from .sql import SessionMaker, Users
|
||||
|
||||
JWT_PUBKEY = open(config.SECRETKEY).read()
|
||||
JWT_ALGORITHM = "RS256"
|
||||
|
|
@ -19,8 +20,9 @@ def decodeJWT(token: str) -> dict:
|
|||
|
||||
|
||||
class JWTBearer(HTTPBearer):
|
||||
def __init__(self, auto_error: bool = True):
|
||||
def __init__(self, account_required=True, auto_error: bool = True):
|
||||
super(JWTBearer, self).__init__(auto_error=auto_error)
|
||||
self.accountRequired = account_required
|
||||
|
||||
async def __call__(self, request: Request):
|
||||
credentials = await super(JWTBearer, self).__call__(request)
|
||||
|
|
@ -30,6 +32,16 @@ class JWTBearer(HTTPBearer):
|
|||
if not self.verify_jwt(credentials.credentials):
|
||||
raise HTTPException(status_code=403, detail="Invalid or expired token.")
|
||||
request.state.jwt = decodeJWT(credentials.credentials)
|
||||
if self.accountRequired:
|
||||
with SessionMaker() as session:
|
||||
sess = SessionMaker()
|
||||
query = sess.query(Users).filter(Users.username == str(request.state.jwt["account"]))
|
||||
first = query.first()
|
||||
if first:
|
||||
if first.temporary:
|
||||
raise HTTPException(status_code=403, detail="Temporary users can't do this")
|
||||
else:
|
||||
raise HTTPException(status_code=403, detail="Somehow you have a valid JWT but no account")
|
||||
return credentials.credentials
|
||||
else:
|
||||
raise HTTPException(status_code=403, detail="Invalid authorization code.")
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue