Securing endpoints with access tokens
Previously, we learned how to implement a simple dependency to protect an endpoint with a header. Here, we'll also retrieve a token from a request header, but then, we'll have to check the database to see if it's valid. If it is, we'll be able to return the corresponding user.
Let's see what our dependency looks like:
app.py
async def get_current_user( token: str = Depends(OAuth2PasswordBearer(tokenUrl="/token")), ) -> UserTortoise: try: access_token: AccessTokenTortoise = await AccessTokenTortoise.get( access_token=token, expiration_date__gte=timezone.now() ).prefetch_related("user") return cast(UserTortoise, access_token.user)...