Last active
June 2, 2020 17:03
-
-
Save lclpedro/13c887754786da5fde0b566370e01adb to your computer and use it in GitHub Desktop.
This file contains hidden or 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
from functools import wraps | |
from src.models import Adminstrator | |
from graphql.execution.base import ResolveInfo | |
from graphql_jwt.exceptions import PermissionDenied | |
def context(f): | |
def decorator(func): | |
def wrapper(*args, **kwargs): | |
info = next(arg for arg in args if isinstance(arg, ResolveInfo)) | |
return func(info.context, *args, **kwargs) | |
return wrapper | |
return decorator | |
def validate_user_admin(test_func, exc=PermissionDenied()): | |
def decorator(f): | |
@wraps(f) | |
@context(f) | |
def wrapper(context, *args, **kwargs): | |
if test_func(context.user): | |
admin = Administrator.objects.filter( | |
user_ptr_id=context.user.id | |
).first() | |
context.admin = admin | |
if not admin: | |
raise PermissionDenied(message="User is not administrator.") | |
elif not admin.active_admin: | |
raise PermissionDenied(message="Administrator is disabled.") | |
return f(*args, **kwargs) | |
raise exc | |
return wrapper | |
return decorator | |
# create decorators | |
admin_required = validate_user_admin(lambda u: u) | |
This file contains hidden or 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
import graphene | |
from graphene_django import DjangoObjectType | |
from src.models import Language | |
from src.decorator import admin_required | |
class LanguageType(DjangoObjectType): | |
class Meta: | |
model = Language | |
class Query: | |
list_languages = graphene.List(LanguageType) | |
@admin_required | |
def resolve_list_languages(root, info, **kwargs): | |
return Language.objects.all() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment