django-two-factor-auth
django-two-factor-auth copied to clipboard
Is there something like OTPRequiredMixin for API
OTPRequiredMixin works great for django views. But when I am building django rest API, I would like to have a OTPRequired permissions that I can add to permission_classes=[]
Do we already have something for this or do we need to build a new permissions class.
Thanks
Assuming you're using django-rest-framework then you need to look at https://www.django-rest-framework.org/api-guide/permissions/#custom-permissions and write your own permission class. Your permission class will need to check request.user.is_verified()
is True
and that should be it.
@moggers87 How do I make sure is_verified()
will be defined in this custom permission class? I know it is supposed to be received from OTPMiddleware but if your user object is created using django-rest-framework how do I couple it to OTPMiddleware
? I cannot for instance do from django_otp.middleware.OTPMiddleware import is_verified
And yes, I do have 'django_otp.middleware.OTPMiddleware'
listed in MIDDLEWARE
in settings.py
. I thought this would be all that is needed to activate it.
Unless I am missing something, the permission class is on the view. As long as OTPMiddleware
comes after whatever middleware is creating request.user
it should Just Work™
Hey! I'm using this lib and it's amazing for Django. Now I'm trying to integrate it with DRF, as I'm working on a project that uses both.
I created a custom permission, but I'm having some problems.
The middleware is listed in the correct order and is working in Django Admin and Django views.
When I make a request to a DRF endpoint, I see the middleware setting is_verified
on the user, but when the has_permission
method is run, the user no longer has it and I get the error AttributeError: 'User' object has no attribute 'is_verified'
.
Could anyone help?
I discovered that the reason for this error is that in DRF, JWTAuthentication
overwrites the user in the request right before entering the view.
I solved the problem by creating a custom authentication class, which does the same as the middleware, adding the function to the user instance in the request.