Vladimir Stazhilov
Vladimir Stazhilov

Reputation: 1954

Check Permissions in FastAPI + Stawberry GraphQL

I'm using BasePermission decorator as specified in documentation.

@strawberry.type
class Query:
    @strawberry.field(permission_classes=[IsAuthenticated])
    def user(self) -> User:
        # get by token OFC
        return User(user_id=1, email="[email protected]", first_name = "Vladimir", last_name = "Kirilov")

In my impementation I use VerifyToken class as described in FastAPI auth0 documentation.

class IsAuthenticated(BasePermission):
    message = "User is not authenticated"

    def has_permission(self, source: Any, info: Info, **kwargs) -> bool:
        print(source)
        print(info)
        token: str = Depends(token_auth_scheme)
        print(token)
        result = VerifyToken(token.credentials).verify()
        if result.get("status"):
            print(result)
            return False

        return True

So I'm trying to get and verify the BEARER from the request, but I'm not able to extract it to process it further and get the error, please advise.

{
  "data": null,
  "errors": [
    {
      "message": "'Depends' object has no attribute 'credentials'",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "user"
      ]
    }
  ]
}

Upvotes: 3

Views: 2203

Answers (1)

Vladimir Stazhilov
Vladimir Stazhilov

Reputation: 1954

Figured it out, not the cleanest way, but here it is

class IsAuthenticated(BasePermission):
    message = "User is not authenticated"
    
    async def has_permission(self, source: Any, info: Info, **kwargs) -> bool:


        request: Union[Request, WebSocket] = info.context["request"]
        print(request.headers)
        if "Authorization" in request.headers:
            print(request.headers['Authorization'])
            result = VerifyToken( request.headers['Authorization'][7:] ).verify()
            if result.get("status") == "error":
                print(result.get("msg"))
                return False
            if result.get("sub"):
                print(result)
                return True
        return False
    

Upvotes: 3

Related Questions