Skip to content

Commit

Permalink
Merge pull request #2 from dulmandakh/isAuthenticated-directive
Browse files Browse the repository at this point in the history
directives: isAuthenticed, isStaff
  • Loading branch information
dulmandakh authored Oct 8, 2021
2 parents d65f9c0 + 7e11cfa commit f0f7bed
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 1 deletion.
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,30 @@ Above example will return following dict
{ "result": "result" }
```

### isAuthenticated & isStaff directive

A resolver will receive an authenticated user as keyword argument.

```graphql
directive @isAuthenticated on FIELD_DEFINITION

type User {
id: ID
username: String
ipAddress: String @isAuthenticated
}
```

```python
from ariadne_django_ext import IsAuthenticatedDirective

schema = make_executable_schema(
type_defs,
resolvers,
directives={"isAuthenticated": IsAuthenticatedDirective}
)
```

## Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Expand All @@ -81,3 +105,7 @@ Please make sure to update tests as appropriate.
## License

[MIT License](https://choosealicense.com/licenses/mit/)

```
```
3 changes: 2 additions & 1 deletion ariadne_django_ext/__init__.py
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"]
33 changes: 33 additions & 0 deletions ariadne_django_ext/directives.py
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

0 comments on commit f0f7bed

Please sign in to comment.