django-two-factor-auth icon indicating copy to clipboard operation
django-two-factor-auth copied to clipboard

Is there something like OTPRequiredMixin for API

Open aseem-hegshetye opened this issue 4 years ago • 5 comments

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

aseem-hegshetye avatar Sep 01 '20 22:09 aseem-hegshetye

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 avatar Sep 09 '20 10:09 moggers87

@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.

Frikster avatar Nov 01 '21 02:11 Frikster

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™

moggers87 avatar Nov 02 '21 01:11 moggers87

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?

andrelccorrea-blinctek avatar Apr 04 '24 03:04 andrelccorrea-blinctek

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.

andrelccorrea avatar Apr 04 '24 12:04 andrelccorrea