11import base64
22import json
33import logging
4- from typing import Any , Dict , Optional
4+ from typing import Any , Optional
55from uuid import UUID
66
77from fastapi import Depends , HTTPException , Request
88from fastapi .exceptions import HTTPException
9- from fastapi .openapi .models import OAuthFlows as OAuthFlowsModel
10- from fastapi .security import OAuth2
119from fastapi .security .utils import get_authorization_scheme_param
12- from starlette .status import HTTP_401_UNAUTHORIZED
13- from web3login .auth import MoonstreamRegistration , to_checksum_address , verify
10+ from web3login .auth import to_checksum_address , verify
1411from web3login .exceptions import MoonstreamVerificationError
12+ from web3login .middlewares .fastapi import OAuth2BearerOrSignature
1513
1614from . import actions , data
1715from .db import yield_db_read_only_session
2018logger = logging .getLogger (__name__ )
2119
2220
23- class OAuth2BearerOrSignature (OAuth2 ):
24- """
25- Extended FastAPI OAuth2 middleware to support Bearer token
26- and Moonstream Web3 base64 signature in one request.
27- """
28-
29- def __init__ (
30- self ,
31- tokenUrl : str ,
32- scheme_name : Optional [str ] = None ,
33- scopes : Optional [Dict [str , str ]] = None ,
34- description : Optional [str ] = None ,
35- auto_error : bool = True ,
36- ):
37- if not scopes :
38- scopes = {}
39- flows = OAuthFlowsModel (password = {"tokenUrl" : tokenUrl , "scopes" : scopes })
40- super ().__init__ (
41- flows = flows ,
42- scheme_name = scheme_name ,
43- description = description ,
44- auto_error = auto_error ,
45- )
46-
47- async def __call__ (self , request : Request ) -> Optional [str ]:
48- authorization : str = request .headers .get ("Authorization" )
49- scheme , param = get_authorization_scheme_param (authorization )
50- if not authorization or (
51- scheme .lower () != "moonstream" and scheme .lower () != "bearer"
52- ):
53- if self .auto_error :
54- raise HTTPException (
55- status_code = HTTP_401_UNAUTHORIZED ,
56- detail = "Not authenticated" ,
57- headers = {"WWW-Authenticate" : "moonstream/bearer" },
58- )
59- else :
60- return None
61- return param
62-
63-
6421# Login implementation follows:
6522# https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/
6623oauth2_scheme = OAuth2BearerOrSignature (tokenUrl = "token" )
@@ -85,8 +42,7 @@ async def get_current_user(
8542 if scheme == "moonstream" :
8643 payload_json = base64 .decodebytes (str (token ).encode ()).decode ("utf-8" )
8744 payload = json .loads (payload_json )
88- moonstream_schema : Any = MoonstreamRegistration # mypy hell
89- verified = verify (authorization_payload = payload , schema = moonstream_schema )
45+ verified = verify (authorization_payload = payload , schema = "registration" )
9046 if not verified :
9147 logger .info ("Moonstream verification error" )
9248 raise MoonstreamVerificationError ()
@@ -159,8 +115,7 @@ async def get_current_user_with_groups(
159115 if scheme == "moonstream" :
160116 payload_json = base64 .decodebytes (str (token ).encode ()).decode ("utf-8" )
161117 payload = json .loads (payload_json )
162- moonstream_schema : Any = MoonstreamRegistration # mypy hell
163- verified = verify (authorization_payload = payload , schema = moonstream_schema )
118+ verified = verify (authorization_payload = payload , schema = "registration" )
164119 if not verified :
165120 logger .info ("Moonstream authorization verification error" )
166121 raise MoonstreamVerificationError ()
0 commit comments