简体   繁体   English

如何使用 django-graphql-auth 自定义错误?

[英]How to customize errors with django-graphql-auth?

I'm working on a project with Django and Graphene, with the library of django_graphql_auth to handle authentication, and i was asked to customize the error message that we receive when we fail a login.我正在使用 Django 和 Graphene 开发一个项目,并使用 django_graphql_auth 库来处理身份验证,并且我被要求自定义登录失败时收到的错误消息。 I've readed the docs over how to do this, and it only mentions a setting called CUSTOM_ERROR_TYPE( https://django-graphql-auth.readthedocs.io/en/latest/settings/#custom_error_type ), but i think i'm not understanding how to use it, or maybe it doesn't work the way i think it does.我已经阅读了有关如何执行此操作的文档,它只提到了一个名为 CUSTOM_ERROR_TYPE( https://django-graphql-auth.readthedocs.io/en/latest/settings/#custom_error_type )的设置,但我认为我'我不明白如何使用它,或者它可能不像我认为的那样工作。 On my files i've:在我的文件中,我有:

custom_errors.py custom_errors.py

import graphene

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

settings.py设置.py

from .custom_errors import CustomErrorType

GRAPHQL_AUTH = {
    'CUSTOM_ERROR_TYPE': CustomErrorType,
}

user.py用户.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)

Yet, when i test the login, i still receive the message: "Please, enter valid credentials."然而,当我测试登录时,我仍然收到消息:“请输入有效凭据。” What should i do to change that message?我应该怎么做才能更改该消息?

Update更新

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)

I had the same issue.我遇到过同样的问题。 I found and referred to this GitHub thread: https://github.com/flavors/django-graphql-jwt/issues/147 it's a little outdated but I tweaked it and it worked:我发现并参考了这个 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')

I ran into this issue as well, but realized due to this line in the django-graphql-auth library in graphql_auth/bases.py you have to indicate the class in your settings.py file as a string in order to use your custom error.我也遇到了这个问题,但是意识到由于graphql_auth/bases.py中的django-graphql-auth库中的这一行,您必须在settings.py文件中将 class 指示为字符串才能使用您的自定义错误. This seemed to fix the issue for me.这似乎为我解决了这个问题。

So I have, for example:所以我有,例如:

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

(where CustomErrorType is a class similar to what you indicated in your original post) (其中CustomErrorType是 class 类似于您在原始帖子中指出的内容)

I have tweaked the above code with the use of ErrorType provided by graphene_django for error format.我使用 graphene_django 提供的 ErrorType 来调整上面的代码以获取错误格式。

import graphene
import graphql_jwt

from ..types import UserType
from graphene_django.types import ErrorType

from graphql_jwt.exceptions import JSONWebTokenError
from graphql_jwt.mixins import ResolveMixin

class CreateToken(graphql_jwt.JSONWebTokenMutation, ResolveMixin):
    user = graphene.Field(UserType)
    errors = graphene.List(ErrorType)

    @classmethod
    def mutate(cls, *args, **kwargs):
        try:
            return super().mutate(*args, **kwargs)
        except JSONWebTokenError as e:
            errors = ErrorType.from_errors({'username/password': [str(e)]})
            return cls(errors=errors)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用带有石墨烯的 django-graphql-auth 自定义突变的响应 - Customize a response from a mutation using django-graphql-auth with graphene 如何使用 python-social-auth 和 django-graphql-auth 返回刷新令牌? - How can I return the refresh token using python-social-auth and django-graphql-auth? 如何在Django中自定义默认的身份验证登录表单? - How to customize default auth login form in Django? Django Graphql 验证未登录用户 - Django Graphql Auth not logged in user 如何使用 django-graphql-social-auth 库获取刷新令牌 - How to get the Refresh Token with the django-graphql-social-auth library 如何在 Django CRUD 中自定义 auth.User 管理页面? - How to customize the auth.User Admin page in Django CRUD? 如何使用urls.py自定义django auth装饰器? - How to customize django auth decorator with urls.py? 如何覆盖/自定义 Django 和 Django rest 框架中的所有服务器错误 - How to override/customize ALL server errors in Django and Django rest framework 是否可以针对某些注册错误自定义 django.auth 错误消息? - Is it possible to customize django.auth error message appropriate for certain registration errors? django自定义self._errors - django customize self._errors
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM