[英]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.