mirror of
https://gitlab.crans.org/bde/nk20
synced 2025-11-14 10:41:27 +01:00
Compare commits
2 Commits
54d28b30e5
...
9998189dbf
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9998189dbf | ||
|
|
08593700fc |
@@ -21,7 +21,7 @@ class PermissionBackend(ModelBackend):
|
||||
Manage permissions of users
|
||||
"""
|
||||
supports_object_permissions = True
|
||||
supports_anonymous_user = True
|
||||
supports_anonymous_user = False
|
||||
supports_inactive_user = False
|
||||
|
||||
@staticmethod
|
||||
@@ -33,6 +33,7 @@ class PermissionBackend(ModelBackend):
|
||||
:param t: The type of the permissions: view, change, add or delete
|
||||
:return: The queryset of the permissions of the user (memoized) grouped by clubs
|
||||
"""
|
||||
# Permission for auth
|
||||
if hasattr(request, 'oauth2') and request.oauth2 is not None and 'scope' in request.oauth2:
|
||||
# OAuth2 Authentication
|
||||
user = request.oauth2['user']
|
||||
@@ -46,6 +47,21 @@ class PermissionBackend(ModelBackend):
|
||||
if int(club_id) == membership_obj.club_id:
|
||||
query |= Q(pk=permission_id, mask__rank__lte=request.oauth2['mask'])
|
||||
return query
|
||||
|
||||
# Restreint token permission to his scope
|
||||
elif hasattr(request, 'auth') and request.auth is not None and hasattr(request.auth, 'scope'):
|
||||
user = request.auth.user
|
||||
|
||||
def permission_filter(membership_obj):
|
||||
query = Q(pk=-1)
|
||||
for scope in request.auth.scope.split(' '):
|
||||
if scope == "openid" or scope == "0_0":
|
||||
continue
|
||||
permission_id, club_id = scope.split('_')
|
||||
if int(club_id) == membership_obj.club_id:
|
||||
query |= Q(pk=permission_id)
|
||||
return query
|
||||
|
||||
else:
|
||||
user = request.user
|
||||
|
||||
@@ -79,7 +95,6 @@ class PermissionBackend(ModelBackend):
|
||||
:param type: The type of the permissions: view, change, add or delete
|
||||
:return: A generator of the requested permissions
|
||||
"""
|
||||
|
||||
if hasattr(request, 'auth') and request.auth is not None and hasattr(request.auth, 'scope'):
|
||||
# OAuth2 Authentication
|
||||
user = request.auth.user
|
||||
|
||||
@@ -54,7 +54,7 @@ class PermissionScopes(BaseScopes):
|
||||
return []
|
||||
scopes = [f"{p.id}_{p.membership.club.id}"
|
||||
for p in PermissionBackend.get_raw_permissions(get_current_request(), 'view')]
|
||||
scopes = ['0_0']
|
||||
scopes = ['0_0'] # always default
|
||||
return scopes
|
||||
|
||||
|
||||
@@ -72,6 +72,11 @@ class PermissionOAuth2Validator(OAuth2Validator):
|
||||
"email": request.user.email,
|
||||
}
|
||||
|
||||
def get_userinfo_claims(self, request):
|
||||
claims = super().get_userinfo_claims(request)
|
||||
claims['is_active'] = request.user.is_active
|
||||
return claims
|
||||
|
||||
def get_discovery_claims(self, request):
|
||||
claims = super().get_discovery_claims(self)
|
||||
return claims + ["name", "normalized_name", "email"]
|
||||
@@ -138,30 +143,6 @@ class PermissionOAuth2Validator(OAuth2Validator):
|
||||
request.scopes = valid_scopes
|
||||
return valid_scopes
|
||||
|
||||
def validate_code_scopes(self, client_id, scopes, client, request, *args, **kwargs):
|
||||
"""
|
||||
For Authorization Code scope are scope of the user
|
||||
"""
|
||||
valid_scopes = set()
|
||||
req = get_current_request()
|
||||
request.oauth2 = {}
|
||||
request.oauth2['user'] = req.user
|
||||
request.oauth2['scope'] = scopes
|
||||
# mask implementation
|
||||
request.oauth2['mask'] = req.session.load()['permission_mask']
|
||||
|
||||
for t in Permission.PERMISSION_TYPES:
|
||||
for p in PermissionBackend.get_raw_permissions(request, t[0]):
|
||||
scope = f"{p.id}_{p.membership.club.id}"
|
||||
if scope in scopes:
|
||||
valid_scopes.add(scope)
|
||||
|
||||
# Always give one scope to generate token
|
||||
if not valid_scopes:
|
||||
valid_scopes.add('0_0')
|
||||
request.scopes = valid_scopes
|
||||
return valid_scopes
|
||||
|
||||
def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs):
|
||||
"""
|
||||
User can request as many scope as he wants, including invalid scopes,
|
||||
@@ -176,16 +157,28 @@ class PermissionOAuth2Validator(OAuth2Validator):
|
||||
if hasattr(request, 'grant_type') and request.grant_type == 'password':
|
||||
return self.validate_ropb_scopes(client_id, scopes, client, request, args, kwargs)
|
||||
|
||||
if hasattr(request, '_params') and request._params['response_type'] == 'code':
|
||||
return self.validate_code_scopes(client_id, scopes, client, request, args, kwargs)
|
||||
# Authorization code and Implicit are the same for scope, OIDC it's only a layer
|
||||
|
||||
valid_scopes = set()
|
||||
req = get_current_request()
|
||||
request.oauth2 = {}
|
||||
request.oauth2['user'] = req.user
|
||||
request.oauth2['scope'] = scopes
|
||||
# mask implementation
|
||||
request.oauth2['mask'] = req.session.load()['permission_mask']
|
||||
|
||||
for t in Permission.PERMISSION_TYPES:
|
||||
for p in PermissionBackend.get_raw_permissions(get_current_request(), t[0]):
|
||||
for p in PermissionBackend.get_raw_permissions(request, t[0]):
|
||||
scope = f"{p.id}_{p.membership.club.id}"
|
||||
if scope in scopes:
|
||||
valid_scopes.add(scope)
|
||||
|
||||
if '0_0' in scopes:
|
||||
# We grant openid scope if user is active
|
||||
if 'openid' in scopes and req.user.is_active:
|
||||
valid_scopes.add('openid')
|
||||
|
||||
# Always give one scope to generate token
|
||||
if not valid_scopes:
|
||||
valid_scopes.add('0_0')
|
||||
|
||||
request.scopes = valid_scopes
|
||||
|
||||
@@ -204,7 +204,136 @@ class OAuth2FlowTestCase(TestCase):
|
||||
"""
|
||||
Ensure OAuth2 Implicit Flow work
|
||||
"""
|
||||
pass
|
||||
app = Application.objects.create(
|
||||
name="Test Implicit Flow",
|
||||
client_type=Application.CLIENT_CONFIDENTIAL,
|
||||
authorization_grant_type=Application.GRANT_IMPLICIT,
|
||||
user=self.user,
|
||||
hash_client_secret=False,
|
||||
algorithm=Application.NO_ALGORITHM,
|
||||
redirect_uris='http://127.0.0.1:8000/noexist/callback/',
|
||||
)
|
||||
|
||||
############################
|
||||
# Minimal RFC6749 requests #
|
||||
############################
|
||||
|
||||
resp = self.client.get('/o/authorize/',
|
||||
data={'response_type': 'token', # REQUIRED
|
||||
'client_id': app.client_id}, # REQUIRED
|
||||
**{"Content-Type": 'application/x-www-form-urlencoded'}
|
||||
)
|
||||
|
||||
# Get user authorization
|
||||
##################################################################################
|
||||
url = resp.url
|
||||
csrf_token = resp.text.split('CSRF_TOKEN = "')[0].split('"')[0]
|
||||
|
||||
resp = self.client.post(url,
|
||||
data={"username": self.user.username,
|
||||
"password": self.user_password,
|
||||
"permission_mask": 1,
|
||||
"csrfmiddlewaretoken": csrf_token})
|
||||
|
||||
url = resp.url
|
||||
resp = self.client.get(url)
|
||||
|
||||
csrf_token = resp.text.split('CSRF_TOKEN = "')[0].split('"')[0]
|
||||
|
||||
resp = self.client.post(url,
|
||||
follow=True,
|
||||
data={"allow": "Authorize",
|
||||
"scope": '0_0',
|
||||
"csrfmiddlewaretoken": csrf_token,
|
||||
"response_type": "token",
|
||||
"client_id": app.client_id,
|
||||
"redirect_uri": app.redirect_uris})
|
||||
|
||||
url = resp.redirect_chain[0][0]
|
||||
keys = url.split('#')[1]
|
||||
refresh_token = ''
|
||||
|
||||
for couple in keys.split('&'):
|
||||
if couple.split('=')[0] == 'access_token':
|
||||
token = couple.split('=')[1]
|
||||
if couple.split('=')[0] == 'refresh_token':
|
||||
refresh_token = couple.split('=')[1]
|
||||
|
||||
##################################################################################
|
||||
|
||||
self.assertEqual(refresh_token, '')
|
||||
|
||||
access_token = AccessToken.objects.get(token=token)
|
||||
|
||||
# Token do nothing, it should be have the useless scope
|
||||
self.assertEqual(access_token.scope, '0_0')
|
||||
|
||||
# Logout user
|
||||
self.client.logout()
|
||||
|
||||
############################
|
||||
# Maximal RFC6749 requests #
|
||||
############################
|
||||
|
||||
state = get_random_string(32)
|
||||
|
||||
resp = self.client.get('/o/authorize/',
|
||||
data={'response_type': 'token', # REQUIRED
|
||||
'client_id': app.client_id, # REQUIRED
|
||||
'redirect_uri': app.redirect_uris, # OPTIONAL
|
||||
'scope': self.base_scope, # OPTIONAL
|
||||
'state': state}, # RECOMMENDED
|
||||
**{"Content-Type": 'application/x-www-form-urlencoded'}
|
||||
)
|
||||
|
||||
# Get user authorization
|
||||
##################################################################################
|
||||
url = resp.url
|
||||
csrf_token = resp.text.split('CSRF_TOKEN = "')[0].split('"')[0]
|
||||
|
||||
resp = self.client.post(url,
|
||||
data={"username": self.user.username,
|
||||
"password": self.user_password,
|
||||
"permission_mask": 1,
|
||||
"csrfmiddlewaretoken": csrf_token})
|
||||
|
||||
url = resp.url
|
||||
resp = self.client.get(url)
|
||||
|
||||
csrf_token = resp.text.split('CSRF_TOKEN = "')[0].split('"')[0]
|
||||
|
||||
resp = self.client.post(url,
|
||||
follow=True,
|
||||
data={"allow": "Authorize",
|
||||
"scope": self.base_scope,
|
||||
"state": state,
|
||||
"csrfmiddlewaretoken": csrf_token,
|
||||
"response_type": "token",
|
||||
"client_id": app.client_id,
|
||||
"redirect_uri": app.redirect_uris})
|
||||
|
||||
url = resp.redirect_chain[0][0]
|
||||
keys = url.split('#')[1]
|
||||
refresh_token = ''
|
||||
|
||||
for couple in keys.split('&'):
|
||||
if couple.split('=')[0] == 'access_token':
|
||||
token = couple.split('=')[1]
|
||||
if couple.split('=')[0] == 'refresh_token':
|
||||
refresh_token = couple.split('=')[1]
|
||||
if couple.split('=')[0] == 'state':
|
||||
resp_state = couple.split('=')[1]
|
||||
|
||||
##################################################################################
|
||||
|
||||
self.assertEqual(refresh_token, '')
|
||||
|
||||
access_token = AccessToken.objects.get(token=token)
|
||||
|
||||
# Token can have access, it shouldn't have the useless scope
|
||||
self.assertEqual(access_token.scope, self.base_scope)
|
||||
|
||||
self.assertEqual(state, resp_state)
|
||||
|
||||
def test_oauth2_resource_owner_password_credentials_flow(self):
|
||||
"""
|
||||
@@ -313,9 +442,3 @@ class OAuth2FlowTestCase(TestCase):
|
||||
|
||||
# Token can have access, it shouldn't have the useless scope
|
||||
self.assertEqual(token.scope, self.base_scope)
|
||||
|
||||
def test_oidc_flow(self):
|
||||
"""
|
||||
Ensure OIDC Flow work
|
||||
"""
|
||||
pass
|
||||
|
||||
@@ -273,9 +273,9 @@ OAUTH2_PROVIDER = {
|
||||
'REFRESH_TOKEN_EXPIRE_SECONDS': timedelta(days=14),
|
||||
'PKCE_REQUIRED': False, # PKCE (fix a breaking change of django-oauth-toolkit 2.0.0)
|
||||
'OIDC_ENABLED': True,
|
||||
'OIDC_RP_INITIATED_LOGOUT_ENABLED': False,
|
||||
'OIDC_RSA_PRIVATE_KEY':
|
||||
os.getenv('OIDC_RSA_PRIVATE_KEY', 'CHANGE_ME_IN_ENV_SETTINGS').replace('\\n', '\n'), # for multilines
|
||||
'SCOPES': { 'openid': "OpenID Connect scope" },
|
||||
}
|
||||
|
||||
# Take control on how widget templates are sourced
|
||||
|
||||
Reference in New Issue
Block a user