Coverage for conf/oauth2_extensions.py: 90%

21 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-07 06:14 +0000

1from rest_framework.exceptions import ( 

2 AuthenticationFailed, 

3 PermissionDenied, 

4) 

5 

6import structlog 

7from drf_spectacular.authentication import TokenScheme 

8from oauth2_provider.contrib.rest_framework import ( 

9 OAuth2Authentication as BaseOAuth2Authentication, 

10) 

11 

12 

13logger = structlog.get_logger(__name__) 

14 

15 

16class OAuth2Authentication(BaseOAuth2Authentication): 

17 # Required by schema extension 

18 keyword = "Bearer" 

19 

20 def authenticate(self, request): 

21 user_auth_tuple = super().authenticate(request) 

22 if getattr(request, "oauth2_error", None): 

23 # oauth2_error is only defined on requests that had errors 

24 # it will be undefined or empty for anonymous requests and 

25 # requests with valid credentials 

26 # `request` is mutated by `super().authenticate` 

27 raise AuthenticationFailed() 

28 

29 # if this is an authed request, check and 

30 # deny access if client's access has been 

31 # revoked. 

32 if user_auth_tuple is not None: 

33 user, auth = user_auth_tuple 

34 if application := getattr(auth, "application", None): 34 ↛ 44line 34 didn't jump to line 44 because the condition on line 34 was always true

35 if application.revoked: 35 ↛ 36line 35 didn't jump to line 36 because the condition on line 35 was never true

36 raise PermissionDenied() 

37 logger.info( 

38 "client_application_authentication", 

39 application_id=application.id, 

40 application_name=application.name, 

41 application_verified=application.verified, 

42 ) 

43 

44 return user_auth_tuple 

45 

46 

47class OAuth2OpenApiAuthenticationExtension(TokenScheme): 

48 target_class = "conf.oauth2_extensions.OAuth2Authentication" 

49 name = "Openverse API Token"