def confirm_migration(request): from tardis.tardis_portal.auth import auth_service migration_form = \ openid_user_migration_form() authForm = migration_form(request.POST) if not authForm.is_valid(): errorMessage = \ 'Please provide all the necessary information to authenticate.' return _getJsonFailedResponse(errorMessage) # let's try and authenticate here user = auth_service.authenticate(authMethod="None", request=request) if user is None: errorMessage = 'Wrong username or password. Please try again' return _getJsonFailedResponse(errorMessage) # do not allow migration from an inactive account if not user.is_active: errorMessage = 'Account is inactive' return _getJsonFailedResponse(errorMessage) # get request user auth method backend = request.session['_auth_user_backend'] # get key from backend class name auth_provider = get_matching_auth_provider(backend) data = _setupJsonData(user, request.user) data['auth_method'] = auth_provider[0] return _getJsonConfirmResponse(data)
def login(request): from tardis.tardis_portal.staging import get_full_staging_path # Basic Authentication if 'username' in request.POST and \ 'password' in request.POST: authMethod = request.POST['authMethod'] user = auth_service.authenticate(authMethod=authMethod, request=request) if user: dl = request.FILES['file'] staging = settings.STAGING_PATH + '/' + str(user) + '/' eid, exp, folder_desc = createhpcexperiment(request, user, dl) next = str(staging) + str(eid) + '@' + str(eid) + '@' + str( folder_desc) return HttpResponse(next) else: next = 'Invalid User name or Password' return HttpResponse(next) else: return HttpResponse("No username password entered")
def test_authenticate(self): from tardis.tardis_portal.auth.ldap_auth import ldap_auth from django.core.handlers.wsgi import WSGIRequest from django.contrib.auth.models import User # Tests Authenticate API l = ldap_auth() req = WSGIRequest({"REQUEST_METHOD": "POST"}) req._post = {'username': '******', 'password': '******', 'authMethod': 'ldap'} u = l.authenticate(req) u1 = {'email': '*****@*****.**', 'display': 'Test', 'id': 'testuser1'} self.failUnlessEqual(u, u1) # Test authservice API from tardis.tardis_portal.auth import auth_service req = WSGIRequest({"REQUEST_METHOD": "POST"}) req._post = {'username': '******', 'password': '******', 'authMethod': 'ldap'} user = auth_service.authenticate('ldap', request=req) self.assertTrue(isinstance(user, User)) # Check that there is an entry in the user authentication table from tardis.tardis_portal.models import UserAuthentication userAuth = UserAuthentication.objects.get( userProfile__user=user, authenticationMethod=l.name) user1 = UserAuthentication.objects.get(username=user.username, authenticationMethod='ldap').userProfile.user self.assertEqual(user, user1)
def post(self, request, *args, **kwargs): from tardis.tardis_portal.auth import auth_service c = self.get_context_data(request, **kwargs) if request.user.is_authenticated: # redirect the user to the home page if he is trying to go to the # login page return HttpResponseRedirect(request.POST.get('next_page', '/')) # TODO: put me in SETTINGS if 'username' in request.POST and \ 'password' in request.POST: authMethod = request.POST.get('authMethod', None) user = auth_service.authenticate(authMethod=authMethod, request=request) if user and user.is_active: next_page = request.POST.get('next_page', '/') user.backend = 'django.contrib.auth.backends.ModelBackend' djauth.login(request, user) return HttpResponseRedirect(next_page) if user and not user.is_active: c['status'] = "Sorry, this account is inactive." else: c['status'] = "Sorry, username and password don't match." c['error'] = True c['loginForm'] = LoginForm() return HttpResponseForbidden( render_response_index(request, self.template_name, c)) return render_response_index(request, self.template_name, c)
def add_auth_method(request): """Add a new authentication method to request.user's existing list of authentication methods. This method will ask for a confirmation if the user wants to merge two accounts if the authentication method he provided already exists as a method for another user. :param Request request: the HTTP request object :returns: The HttpResponse which contains request.user's new list of authentication methods :rtype: HttpResponse """ from tardis.tardis_portal.auth import auth_service supportedAuthMethods = _getSupportedAuthMethods() LinkedUserAuthenticationForm = \ createLinkedUserAuthenticationForm(supportedAuthMethods) authForm = LinkedUserAuthenticationForm(request.POST) if not authForm.is_valid(): errorMessage = \ 'Please provide all the necessary information to authenticate.' return _getJsonFailedResponse(errorMessage) authenticationMethod = authForm.cleaned_data['authenticationMethod'] # let's try and authenticate here user = auth_service.authenticate(authMethod=authenticationMethod, request=request) if user is None: errorMessage = 'Wrong username or password. Please try again' return _getJsonFailedResponse(errorMessage) # if has already registered to use the provided auth method, then we'll # merge the two accounts if user != request.user: # but before we do that, we'll try and confirm with the user if that's # what he really wants return _getJsonConfirmResponse() # TODO: we'll need to send back a json message with a success status and # other info that can be used to modify the html document # get the user authentication methods for the current user userAuths = UserAuthentication.objects.filter( userProfile__user=request.user) # ... and append it to our list for userAuth in userAuths: # also remove the current userAuth from the list of authentication # method options that can be added by this user del supportedAuthMethods[userAuth.authenticationMethod] data = _setupJsonData(authForm, authenticationMethod, supportedAuthMethods) return _getJsonSuccessResponse(data)
def add_auth_method(request): """Add a new authentication method to request.user's existing list of authentication methods. This method will ask for a confirmation if the user wants to merge two accounts if the authentication method he provided already exists as a method for another user. :param request: the HTTP request object :returns: The HttpResponse which contains request.user's new list of authentication methods """ from tardis.tardis_portal.auth import auth_service supportedAuthMethods = _getSupportedAuthMethods() LinkedUserAuthenticationForm = \ createLinkedUserAuthenticationForm(supportedAuthMethods) authForm = LinkedUserAuthenticationForm(request.POST) if not authForm.is_valid(): errorMessage = \ 'Please provide all the necessary information to authenticate.' return _getJsonFailedResponse(errorMessage) authenticationMethod = authForm.cleaned_data['authenticationMethod'] # let's try and authenticate here user = auth_service.authenticate(authMethod=authenticationMethod, request=request) if user is None: errorMessage = 'Wrong username or password. Please try again' return _getJsonFailedResponse(errorMessage) # if has already registered to use the provided auth method, then we'll # merge the two accounts if user != request.user: # but before we do that, we'll try and confirm with the user if that's # what he really wants return _getJsonConfirmResponse() # TODO: we'll need to send back a json message with a success status and # other info that can be used to modify the html document # get the user authentication methods for the current user userAuths = UserAuthentication.objects.filter( userProfile__user=request.user) # ... and append it to our list for userAuth in userAuths: # also remove the current userAuth from the list of authentication # method options that can be added by this user del supportedAuthMethods[userAuth.authenticationMethod] data = _setupJsonData(authForm, authenticationMethod, supportedAuthMethods) return _getJsonSuccessResponse(data)
def mytardis_sites(request): if request.method == 'POST': if 'username' in request.POST and 'password' in request.POST: user = auth_service.authenticate(authMethod=localdb_auth_key, request=request) if user is not None: if user.is_superuser: return render_to_response('tardis_portal/mytardis_sites.xml', Context({}), mimetype='application/xml') return HttpResponseForbidden('ERROR')
def login(request): ''' handler for login page ''' logger.debug("start!") if request.user.is_authenticated(): # redirect the user to the home page if he is trying to go to the # login page return HttpResponseRedirect(request.POST.get('next_page', '/')) # TODO: put me in SETTINGS if 'username' in request.POST and \ 'password' in request.POST: authMethod = request.POST.get('authMethod', None) user = auth_service.authenticate(authMethod=authMethod, request=request) if user: next_page = request.POST.get('next_page', request.GET.get('next_page', '/')) user.backend = 'django.contrib.auth.backends.ModelBackend' djauth.login(request, user) return HttpResponseRedirect(next_page) c = { 'status': "Sorry, username and password don't match.", 'error': True, 'loginForm': LoginForm() } c = get_multimodal_context_data(c) return HttpResponseForbidden( render_response_index(request, 'tardis_portal/login.html', c)) url = request.META.get('HTTP_REFERER', '/') u = urlparse(url) if u.netloc == request.META.get('HTTP_HOST', ""): next_page = u.path else: next_page = '/' c = {'loginForm': LoginForm(), 'next_page': next_page} c = get_multimodal_context_data(c) return HttpResponse( render_response_index(request, 'tardis_portal/login.html', c))
def login(request): ''' handler for login page ''' from tardis.tardis_portal.auth import auth_service if request.user.is_authenticated(): # redirect the user to the home page if he is trying to go to the # login page return HttpResponseRedirect(request.POST.get('next_page', '/')) # TODO: put me in SETTINGS if 'username' in request.POST and \ 'password' in request.POST: authMethod = request.POST.get('authMethod', None) user = auth_service.authenticate(authMethod=authMethod, request=request) if user: next_page = request.POST.get('next_page', request.GET.get('next_page', '/')) user.backend = 'django.contrib.auth.backends.ModelBackend' djauth.login(request, user) return HttpResponseRedirect(next_page) c = { 'status': "Sorry, username and password don't match.", 'error': True, 'loginForm': LoginForm() } return HttpResponseForbidden( render_response_index(request, 'tardis_portal/login.html', c)) url = request.META.get('HTTP_REFERER', '/') u = urlparse(url) if u.netloc == request.META.get('HTTP_HOST', ""): next_page = u.path else: next_page = '/' c = {'loginForm': LoginForm(), 'next_page': next_page} c['RAPID_CONNECT_ENABLED'] = settings.RAPID_CONNECT_ENABLED c['RAPID_CONNECT_LOGIN_URL'] = settings.RAPID_CONNECT_CONFIG[ 'authnrequest_url'] return HttpResponse( render_response_index(request, 'tardis_portal/login.html', c))
def login(request): ''' handler for login page ''' from tardis.tardis_portal.auth import auth_service if request.user.is_authenticated(): # redirect the user to the home page if he is trying to go to the # login page return HttpResponseRedirect(request.POST.get('next_page', '/')) # TODO: put me in SETTINGS if 'username' in request.POST and \ 'password' in request.POST: authMethod = request.POST.get('authMethod', None) user = auth_service.authenticate( authMethod=authMethod, request=request) if user: next_page = request.POST.get( 'next_page', request.GET.get('next_page', '/')) user.backend = 'django.contrib.auth.backends.ModelBackend' djauth.login(request, user) return HttpResponseRedirect(next_page) c = {'status': "Sorry, username and password don't match.", 'error': True, 'loginForm': LoginForm()} return HttpResponseForbidden( render_response_index(request, 'tardis_portal/login.html', c)) url = request.META.get('HTTP_REFERER', '/') u = urlparse(url) if u.netloc == request.META.get('HTTP_HOST', ""): next_page = u.path else: next_page = '/' c = {'loginForm': LoginForm(), 'next_page': next_page} c['RAPID_CONNECT_ENABLED'] = settings.RAPID_CONNECT_ENABLED c['RAPID_CONNECT_LOGIN_URL'] = settings.RAPID_CONNECT_CONFIG[ 'authnrequest_url'] return HttpResponse(render_response_index(request, 'tardis_portal/login.html', c))
def test_getgroups(self): from django.contrib.auth.models import User from django.core.handlers.wsgi import WSGIRequest from tardis.tardis_portal.auth import auth_service req = WSGIRequest({"REQUEST_METHOD": "POST"}) req._post = {'username': '******', 'password': '******', 'authMethod': 'ldap'} user = auth_service.authenticate('ldap', request=req) self.assertTrue(isinstance(user, User)) req.user = user from tardis.tardis_portal.auth.ldap_auth import ldap_auth # Tests getGroups l = ldap_auth() self.assertEqual([g for g in l.getGroups(req)], ['full', 'systems'])
def protocol(request): # Basic Authentication if "username" in request.POST and "password" in request.POST: authMethod = request.POST["authMethod"] user = auth_service.authenticate(authMethod=authMethod, request=request) if user: html = "Successful" return HttpResponse(html) else: html = "Unsuccessful" return HttpResponse(html) else: html = "Please enter Username and Password" return HttpResponse(html)
def test_getgroups(self): from django.contrib.auth.models import User from tardis.tardis_portal.auth import auth_service rf = RequestFactory() req = rf.post('') req._post = {'username': '******', 'password': '******', 'authMethod': 'ldap'} user = auth_service.authenticate('ldap', request=req) self.assertTrue(isinstance(user, User)) req.user = user from tardis.tardis_portal.auth.ldap_auth import ldap_auth # Tests getGroups l = ldap_auth() self.assertEqual([g for g in l.getGroups(req.user)], ['full', 'systems'])
def protocol(request): # Basic Authentication if 'username' in request.POST and \ 'password' in request.POST: authMethod = request.POST['authMethod'] user = auth_service.authenticate( authMethod=authMethod, request=request) if user: html = 'Successful' return HttpResponse(html) else: html = 'Unsuccessful' return HttpResponse(html) else: html = 'Please enter Username and Password' return HttpResponse(html)
def protocol(request): # Basic Authentication if 'username' in request.POST and \ 'password' in request.POST: authMethod = request.POST['authMethod'] user = auth_service.authenticate(authMethod=authMethod, request=request) if user: html = 'Successful' return HttpResponse(html) else: html = 'Unsuccessful' return HttpResponse(html) else: html = 'Please enter Username and Password' return HttpResponse(html)
def test_getgroups(self): from django.contrib.auth.models import User from django.core.handlers.wsgi import WSGIRequest from tardis.tardis_portal.auth import auth_service req = WSGIRequest({"REQUEST_METHOD": "POST"}) req._post = { 'username': '******', 'password': '******', 'authMethod': 'ldap' } user = auth_service.authenticate('ldap', request=req) self.assertTrue(isinstance(user, User)) req.user = user from tardis.tardis_portal.auth.ldap_auth import ldap_auth # Tests getGroups l = ldap_auth() self.assertEqual([g for g in l.getGroups(req)], ['full', 'systems'])
def test_authenticate(self): from tardis.tardis_portal.auth.ldap_auth import ldap_auth from django.core.handlers.wsgi import WSGIRequest from django.contrib.auth.models import User # Tests Authenticate API l = ldap_auth() req = WSGIRequest({"REQUEST_METHOD": "POST"}) req._post = { 'username': '******', 'password': '******', 'authMethod': 'ldap' } u = l.authenticate(req) u1 = { 'email': '*****@*****.**', 'display': 'Test', 'id': 'testuser1' } self.failUnlessEqual(u, u1) # Test authservice API from tardis.tardis_portal.auth import auth_service req = WSGIRequest({"REQUEST_METHOD": "POST"}) req._post = { 'username': '******', 'password': '******', 'authMethod': 'ldap' } user = auth_service.authenticate('ldap', request=req) self.assertTrue(isinstance(user, User)) # Check that there is an entry in the user authentication table from tardis.tardis_portal.models import UserAuthentication userAuth = UserAuthentication.objects.get(userProfile__user=user, authenticationMethod=l.name) user1 = UserAuthentication.objects.get( username=user.username, authenticationMethod='ldap').userProfile.user self.assertEqual(user, user1)
def myt_auth(self, username, password): from tardis.tardis_portal.auth import auth_service class FakeRequest(object): POST = {} session = {} user = AnonymousUser() fake_request = FakeRequest() fake_request.POST = {'username': username, 'password': password} user = auth_service.authenticate( request=fake_request, authMethod=None) # checks all available methods if user and user.is_authenticated: # the following line is Australian Synchrotron specific and will # disappear when we start using their newer auth system user.epn_list = fake_request.session.get('_epn_list', []) self.username = username self.user = user return AUTH_SUCCESSFUL return AUTH_FAILED
def login(request): """ handler for login page """ logger.debug("start!") if request.user.is_authenticated(): # redirect the user to the home page if he is trying to go to the # login page return HttpResponseRedirect(request.POST.get("next_page", "/")) # TODO: put me in SETTINGS if "username" in request.POST and "password" in request.POST: authMethod = request.POST.get("authMethod", None) user = auth_service.authenticate(authMethod=authMethod, request=request) if user: next_page = request.POST.get("next_page", request.GET.get("next_page", "/")) user.backend = "django.contrib.auth.backends.ModelBackend" djauth.login(request, user) return HttpResponseRedirect(next_page) c = {"status": "Sorry, username and password don't match.", "error": True, "loginForm": LoginForm()} c = get_multimodal_context_data(c) return HttpResponseForbidden(render_response_index(request, "tardis_portal/login.html", c)) url = request.META.get("HTTP_REFERER", "/") u = urlparse(url) if u.netloc == request.META.get("HTTP_HOST", ""): next_page = u.path else: next_page = "/" c = {"loginForm": LoginForm(), "next_page": next_page} c = get_multimodal_context_data(c) return HttpResponse(render_response_index(request, "tardis_portal/login.html", c))
def site_settings(request): if request.method == 'POST': if 'username' in request.POST and 'password' in request.POST: user = auth_service.authenticate(request=request, authMethod=localdb_auth_key) if user is not None: if user.is_staff: x509 = open(settings.GRID_PROXY_FILE, 'r') c = { 'baseurl': request.build_absolute_uri('/'), 'proxy': x509.read(), 'filestorepath': settings.FILE_STORE_PATH} return HttpResponse(render_response_index( request, 'tardis_portal/site_settings.xml', c), content_type='application/xml') return return_response_error(request)
def login(request): from tardis.tardis_portal.staging import get_full_staging_path # Basic Authentication if "username" in request.POST and "password" in request.POST: authMethod = request.POST["authMethod"] user = auth_service.authenticate(authMethod=authMethod, request=request) if user: dl = request.FILES["file"] staging = settings.STAGING_PATH + "/" + str(user) + "/" eid, exp, folder_desc = createhpcexperiment(request, user, dl) next = str(staging) + str(eid) + "@" + str(eid) + "@" + str(folder_desc) return HttpResponse(next) else: next = "Invalid User name or Password" return HttpResponse(next) else: return HttpResponse("No username password entered")
def login(request): from tardis.tardis_portal.staging import get_full_staging_path # Basic Authentication if 'username' in request.POST and \ 'password' in request.POST: authMethod = request.POST['authMethod'] user = auth_service.authenticate( authMethod=authMethod, request=request) if user: dl = request.FILES['file'] staging = settings.STAGING_PATH + '/' +str(user)+ '/' eid,exp,folder_desc = createhpcexperiment(request,user,dl) next = str(staging) + str(eid) + '@' + str(eid) + '@' + str(folder_desc) return HttpResponse(next) else: next = 'Invalid User name or Password' return HttpResponse(next) else: return HttpResponse("No username password entered")
def register_experiment_ws_xmldata(request): ''' Web-service mechanism for registering an experiment, and triggering a corresponding file transfer. Although intended to be called as a web service, it actually works fine as a normal form, at /experiment/register ''' # --- start function body --- global experiment, idless_statuses, current_action, debug_POST experiment=None idless_statuses=[] logger.debug("Starting ingest process") # Check that we have received a form, abort otherwise try: if request.method != 'POST': # Happens when just viewing the form form = RegisterExperimentForm() # An unbound form return send_retry_response(request, form, '') logger.info("Starting experiment ingest processing") from datetime import datetime temp_title = "Ingest Received: " + \ datetime.now().strftime("%A, %d. %B %Y %I:%M%p") # A form bound to the POST data form = RegisterExperimentForm(request.POST, request.FILES) # Check that the form is filled out, abort otherwise. if not form.is_valid(): fail_message = "Form validation failure: <br/>" \ "Form Errors: " + str(form.errors) + "<br/>" \ try: add_status(RegistrationStatus.ERROR, fail_message) return send_retry_response(request, form, '') except Exception as ex: logger.error("Really an exception %s" % ex) logger.debug("Form validation: ok") xmldata = request.FILES['xmldata'] xmldata_meta = xmldata.name username = form.cleaned_data['username'] originid = form.cleaned_data['originid'] from_url = form.cleaned_data['from_url'] owners = request.POST.getlist('experiment_owner') debug_POST = "username: "******"<br/>" \ "xmldata: " + xmldata_meta + "<br/>" \ "originid: " + originid + "<br/>" \ "from_url: " + from_url + "<br/>" \ user = auth_service.authenticate(request=request, authMethod=localdb_auth_key) # Check user is authenticated, and user information is present, abort otherwise if not authentication_ok(user): return return_response_error(request) logger.debug("User authentication: ok") # Basic checks have passed, so create the experiment. global experiment experiment = Experiment(title=temp_title, approved=True, created_by=user,) experiment.save() # Now update old registration statuses with the new experiment number. for oldstatus in idless_statuses: rs = RegistrationStatus.objects.get(pk=oldstatus) rs.experiment=experiment rs.save() # If no owner provided, record a warning. check_owner(owners) # Write the submitted XML file to disk filename = path.join(experiment.get_or_create_directory(), 'mets_upload.xml') f = open(filename, 'wb+') for chunk in xmldata.chunks(): f.write(chunk) f.close() add_status(status=RegistrationStatus.PASS, message="Ingest Successfully Received") # Now process METS/XML file current_action = "Ingest Processing" try: _registerExperimentDocument(filename=filename, created_by=user, expid=experiment.id, owners=owners, username=username) except: add_status(status=RegistrationStatus.ERROR, message="METS metadata ingest failed", exception=True) return return_response_error(request) add_status(status=RegistrationStatus.PASS, message="Ingest Successfully Processed") if from_url: # form is ok, METS file ingested ok, and they also specified a file to transer current_action = 'File Transfer Request' logger.debug("transferring file") file_transfer_url = from_url + '/file_transfer/' do_file_transfer(file_transfer_url, originid, request) # Success: respond with just the ID of the newly created and processed experiment. response = HttpResponse(str(experiment.id), status=200) response['Location'] = request.build_absolute_uri( '/experiment/view/' + str(experiment.id)) return response except Exception as ex: add_status(RegistrationStatus.ERROR, "Unhandled exception in METS ingest.", exception=True)
def merge_auth_method(request): """Merge the account that the user is logged in as and the account that he provided in the Authentication Form. Merging accounts involve relinking the UserAuthentication table entries, transferring ObjectACL entries to the merged account, changing the Group memberships and deleting the unneeded account. :param Request request: the HTTP request object :returns: The HttpResponse which contains request.user's new list of authentication methods :rtype: HttpResponse """ from tardis.tardis_portal.auth import auth_service supportedAuthMethods = _getSupportedAuthMethods() LinkedUserAuthenticationForm = \ createLinkedUserAuthenticationForm(supportedAuthMethods) authForm = LinkedUserAuthenticationForm(request.POST) if not authForm.is_valid(): errorMessage = \ 'Please provide all the necessary information to authenticate.' return _getJsonFailedResponse(errorMessage) authenticationMethod = authForm.cleaned_data['authenticationMethod'] # let's try and authenticate here user = auth_service.authenticate(authMethod=authenticationMethod, request=request) if user is None: errorMessage = 'Wrong username or password. Please try again' return _getJsonFailedResponse(errorMessage) # if has already registered to use the provided auth method, then we can't # link the auth method to the user if user != request.user: # TODO: find all the experiments "user" has access to and link # "request.user" to them # check if the "request.user" has a userProfile userProfile, created = UserProfile.objects.get_or_create( user=request.user) # if he has, link 'user's UserAuthentication to it userAuths = UserAuthentication.objects.filter(userProfile__user=user) for userAuth in userAuths: userAuth.userProfile = userProfile userAuth.save() # also remove the current userAuth from the list of authentication # method options that can be added by this user del supportedAuthMethods[userAuth.authenticationMethod] # let's search for the ACLs that refer to 'user' and transfer them # to request.user userIdToBeReplaced = user.id replacementUserId = request.user.id # TODO: note that django_user here has been hardcoded. Uli's going # to change the implementation on his end so that I can just use a key # in here instead of a hardcoded string. experimentACLs = ObjectACL.objects.filter(pluginId='django_user', entityId=userIdToBeReplaced) for experimentACL in experimentACLs: # now let's check if there's already an existing entry in the ACL # for the given experiment and replacementUserId try: acl = ObjectACL.objects.get( pluginId='django_user', entityId=replacementUserId, content_type=experimentACL.content_type, object_id=experimentACL.object_id) acl.canRead = acl.canRead or experimentACL.canRead acl.canWrite = acl.canWrite or experimentACL.canWrite acl.canDelete = acl.canDelete or acl.canDelete acl.save() experimentACL.delete() except ObjectACL.DoesNotExist: experimentACL.entityId = replacementUserId experimentACL.save() # let's also change the group memberships of all the groups that 'user' # is a member of groups = Group.objects.filter(user=user) for group in groups: request.user.groups.add(group) # we can now delete 'user' user.delete() data = _setupJsonData(authForm, authenticationMethod, supportedAuthMethods) return _getJsonSuccessResponse(data)
def addfiles(request): import os from os.path import basename from os import path from tardis.tardis_portal.models import Dataset_File import itertools from tardis.hpctardis.metadata import process_all_experiments from tardis.hpctardis.metadata import process_experimentX if 'username' in request.POST and \ 'password' in request.POST: authMethod = request.POST['authMethod'] user = auth_service.authenticate(authMethod=authMethod, request=request) if user: eid = request.POST['eid'] desc = request.POST['desc'] folder = request.POST['folder'] eid = int(eid) # TODO Use the try and except auth_key = settings.DEFAULT_AUTH try: exp = Experiment.objects.get(pk=eid) author = exp.created_by except Experiment.DoesNotExist: logger.exception( 'Experiment for eid %i in addfiles does not exist' % eid) return HttpResponse("Experiment Not Found") current_user = str(user) created_user = str(author) if current_user == created_user: staging = path.join(settings.STAGING_PATH, str(user), str(eid), str(folder)) filelist = [] ds_desc = {} # import pdb # pdb.set_trace() for root, dirs, files in os.walk(staging): for named in files: filelist.append(named) next = str(filelist) ds_desc[desc] = filelist #TODO If needed for security - Metadata from the folder can be extracted #to check the folder name for d, df in ds_desc.items(): dataset = models.Dataset(description=d, experiment=exp) dataset.save() for f in df: logger.debug('f = %s' % f) filepath = path.join(staging, f) size = path.getsize(filepath) filename = path.basename(filepath) datafile = Dataset_File(dataset=dataset, filename=filename, url=filepath, size=size, protocol='staging') datafile.save() next = next + ' File path :' + staging process_experimentX(exp) next = next + ' The Author is : ' + str( author) + ',' + ' The User is : ' + str(user) return HttpResponse(next) else: next = 'The author of the experiment can only add the files (From Tardis)' return HttpResponse(next) else: return HttpResponse("UnSuccessful")
def do_migration(request): """Migrating account from the account that the logged in user has provided in the Authentication Form. Migration involve relinking the UserAuthentication table entries, transferring ObjectACL entries to the migrated account, changing the Group memberships and making the old account inactive. :param Request request: the HTTP request object :returns: The HttpResponse which contains request.user's new list of authentication methods :rtype: HttpResponse """ from tardis.tardis_portal.auth import auth_service # let's try and authenticate here user = auth_service.authenticate(authMethod="None", request=request) if user is None: errorMessage = 'Wrong username or password. Please try again' return _getJsonFailedResponse(errorMessage) # if has already registered to use the provided auth method, then we can't # link the auth method to the user if user == request.user: errorMessage = "You can't migrate to the same account" return _getJsonFailedResponse(errorMessage) logger.info("starting migration from %s to %s", user.username, request.user.username) # get request user authentication method data = _setupJsonData(old_user=user, new_user=request.user) # get authenticated user backend backend = request.session['_auth_user_backend'] # get key from backend class name auth_provider = get_matching_auth_provider(backend) logger.info("linking user authentication") # in most of the case it should return one authentication method # but in case it returns more than one we need to throw an exception # and notify admin about this. try: userAuths = UserAuthentication.objects.filter(userProfile__user=user) if userAuths.count() > 1: logger.error("Multiple authentication methods found for user %s" % user) return _getJsonFailedResponse("Something went wrong") if userAuths.count() == 1: old_authentication_method = userAuths[0].authenticationMethod else: old_authentication_method = getattr(settings, 'DEFAULT_AUTH', 'localdb') except ValueError: logger.error("issue with authentication methods for user %s" % user) old_authentication_method = getattr(settings, 'DEFAULT_AUTH', 'localdb') logger.info("Old authentication method is %s", old_authentication_method) # let's search for the ACLs that refer to 'user' and transfer them # to request.user userIdToBeReplaced = user.id replacementUserId = request.user.id # for logging migration event user_migration_record = OpenidUserMigration( old_user=user, new_user=request.user, old_user_auth_method=old_authentication_method, new_user_auth_method=auth_provider[0]) user_migration_record.save() logger.info("Staring object ACL migration") acl_migration(userIdToBeReplaced, replacementUserId, user_migration_record) # let's also change the group memberships of all the groups that 'user' # is a member of logger.info("Migrating user groups") groups = Group.objects.filter(user=user) logger.info("Number of groups found : %s", groups.count()) for group in groups: request.user.groups.add(group) # change old user username to username_authmethod amd make it inactive old_username = user.username user.username = old_username + '_' + old_authentication_method logger.info("setting old user to inactive") user.is_active = False user.save() # change new user username to old user new_user = request.user # copy api key from old user to new user so that MyData works seamlessly post migration logger.info("migrating api key") migrate_api_key(user, request.user) # migrate user permissions logger.info("migrating user permissions") migrate_user_permissions(user, request.user) # Add migration event record user_migration_record.migration_status = True user_migration_record.save() # send email for successful migration # TODO : get request user auth method logger.info("sending email to %s", user.email) notify_migration_status.apply_async( args=[user.id, new_user.username, auth_provider[1]], priority=settings.DEFAULT_EMAIL_TASK_PRIORITY) logger.info("migration complete") if new_user.has_perm('openid_migration.add_openidusermigration'): perm = Permission.objects.get(codename='add_openidusermigration') new_user.user_permissions.remove(perm) # refresh permissions from db User.objects.get(pk=new_user.pk) message = ( "Your account has been migrated successfully. " "Please note that your old account has been deactivated and is no longer accessible. " "Please use Login via %s for all of your future logins to %s." % (auth_provider[1], getattr(settings, 'SITE_TITLE', 'MyTardis'))) messages.add_message(request, messages.INFO, message) data['auth_method'] = auth_provider[0] return _getJsonSuccessResponse(data=data)
def merge_auth_method(request): """Merge the account that the user is logged in as and the account that he provided in the Authentication Form. Merging accounts involve relinking the UserAuthentication table entries, transferring ExperimentACL entries to the merged account, changing the Group memberships and deleting the unneeded account. :param request: the HTTP request object :returns: The HttpResponse which contains request.user's new list of authentication methods """ from tardis.tardis_portal.auth import auth_service supportedAuthMethods = _getSupportedAuthMethods() LinkedUserAuthenticationForm = createLinkedUserAuthenticationForm(supportedAuthMethods) authForm = LinkedUserAuthenticationForm(request.POST) if not authForm.is_valid(): errorMessage = "Please provide all the necessary information to authenticate." return _getJsonFailedResponse(errorMessage) authenticationMethod = authForm.cleaned_data["authenticationMethod"] # let's try and authenticate here user = auth_service.authenticate(authMethod=authenticationMethod, request=request) if user is None: errorMessage = "Wrong username or password. Please try again" return _getJsonFailedResponse(errorMessage) # if has already registered to use the provided auth method, then we can't # link the auth method to the user if user != request.user: # TODO: find all the experiments "user" has access to and link # "request.user" to them # check if the "request.user" has a userProfile userProfile, created = UserProfile.objects.get_or_create(user=request.user) # if he has, link 'user's UserAuthentication to it userAuths = UserAuthentication.objects.filter(userProfile__user=user) for userAuth in userAuths: userAuth.userProfile = userProfile userAuth.save() # also remove the current userAuth from the list of authentication # method options that can be added by this user del supportedAuthMethods[userAuth.authenticationMethod] # let's search for the ACLs that refer to 'user' and transfer them # to request.user userIdToBeReplaced = user.id replacementUserId = request.user.id # TODO: note that django_user here has been hardcoded. Uli's going # to change the implementation on his end so that I can just use a key # in here instead of a hardcoded string. experimentACLs = ExperimentACL.objects.filter(pluginId="django_user", entityId=userIdToBeReplaced) for experimentACL in experimentACLs: # now let's check if there's already an existing entry in the ACL # for the given experiment and replacementUserId try: acl = ExperimentACL.objects.get( pluginId="django_user", entityId=replacementUserId, experiment=experimentACL.experiment ) acl.canRead = acl.canRead or experimentACL.canRead acl.canWrite = acl.canWrite or experimentACL.canWrite acl.canDelete = acl.canDelete or acl.canDelete acl.save() experimentACL.delete() except ExperimentACL.DoesNotExist: experimentACL.entityId = replacementUserId experimentACL.save() # let's also change the group memberships of all the groups that 'user' # is a member of groups = Group.objects.filter(user=user) for group in groups: request.user.groups.add(group) # we can now delete 'user' user.delete() data = _setupJsonData(authForm, authenticationMethod, supportedAuthMethods) return _getJsonSuccessResponse(data)
def addfiles(request): import os from os.path import basename from os import path from tardis.tardis_portal.models import Dataset_File import itertools from tardis.apps.hpctardis.metadata import process_all_experiments from tardis.apps.hpctardis.metadata import process_experimentX if "username" in request.POST and "password" in request.POST: authMethod = request.POST["authMethod"] user = auth_service.authenticate(authMethod=authMethod, request=request) if user: eid = request.POST["eid"] desc = request.POST["desc"] folder = request.POST["folder"] eid = int(eid) # TODO Use the try and except auth_key = settings.DEFAULT_AUTH try: exp = Experiment.objects.get(pk=eid) author = exp.created_by except Experiment.DoesNotExist: logger.exception("Experiment for eid %i in addfiles does not exist" % eid) return HttpResponse("Experiment Not Found") current_user = str(user) created_user = str(author) if current_user == created_user: staging = path.join(settings.STAGING_PATH, str(user), str(eid), str(folder)) filelist = [] ds_desc = {} # import pdb # pdb.set_trace() for root, dirs, files in os.walk(staging): for named in files: filelist.append(named) next = str(filelist) ds_desc[desc] = filelist # TODO If needed for security - Metadata from the folder can be extracted # to check the folder name for d, df in ds_desc.items(): dataset = models.Dataset(description=d, experiment=exp) dataset.save() for f in df: logger.debug("f = %s" % f) filepath = path.join(staging, f) size = path.getsize(filepath) filename = path.basename(filepath) datafile = Dataset_File( dataset=dataset, filename=filename, url=filepath, size=size, protocol="staging" ) datafile.save() next = next + " File path :" + staging process_experimentX(exp) next = next + " The Author is : " + str(author) + "," + " The User is : " + str(user) return HttpResponse(next) else: next = "The author of the experiment can only add the files (From Tardis)" return HttpResponse(next) else: return HttpResponse("UnSuccessful")
def do_migration(request): """Migrating account from the account that the logged in user has provided in the Authentication Form. Migration involve relinking the UserAuthentication table entries, transferring ObjectACL entries to the migrated account, changing the Group memberships and making the old account inactive. :param Request request: the HTTP request object :returns: The HttpResponse which contains request.user's new list of authentication methods :rtype: HttpResponse """ from tardis.tardis_portal.auth import auth_service userAuthMethodList = [] # the list of supported non-local DB authentication methods supportedAuthMethods = getSupportedAuthMethods() # let's try and authenticate here user = auth_service.authenticate(authMethod="None", request=request) if user is None: errorMessage = 'Wrong username or password. Please try again' return _getJsonFailedResponse(errorMessage) # if has already registered to use the provided auth method, then we can't # link the auth method to the user if user == request.user: errorMessage = "You can't migrate to the same account" return _getJsonFailedResponse(errorMessage) logger.info("starting migration from %s to %s", user.username, request.user.username) # check if the "request.user" has a userProfile userProfile, created = UserProfile.objects.get_or_create( user=request.user) # get request user authentication method data = _setupJsonData(old_user=user, new_user=request.user) # get authenticated user backend backend = request.session['_auth_user_backend'] # get key from backend class name auth_provider = get_matching_auth_provider(backend) logger.info("linking user authentication") # in most of the case it should return one authentication method # but in case it returns more than one we need to throw an exception # and notify admin about this. try: userAuths = UserAuthentication.objects.filter( userProfile__user=user) if userAuths.count() > 1: logger.error("Multiple authentication methods found for user %s" % user) return _getJsonFailedResponse("Something went wrong") if userAuths.count() == 1: old_authentication_method = userAuths[0].authenticationMethod else: old_authentication_method = getattr(settings, 'DEFAULT_AUTH', 'localdb') except ValueError: logger.error("issue with authentication methods for user %s" % user) old_authentication_method = getattr(settings, 'DEFAULT_AUTH', 'localdb') logger.info("Old authentication method is %s", old_authentication_method) # let's search for the ACLs that refer to 'user' and transfer them # to request.user userIdToBeReplaced = user.id replacementUserId = request.user.id # for logging migration event user_migration_record = OpenidUserMigration( old_user=user, new_user=request.user, old_user_auth_method=old_authentication_method, new_user_auth_method=auth_provider[0]) user_migration_record.save() logger.info("Staring object ACL migration") acl_migration(userIdToBeReplaced, replacementUserId, user_migration_record) # let's also change the group memberships of all the groups that 'user' # is a member of logger.info("Migrating user groups") groups = Group.objects.filter(user=user) logger.info("Number of groups found : %s", groups.count()) for group in groups: request.user.groups.add(group) # change old user username to username_authmethod amd make it inactive old_username = user.username user.username = old_username + '_' + old_authentication_method logger.info("setting old user to inactive") user.is_active = False user.save() # change new user username to old user new_user = request.user # copy api key from old user to new user so that MyData works seamlessly post migration logger.info("migrating api key") migrate_api_key(user, request.user) # migrate user permissions logger.info("migrating user permissions") migrate_user_permissions(user, request.user) # Add migration event record user_migration_record.migration_status = True user_migration_record.save() # send email for successful migration # TODO : get request user auth method logger.info("sending email to %s", user.email) notify_migration_status.delay(user, new_user.username, auth_provider[1]) logger.info("migration complete") if new_user.has_perm('openid_migration.add_openidusermigration'): perm = Permission.objects.get(codename='add_openidusermigration') new_user.user_permissions.remove(perm) # refresh permissions from db User.objects.get(pk=new_user.pk) message = ( "Your account has been migrated successfully. " "Please note that your old account has been deactivated and is no longer accessible. " "Please use Login via %s for all of your future logins to %s." % (auth_provider[1], getattr(settings, 'SITE_TITLE', 'MyTardis'))) messages.add_message(request, messages.INFO, message) data['auth_method'] = auth_provider[0] return _getJsonSuccessResponse(data=data)
def login(request): if type(request.user) is not AnonymousUser: return HttpResponseRedirect('/') c = Context({'loginForm': LoginForm()}) # get POST and GET variables username = request.POST.get('username', '') password = request.POST.get('password', '') authMethod = request.POST.get('authMethod', '') next = request.GET.get('next', '/') if not username or not password: # show login form return HttpResponse(render_response_index(request, 'tardis_portal/login.html', c)) #authenticate user in mytardis localdb user = auth_service.authenticate(authMethod=authMethod, request=request) user_exist = None try: user_exist = User.objects.get(username=username) except User.DoesNotExist: pass # check the existence of user if user: # user existed and authentication passed user.backend = 'django.contrib.auth.backends.ModelBackend' tardis_login(request, user) return HttpResponseRedirect(next) elif user_exist: # user existed but authentication failed c['status'] = "Sorry, username and password don't match." c['error'] = True return HttpResponseForbidden( render_response_index(request, 'tardis_portal/login.html', c)) else: # user doesn't exist, create one if EMBS authentication succeeded # authenticate username and password with EMBS system embs_url = settings.EMBS_URL embs_url += "username=%s&passwordmd5=%s" % ( str(username).lower(), hashlib.md5(password).hexdigest() ) try: response = urllib2.urlopen(embs_url).read() if response.status() == 200: # succeeded authentication # dummy data testing start # dummy_status = 200 # dummy_json = """ #{"user_id": "1", # "fname": "e123", # "lname": "e123", # "title": "mr", # "department": "rmmf", # "login_name": "e123", # "email": "*****@*****.**", # "phone": "12345", # "user_type": "student", # "user_category": "student" } """ # if dummy_status == 200: # dummy data testing end embs_user_group_name = settings.EMBS_USER_GROUP_NAME try: # check existence of default user group group = Group.objects.get(name=embs_user_group_name) except Group.DoesNotExist: # create a new group if it doesn't exist group = Group(name=embs_user_group_name) group.save() # add basic permissions to the group group.permissions.add(Permission.objects.get(codename='add_experiment'), Permission.objects.get(codename='change_experiment'), Permission.objects.get(codename='change_experimentacl'), Permission.objects.get(codename='change_userauthentication')) group.save() # create new user user_json = json.loads(response.read()) # user_json = json.loads(dummy_json) email = user_json['email'] first_name = user_json['fname'] last_name = user_json['lname'] user = User.objects.create_user(username=username, password=password, email=email) user.first_name = first_name user.last_name = last_name # assign the user to the default user group user.groups.add(group) #user.user_permissions.add(Permission.objects.get(codename='add_experiment')) #user.user_permissions.add(Permission.objects.get(codename='change_experiment')) #user.user_permissions.add(Permission.objects.get(codename='change_experimentacl')) #user.user_permissions.add(Permission.objects.get(codename='change_group')) #user.user_permissions.add(Permission.objects.get(codename='change_userauthentication')) user.save() # create new user profile userProfile = UserProfile(user=user, isDjangoAccount=True) userProfile.save() # create new user authentication userAuth = UserAuthentication(userProfile=userProfile, username=username, authenticationMethod=authMethod) userAuth.save() # log the valid user in user.backend = 'django.contrib.auth.backends.ModelBackend' tardis_login(request, user) return HttpResponseRedirect(next) else: # authentication failed c['status'] = "Sorry, username and password don't match." c['error'] = True return HttpResponseForbidden( render_response_index(request, 'tardis_portal/login.html', c)) except urllib2.URLError, e: c['status'] = "Sorry, error happened with EMBS authentication: %s" % e c['error'] = True
def register_experiment_ws_xmldata(request): status = '' if request.method == 'POST': # If the form has been submitted... # A form bound to the POST data form = RegisterExperimentForm(request.POST, request.FILES) if form.is_valid(): # All validation rules pass xmldata = request.FILES['xmldata'] username = form.cleaned_data['username'] origin_id = form.cleaned_data['originid'] from_url = form.cleaned_data['from_url'] user = auth_service.authenticate(request=request, authMethod=localdb_auth_key) if user: if not user.is_active: return return_response_error(request) else: return return_response_error(request) e = Experiment( title='Placeholder Title', approved=True, created_by=user, ) e.save() eid = e.id filename = path.join(e.get_or_create_directory(), 'mets_upload.xml') f = open(filename, 'wb+') for chunk in xmldata.chunks(): f.write(chunk) f.close() logger.info('=== processing experiment: START') owners = request.POST.getlist('experiment_owner') try: _registerExperimentDocument(filename=filename, created_by=user, expid=eid, owners=owners, username=username) logger.info('=== processing experiment %s: DONE' % eid) except: logger.exception('=== processing experiment %s: FAILED!' % eid) return return_response_error(request) if from_url: logger.debug('=== sending file request') logger.info('Sending received_remote signal') from tardis.tardis_portal.signals import received_remote received_remote.send(sender=Experiment, instance=e, uid=origin_id, from_url=from_url) response = HttpResponse(str(eid), status=200) response['Location'] = request.build_absolute_uri( '/experiment/view/' + str(eid)) return response else: form = RegisterExperimentForm() # An unbound form c = Context({ 'form': form, 'status': status, 'subtitle': 'Register Experiment', 'searchDatafileSelectionForm': getNewSearchDatafileSelectionForm()}) return HttpResponse(render_response_index(request, 'tardis_portal/register_experiment.html', c))