7
7
from django .urls .exceptions import NoReverseMatch
8
8
from django .utils .translation import gettext_lazy as _
9
9
10
+ from netbox .api .authentication import TokenAuthentication
10
11
from netbox .plugins import PluginConfig
11
12
from netbox .registry import registry
12
13
from utilities .relations import get_related_models
19
20
'GetRelatedModelsMixin' ,
20
21
'GetReturnURLMixin' ,
21
22
'ObjectPermissionRequiredMixin' ,
23
+ 'TokenConditionalLoginRequiredMixin' ,
22
24
'ViewTab' ,
23
25
'get_viewname' ,
24
26
'register_model_view' ,
@@ -39,6 +41,19 @@ def dispatch(self, request, *args, **kwargs):
39
41
return super ().dispatch (request , * args , ** kwargs )
40
42
41
43
44
+ class TokenConditionalLoginRequiredMixin (ConditionalLoginRequiredMixin ):
45
+ def dispatch (self , request , * args , ** kwargs ):
46
+ # Attempt to authenticate the user using a DRF token, if provided
47
+ if settings .LOGIN_REQUIRED and not request .user .is_authenticated :
48
+ authenticator = TokenAuthentication ()
49
+ auth_info = authenticator .authenticate (request )
50
+ if auth_info is not None :
51
+ request .user = auth_info [0 ] # User object
52
+ request .auth = auth_info [1 ]
53
+
54
+ return super ().dispatch (request , * args , ** kwargs )
55
+
56
+
42
57
class ContentTypePermissionRequiredMixin (ConditionalLoginRequiredMixin ):
43
58
"""
44
59
Similar to Django's built-in PermissionRequiredMixin, but extended to check model-level permission assignments.
0 commit comments