-
Notifications
You must be signed in to change notification settings - Fork 1
Quick Start Guide
Ashwin Shenoy edited this page Jul 11, 2023
·
1 revision
- Install the package from PyPI:
pip install chowkidar-strawberry
- Add
chowkidar
to yourINSTALLED_APPS
:
INSTALLED_APPS = [
...
"chowkidar",
]
- Add
chowkidar.extensions.JWTAuthExtension
to your strawberry schema extensions:-
from chowkidar.extension import JWTAuthExtension
schema = strawberry.Schema(
query=Query,
mutation=Mutation,
extensions=[JWTAuthExtension],
)
- Wrap your Strawberry GraphQL view with
chowkidar.view.auth_enabled_view
in yoururls.py
:
from chowkidar.view import auth_enabled_view
urlpatterns = [
...
path(
"graphql/",
auth_enabled_view(
GraphQLView.as_view(schema=schema, graphiql=settings.DEBUG)
)
),
]
- Create a Refresh Token Model in an app of your choice inheriting the
chowkidar.models.AbstractRefreshToken
abstract model:
class RefreshToken(AbstractRefreshToken, models.Model):
pass
(do not forget run to python manage.py makemigrations
and python manage.py migrate
)
- Add 'REFRESH_TOKEN_MODEL' to your
settings.py
and point it to the Refresh Token Model you created in the previous step:
REFRESH_TOKEN_MODEL = '<your app>.RefreshToken'
- Implement Mutations for
login
andlogout
withissue_tokens_on_login
andrevoke_tokens_on_logout
respectively:
import strawberry
from chowkidar.wrappers import issue_tokens_on_login, revoke_tokens_on_logout
from chowkidar.authentication import authenticate # You may also use your own authentication methods or other methods like `authenticate_with_email` from chowkidar as well.
@strawberry.type
class AuthMutations:
@strawberry.mutation
@issue_tokens_on_login
def login(self, info, username: str, password: str) -> bool:
user = authenticate(username=username, password=password)
if user is None:
raise Exception("Invalid username or password")
# Set LOGIN_USER with the authenticated user's object, in case of successful authentication
# else, set LOGIN_USER to None
info.context.LOGIN_USER = user
return True
@strawberry.mutation
@revoke_tokens_on_logout
def logout(self, info) -> bool:
# Set info.context.LOGIN_USER to True for logging out the user
info.context.LOGOUT_USER = True
return True
All your resolvers will now get the following parameters from info.context
-
-
info.context.userID
- ID of the requesting user, None if not logged-in -
info.context.refreshToken
- Refresh token string of the requesting user, None if not logged-in
Chowkidar comes with 3 authentication methods (importable from chowkidar.authentication
), which you may use -
-
authenticate_with_email
- authenticate with email and password -
authenticate_with_username
- authenticate with username and password -
authenticate
- authenticate with username or email and password