Commit 72007968 authored by Joern jkuensem's avatar Joern jkuensem

TMSS-155: Add context manager TMSSsession for ease of use in scripts

parent 47223c5c
......@@ -26,6 +26,7 @@ find_python_module(swagger_spec_validator REQUIRED) # pip install swagger-spec-v
set(_py_files
manage.py
remakemigrations.py
util.py
)
python_install(${_py_files}
......
......@@ -106,7 +106,6 @@ MIDDLEWARE = [
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
# 'mozilla_django_oidc.middleware.SessionRefresh',
]
ROOT_URLCONF = 'lofar.sas.tmss.tmss.urls'
......@@ -184,15 +183,15 @@ REST_FRAMEWORK = {
# AUTHENTICATION: simple LDAP, or OpenID, or both
AUTHENTICATION_BACKENDS = ()
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
if "TMSS_LDAPCREDENTIALS" in os.environ.keys():
# plain LDAP
import ldap
REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES'].append('rest_framework.authentication.BasicAuthentication')
REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES'].append('rest_framework.authentication.SessionAuthentication')
REST_FRAMEWORK['DEFAULT_PERMISSION_CLASSES'].append('rest_framework.permissions.IsAuthenticated')
#REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES'].append('rest_framework.authentication.SessionAuthentication')
#REST_FRAMEWORK['DEFAULT_PERMISSION_CLASSES'].append('rest_framework.permissions.IsAuthenticated')
# LDAP
ldap_creds_name = os.environ.get('TMSS_LDAPCREDENTIALS', 'tmss_ldap')
......@@ -212,13 +211,14 @@ if "TMSS_LDAPCREDENTIALS" in os.environ.keys():
"email": "mail"
}
AUTHENTICATION_BACKENDS += ('django_auth_ldap.backend.LDAPBackend','django.contrib.auth.backends.ModelBackend',)
AUTHENTICATION_BACKENDS += ('django_auth_ldap.backend.LDAPBackend',)
if "OIDC_RP_CLIENT_ID" in os.environ.keys():
INSTALLED_APPS.append('mozilla_django_oidc') # Load after auth
REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES'].append('mozilla_django_oidc.contrib.drf.OIDCAuthentication')
REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES'].append('rest_framework.authentication.SessionAuthentication')
REST_FRAMEWORK['DEFAULT_PERMISSION_CLASSES'].append('rest_framework.permissions.IsAuthenticated')
# OPEN-ID CONNECT
......@@ -235,8 +235,9 @@ if "OIDC_RP_CLIENT_ID" in os.environ.keys():
OIDC_OP_USER_ENDPOINT = "http://%s:8088/openid/userinfo" % OIDC_ENDPOINT_HOST
AUTHENTICATION_BACKENDS += ('mozilla_django_oidc.auth.OIDCAuthenticationBackend',)
MIDDLEWARE.append('mozilla_django_oidc.middleware.SessionRefresh')
if len(AUTHENTICATION_BACKENDS) is 0:
if len(AUTHENTICATION_BACKENDS) is 1:
REST_FRAMEWORK['DEFAULT_PERMISSION_CLASSES'].append('rest_framework.permissions.AllowAny') # todo: Whoo! This seems unsafe! Maybe we should at least have users explicitly disable authentication on startup?!
logger.warning("No authentication configured! please set either OIDC_RP_CLIENT_ID or TMSS_LDAPCREDENTIALS environment variable.")
......
import logging
import requests
logger = logging.getLogger(__file__)
# usage example:
#
# with TMSSsession('paulus', 'pauluspass') as session:
# response = session.get(url='http://localhost:8008/api/task_draft/')
# print(response)
class TMSSsession(object):
def __init__(self, username, password, host):
self.session = requests.session()
self.username = username
self.password = password
self.host = host
def __enter__(self):
self.session.__enter__()
self.session.verify = False
# get authentication page of OIDC through TMSS redirect
response = self.session.get(self.host + '/oidc/authenticate/', allow_redirects=True)
csrftoken = self.session.cookies['csrftoken']
# post user credentials to login page, also pass csrf token
data = {'username': self.username, 'password': self.password, 'csrfmiddlewaretoken': csrftoken}
response = self.session.post(url=response.url, data=data, allow_redirects=True)
# raise when sth went wrong
if "The username and/or password you specified are not correct" in response.content.decode('utf8'):
raise ValueError("The username and/or password you specified are not correct")
if response.status_code != 200:
raise ConnectionError(response.content.decode('utf8'))
# return the authenticated session as user context
return self.session
def __exit__(self, type, value, traceback):
try:
# logout user
self.session.get(self.host + '/api/logout/', allow_redirects=True)
self.session.__exit__(self, type, value, traceback)
except:
pass
......@@ -37,6 +37,11 @@ from lofar.sas.tmss.test.tmss_test_environment_unittest_setup import *
from lofar.sas.tmss.test.tmss_test_data_rest import TMSSRESTTestDataCreator
test_data_creator = TMSSRESTTestDataCreator(BASE_URL, AUTH)
# todo: figure out why csrftoken is missing when using the TMSSRESTTestDataCreator while it is present when...
# todo: ...running tmss manually and referring to that by overriding BASE_URL here:
# BASE_URL = 'http://localhost:8008/api'
from lofar.sas.tmss.util import TMSSsession
class LDAPSession(unittest.TestCase):
......@@ -73,29 +78,14 @@ class OIDCSession(unittest.TestCase):
self.assertTrue("Authentication credentials were not provided" in r.content.decode('utf8'))
def test_failure_using_wrong_credentials(self):
with requests.Session() as session:
session.verify = False
response = session.get(OIDC_URL + '/authenticate/', allow_redirects=True)
csrftoken = session.cookies['csrftoken']
data = {'username': AUTH.username, 'password': 'wrong', 'csrfmiddlewaretoken': csrftoken}
response = session.post(url=response.url, data=data, allow_redirects=True)
with self.assertRaises(ValueError) as err:
with TMSSsession(AUTH.username, 'wrong', BASE_URL.replace('/api', '')) as session:
pass
# assert OIDC provider reports error
self.assertTrue("The username and/or password you specified are not correct" in response.content.decode('utf8'))
# assert TMSS failure
r = session.get(BASE_URL + '/task_draft/?format=api')
self.assertEqual(r.status_code, 401)
self.assertTrue("Invalid username/password" in r.content.decode('utf8'))
self.assertTrue('The username and/or password you specified are not correct' in str(err.exception))
def test_success_using_correct_credentials(self):
with requests.Session() as session:
session.verify = False
response = session.get(OIDC_URL + '/authenticate/', allow_redirects=True)
csrftoken = session.cookies['csrftoken']
#data = {'username': AUTH.username, 'password': AUTH.password, 'csrfmiddlewaretoken': csrftoken}
data = {'username': 'paulus', 'password': 'pauluspass', 'csrfmiddlewaretoken': csrftoken}
session.post(url=response.url, data=data, allow_redirects=True)
with TMSSsession(AUTH.username, AUTH.password, BASE_URL.replace('/api', '')) as session:
r = session.get(BASE_URL + '/task_draft/?format=api')
self.assertEqual(r.status_code, 200)
self.assertTrue("Task Draft List" in r.content.decode('utf8'))
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment