Source code for simple_openid_connect.integrations.djangorestframework.permissions
"""DRF permission classesSee the `DRF documentation on Setting the permission policy <https://www.django-rest-framework.org/api-guide/permissions/#setting-the-permission-policy>`_ on how to use the classes contained here."""importloggingfromtypingimportAnyfromdjango.core.exceptionsimportImproperlyConfiguredfromdjango.httpimportHttpRequestfromrest_framework.permissionsimportBasePermissionfromsimple_openid_connect.integrations.django.appsimportOpenidAppConfigfromsimple_openid_connect.integrations.djangorestframework.authenticationimport(AuthenticatedViaToken,)logger=logging.getLogger(__name__)class_HasScope(BasePermission):@staticmethoddef_get_required_scopes(view:Any)->str:ifhasattr(view,"required_scopes"):ifnotisinstance(view.required_scopes,str):raiseImproperlyConfigured(f"view {view.__name__} has field 'required_scopes' but it is not a string. required_scopes needs to be a space separated string")returnview.required_scopesreturnOpenidAppConfig.get_instance().safe_settings.OPENID_SCOPE@staticmethoddef_validate_scopes(required_scopes:str,granted_scopes:str)->bool:""" :returns: ``True`` iff all required scopes are present in granted scopes """returnall(i_scopeingranted_scopes.split(" ")fori_scopeinrequired_scopes.split(" "))
[docs]classHasSessionScope(_HasScope):"""Check whether an authenticated user has a session with the required scope"""
[docs]defhas_permission(self,request:HttpRequest,view:Any)->bool:# validate that enough information is present to authorize the requestifnotrequest.user.is_authenticated:logger.error("session permission is supposed to be checked but the request was not authenticated; denying access")returnFalseifnothasattr(request.user,"openid"):logger.error("session permission is supposed to be checked but the request was not authenticated with an OpenidSession; denying access")returnFalsesession_scopes=request.user.openid.sessions.values_list("scope",flat=True)required_scopes=self._get_required_scopes(view)forsession_scopeinsession_scopes:ifself._validate_scopes(required_scopes,session_scope):returnTruereturnFalse
[docs]classHasTokenScope(_HasScope):"""Check whether an authenticated user has a token with the required scope"""
[docs]defhas_permission(self,request:HttpRequest,view:Any)->bool:# validate that enough information is present to authorize the requestifnothasattr(request,"auth")ornotisinstance(request.auth,AuthenticatedViaToken):logger.error("token permission is supposed to be checked but the request was not authenticated via an access token; denying access")returnFalseif(nothasattr(request.auth.user_data,"scope")orrequest.auth.user_data.scopeisNone):logger.error("token permission could not be checked because the token introspection does not contain token scopes; denying access")returnFalse# authorize the requestrequired_scopes=self._get_required_scopes(view)returnself._validate_scopes(required_scopes,request.auth.user_data.scope)