-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #2 from dulmandakh/isAuthenticated-directive
directives: isAuthenticed, isStaff
- Loading branch information
Showing
3 changed files
with
63 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
from .cache import cache | ||
from .decorators import wrap_result | ||
from .directives import IsAuthenticatedDirective, IsStaffDirective | ||
|
||
__all__ = ["cache", "wrap_result"] | ||
__all__ = ["cache", "wrap_result", "IsAuthenticatedDirective", "IsStaffDirective"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
from ariadne import SchemaDirectiveVisitor | ||
from graphql import default_field_resolver | ||
from django.core.exceptions import PermissionDenied | ||
|
||
|
||
class IsAuthenticatedDirective(SchemaDirectiveVisitor): | ||
def visit_field_definition(self, field, _): | ||
original_resolver = field.resolve or default_field_resolver | ||
|
||
def resolve_for_authenticated_user(parent, info, **kwargs): | ||
user = info.context["request"].user | ||
if user and user.is_authenticated: | ||
return original_resolver(parent, info, user=user, **kwargs) | ||
else: | ||
raise PermissionDenied() | ||
|
||
field.resolve = resolve_for_authenticated_user | ||
return field | ||
|
||
|
||
class IsStaffDirective(SchemaDirectiveVisitor): | ||
def visit_field_definition(self, field, _): | ||
original_resolver = field.resolve or default_field_resolver | ||
|
||
def resolve_for_authenticated_user(parent, info, **kwargs): | ||
user = info.context["request"].user | ||
if user and user.is_authenticated and user.is_staff: | ||
return original_resolver(parent, info, user=user, **kwargs) | ||
else: | ||
raise PermissionDenied() | ||
|
||
field.resolve = resolve_for_authenticated_user | ||
return field |