如何使用Djangographqlauth自定义错误?

2024-04-26 13:45:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在与Django和Graphene一起进行一个项目,Django_graphql_auth库用于处理身份验证,我被要求自定义登录失败时收到的错误消息。我已经阅读了文档中关于如何执行此操作的内容,其中只提到了一个名为CUSTOM_ERROR_TYPE(https://django-graphql-auth.readthedocs.io/en/latest/settings/#custom_error_type)的设置,但我认为我不了解如何使用它,或者可能它没有按照我认为的方式工作。在我的文件中,我:

自定义_errors.py

import graphene

class CustomErrorType(graphene.Scalar):
    @staticmethod
    def serialize(errors):
        return {"my_custom_error_format"}

设置.py

from .custom_errors import CustomErrorType

GRAPHQL_AUTH = {
    'CUSTOM_ERROR_TYPE': CustomErrorType,
}

user.py

class AuthRelayMutation(graphene.ObjectType):
    password_set = PasswordSet.Field()
    password_change = PasswordChange.Field()

    # # django-graphql-jwt inheritances
    token_auth = ObtainJSONWebToken.Field()
    verify_token = relay.VerifyToken.Field()
    refresh_token = relay.RefreshToken.Field()
    revoke_token = relay.RevokeToken.Field()
    unlock_user = UsuarioUnlock.Field()

class Mutation(AuthRelayMutation, graphene.ObjectType):
    user_create = UserCreate.Field()
    user_update = UserUpdate.Field()
    user_delete = UserDelete.Field()

schema = graphene.Schema(query=Query, mutation=Mutation)

然而,当我测试登录时,仍然会收到消息:“请输入有效的凭据。”我应该如何更改该消息

更新

class ObtainJSONWebToken(
    RelayMutationMixin, ObtainJSONWebTokenMixin, graphql_jwt.relay.JSONWebTokenMutation
):
    __doc__ = ObtainJSONWebTokenMixin.__doc__
    user = graphene.Field(UserNode)
    days_remaining = graphene.Field(graphene.String, to=graphene.String())
    unarchiving = graphene.Boolean(default_value=False)

    @classmethod
    def resolve(cls, root, info, **kwargs):
        user = info.context.user

        # Little logic validations

        unarchiving = kwargs.get("unarchiving", False)
        return cls(user=info.context.user, days_remaining=days_remaining)
        

    @classmethod
    def Field(cls, *args, **kwargs):
        cls._meta.arguments["input"]._meta.fields.update(
            {"password": graphene.InputField(graphene.String, required=True)}
        )
        for field in app_settings.LOGIN_ALLOWED_FIELDS:
            cls._meta.arguments["input"]._meta.fields.update(
                {field: graphene.InputField(graphene.String)}
            )
        return super(graphql_jwt.relay.JSONWebTokenMutation, cls).Field(*args, **kwargs)

Tags: tokenauth消息fieldstringcustomgraphqlrelay
2条回答

我也遇到了这个问题,但由于graphql_auth/bases.py中的django-graphql-auth库中的this line而意识到,为了使用自定义错误,您必须将settings.py文件中的类指示为字符串。这似乎为我解决了这个问题

例如,我有:

GRAPHQL_AUTH = {
    'CUSTOM_ERROR_TYPE': 'accounts.custom_errors.CustomErrorType'
}

(其中CustomErrorType是一个类似于您在原始帖子中指出的类)

我也有同样的问题。我找到并引用了这个GitHub线程:https://github.com/flavors/django-graphql-jwt/issues/147 它有点过时,但我对它进行了调整,效果很好:

import graphql_jwt
from graphql_jwt.exceptions import JSONWebTokenError


class CustomObtainJSONWebToken(ObtainJSONWebToken):
    @classmethod
    def mutate(cls, *args, **kwargs):
        try:
            return super().mutate(*args, **kwargs)
        except JSONWebTokenError:
            raise Exception('Your custom error message here')

相关问题 更多 >