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_par(request, parentObject, otype, stype): all_schema = Schema.objects.filter(type=stype, immutable=False) if 'schema_id' in request.GET: schema_id = request.GET['schema_id'] elif all_schema.count() > 0: schema_id = all_schema[0].id else: return HttpResponse(render_response_index( request, 'tardis_portal/ajax/parameter_set_unavailable.html', {})) schema = Schema.objects.get(id=schema_id) parameternames = ParameterName.objects.filter( schema__namespace=schema.namespace) success = False valid = True if request.method == 'POST': request = remove_csrf_token(request) class DynamicForm(create_datafile_add_form( schema.namespace, parentObject, request=request)): pass form = DynamicForm(request.POST) if form.is_valid(): save_datafile_add_form(schema.namespace, parentObject, request) success = True else: valid = False else: class DynamicForm(create_datafile_add_form( schema.namespace, parentObject)): pass form = DynamicForm() c = { 'schema': schema, 'form': form, 'parameternames': parameternames, 'type': otype, 'success': success, 'valid': valid, 'parentObject': parentObject, 'all_schema': all_schema, 'schema_id': schema.id, } return HttpResponse(render_response_index(request, 'tardis_portal/ajax/parameteradd.html', c))
def auth_exp_publish(request): """ Check the provided authcode against outstanding experiments awaiting authorisation and if match, then give authorisation. :param request: the web request :type request: :class:`django.http.HttpRequest` """ context = {} if request.method == "GET": exp_id = None if "expid" in request.GET: exp_id = request.GET["expid"] else: context[u"message"] = u"Unknown experiment" return HttpResponse(render_response_index(request, u"hpctardis/authorise_publish.html", Context(context))) try: experiment = Experiment.objects.get(id=exp_id) except Experiment.DoesNotExist: context[u"message"] = u"Unknown experiment" return HttpResponse(render_response_index(request, "hpctardis/authorise_publish.html", Context(context))) if experiment.public: context[u"message"] = u"Experiment already public" return HttpResponse(render_response_index(request, "hpctardis/authorise_publish.html", Context(context))) if "authcode" in request.GET: authcode = request.GET["authcode"] else: context[u"message"] = u"bad authcode" return HttpResponse(render_response_index(request, "hpctardis/authorise_publish.html", Context(context))) auths = PublishAuthorisation.objects.filter(auth_key=authcode, experiment=experiment) for auth in auths: if auth.status == PublishAuthorisation.PENDING_APPROVAL: if authcode == auth.auth_key: auth.status = PublishAuthorisation.APPROVED_PUBLIC auth.date_authorised = datetime.datetime.now() auth.save() context[u"message"] = u"Thank you for your approval %s" % auth.party_record break elif auth.status == PublishAuthorisation.APPROVED_PUBLIC: if authcode == auth.auth_key: context[u"message"] = u"Already authorised" break else: context[u"message"] = u"unknown command %s" % auth.status # TODO: send message to original owner if exp now public _ = _promote_experiments_to_public(experiment) return HttpResponse(render_response_index(request, "hpctardis/authorise_publish.html", Context(context)))
def index(request, experiment_id): url = 'monash_ands/form.html' try: e = Experiment.objects.get(id=experiment_id) import sys allowed_protocol = sys.modules['%s.%s.settings' % (settings.TARDIS_APP_ROOT, 'monash_ands')].ALLOWED_PROTOCOL if not request.user.is_authenticated(): # todo: de-duplicate from django.template import Context c = Context() c['disallowed_protocol'] = True return HttpResponse(render_response_index(request, url, c)) ua = UserAuthentication.objects.get(username=request.user.username) if not ua.authenticationMethod == allowed_protocol: from django.template import Context c = Context() c['is_owner'] = authz.has_experiment_ownership(request, experiment_id) c['disallowed_protocol'] = True return HttpResponse(render_response_index(request, url, c)) if not request.POST: monashandsService = MonashANDSService(experiment_id) c = monashandsService.get_context(request) if request.user.is_authenticated(): c['is_owner'] = authz.has_experiment_ownership(request, experiment_id) c['experiment'] = e cch = CreativeCommonsHandler(experiment_id=experiment_id, create=False) c['has_cc_license'] = cch.has_cc_license() return HttpResponse(render_response_index(request, url, c)) else: monashandsService = MonashANDSService(experiment_id) c = monashandsService.register(request) if request.user.is_authenticated(): c['is_owner'] = authz.has_experiment_ownership(request, experiment_id) c['experiment'] = e return HttpResponse(render_response_index(request, url, c)) except Exception, e: # todo: check with web services for adequate responses.. message = '<b>An error occured:</b> ' + str(e) return HttpResponse(content=message)
def create_user(request): if 'user' not in request.POST: c = {'createUserPermissionsForm': CreateUserPermissionsForm()} response = HttpResponse( render_response_index(request, 'tardis_portal/ajax/create_user.html', c)) return response authMethod = localdb_auth_key if 'user' in request.POST: username = request.POST['user'] if 'authMethod' in request.POST: authMethod = request.POST['authMethod'] if 'email' in request.POST: email = request.POST['email'] if 'password' in request.POST: password = request.POST['password'] try: with transaction.atomic(): validate_email(email) user = User.objects.create_user(username, email, password) authentication = UserAuthentication( userProfile=user.userprofile, username=username, authenticationMethod=authMethod) authentication.save() except ValidationError: return HttpResponse('Could not create user %s ' '(Email address is invalid: %s)' % (username, email), status=403) except: # FIXME return HttpResponse( 'Could not create user %s ' '(It is likely that this username already exists)' % (username), status=403) c = {'user_created': username} transaction.commit() response = HttpResponse( render_response_index(request, 'tardis_portal/ajax/create_user.html', c)) return response
def add_par(request, parentObject, otype, stype): all_schema = Schema.objects.filter(type=stype, immutable=False) if "schema_id" in request.GET: schema_id = request.GET["schema_id"] elif all_schema.count() > 0: schema_id = all_schema[0].id else: return HttpResponse(render_response_index(request, "tardis_portal/ajax/parameter_set_unavailable.html", {})) schema = Schema.objects.get(id=schema_id) parameternames = ParameterName.objects.filter(schema__namespace=schema.namespace) success = False valid = True if request.method == "POST": request = remove_csrf_token(request) class DynamicForm(create_datafile_add_form(schema.namespace, parentObject, request=request)): pass form = DynamicForm(request.POST) if form.is_valid(): save_datafile_add_form(schema.namespace, parentObject, request) success = True else: valid = False else: class DynamicForm(create_datafile_add_form(schema.namespace, parentObject)): pass form = DynamicForm() c = { "schema": schema, "form": form, "parameternames": parameternames, "type": otype, "success": success, "valid": valid, "parentObject": parentObject, "all_schema": all_schema, "schema_id": schema.id, } return HttpResponse(render_response_index(request, "tardis_portal/ajax/parameteradd.html", c))
def create_user(request): if 'user' not in request.POST: c = {'createUserPermissionsForm': CreateUserPermissionsForm()} response = HttpResponse(render_response_index( request, 'tardis_portal/ajax/create_user.html', c)) return response authMethod = localdb_auth_key if 'user' in request.POST: username = request.POST['user'] if 'authMethod' in request.POST: authMethod = request.POST['authMethod'] if 'email' in request.POST: email = request.POST['email'] if 'password' in request.POST: password = request.POST['password'] try: with transaction.atomic(): validate_email(email) user = User.objects.create_user(username, email, password) authentication = UserAuthentication(userProfile=user.userprofile, username=username, authenticationMethod=authMethod) authentication.save() except ValidationError: return HttpResponse('Could not create user %s ' '(Email address is invalid: %s)' % (username, email), status=403) except: # FIXME return HttpResponse( 'Could not create user %s ' '(It is likely that this username already exists)' % (username), status=403) c = {'user_created': username} transaction.commit() response = HttpResponse(render_response_index( request, 'tardis_portal/ajax/create_user.html', c)) return response
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 ''' 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 return_response_datafile_private(request,exp): c = Context({'exp_id':exp.id, 'exp_name':exp.title, 'owner_name':exp.created_by.get_full_name(), 'owner_email': exp.created_by.email}) return HttpResponseNotFound(render_response_index(request, 'hpctardis/contact_download.html', c))
def mydetails(request): c = Context() existing_details = OwnerDetails.objects.filter(user=request.user) if existing_details.count() == 1: owner_details = existing_details[0] else: owner_details = None if request.method == 'POST': form = OwnerDetailsForm(request.POST, instance=owner_details) if form.is_valid(): form.save() request.POST = {'status': 'Details Saved'} c['status'] = 'Details Saved' else: c['status'] = "Errors exist in form." c["error"] = 'true' #return redirect(reverse('tardis.tardis_portal.views.experiment_index')) else: if not owner_details: owner_details = OwnerDetails(user=request.user, first_name=request.user.first_name, last_name=request.user.last_name, email=request.user.email) form = OwnerDetailsForm(instance=owner_details) c['form'] = form return HttpResponse(render_response_index(request, 'tardis_portal/rif-cs/mydetails.html', c))
def retrieve_group_list_by_user(request): groups = Group.objects.filter(groupadmin__user=request.user) c = {'groups': groups} return HttpResponse( render_response_index(request, 'tardis_portal/ajax/group_list.html', c))
def partners(request): c = Context({'subtitle': 'Partners', 'about_pressed': True, 'nav': [{'name': 'Partners', 'link': '/partners/'}]}) return HttpResponse(render_response_index(request, 'tardis_portal/partners.html', c))
def display_datafile_details(request, datafile_id): """ Displays a box, with a list of interaction options depending on the file type given and displays the one with the highest priority first. Views are set up in settings. Order of list is taken as priority. Given URLs are called with the datafile id appended. """ # retrieve valid interactions for file type the_file = DataFile.objects.get(id=datafile_id) the_schemas = [p.schema.namespace for p in the_file.getParameterSets()] default_view = "Datafile Metadata" apps = [ (default_view, '/ajax/parameters'), ] if hasattr(settings, "DATAFILE_VIEWS"): apps += settings.DATAFILE_VIEWS views = [] for ns, url in apps: if ns == default_view: views.append({"url": "%s/%s/" % (url, datafile_id), "name": default_view}) elif ns in the_schemas: schema = Schema.objects.get(namespace__exact=ns) views.append({"url": "%s/%s/" % (url, datafile_id), "name": schema.name}) context = { 'datafile_id': datafile_id, 'views': views, } return HttpResponse(render_response_index( request, "tardis_portal/ajax/datafile_details.html", context))
def retrieve_access_list_user_readonly(request, experiment_id): user_acls = Experiment.safe.user_acls(experiment_id) c = {'user_acls': user_acls, 'experiment_id': experiment_id} return HttpResponse( render_response_index( request, 'tardis_portal/ajax/access_list_user_readonly.html', c))
def share(request, experiment_id): ''' Choose access rights and licence. ''' experiment = Experiment.objects.get(id=experiment_id) user = request.user c = {} c['has_write_permissions'] = \ authz.has_write_permissions(request, experiment_id) c['has_download_permissions'] = \ authz.has_experiment_download_access(request, experiment_id) if user.is_authenticated(): c['is_owner'] = authz.has_experiment_ownership(request, experiment_id) c['is_superuser'] = user.is_superuser c['is_staff'] = user.is_staff domain = Site.objects.get_current().domain public_link = experiment.public_access >= Experiment.PUBLIC_ACCESS_METADATA c['experiment'] = experiment c['public_link'] = public_link c['domain'] = domain return HttpResponse(render_response_index(request, 'tardis_portal/ajax/share.html', c))
def get(self, request, *args, **kwargs): """ :param request: a HTTP request object :type request: :class:`django.http.HttpRequest` :return: The Django response object :rtype: :class:`django.http.HttpResponse` """ dataset_id = kwargs.get('dataset_id', None) if dataset_id is None: return return_response_error(request) dataset = Dataset.objects.get(id=dataset_id) if not dataset: return return_response_not_found(request) c = self.get_context_data(request, dataset, **kwargs) template_name = kwargs.get('template_name', None) if template_name is None: template_name = self.template_name return HttpResponse(render_response_index(request, template_name, c))
def view_rifcs(request, experiment_id): """View the rif-cs of an existing experiment. :param request: a HTTP Request instance :type request: :class:`django.http.HttpRequest` :param experiment_id: the ID of the experiment to be viewed :type experiment_id: string :rtype: :class:`django.http.HttpResponse` """ try: experiment = Experiment.safe.get(request.user, experiment_id) except PermissionDenied: return return_response_error(request) except Experiment.DoesNotExist: return return_response_not_found(request) try: rifcs_provs = settings.RIFCS_PROVIDERS except AttributeError: rifcs_provs = () from tardis.tardis_portal.publish.publishservice import PublishService pservice = PublishService(rifcs_provs, experiment) context = pservice.get_context() if context is None: # return error page or something return return_response_error(request) template = pservice.get_template() return HttpResponse(render_response_index(request, template, context), content_type="text/xml")
def edit_sample(request, experiment_id, sample_id): try: experiment = Experiment.safe.get(request, experiment_id) except PermissionDenied: return return_response_error(request) except Experiment.DoesNotExist: return return_response_not_found(request) c = Context() c['experiment'] = experiment sample = Sample.objects.get(id=sample_id) c['sample_count'] = sample.name if request.POST: form = SampleForm(request.POST, instance=sample, extra=0) if form.is_valid(): full_sample = form.save(experiment_id, commit=False) full_sample.save_m2m() request.POST = {'status': "Sample Created."} return _redirect(experiment_id) c['status'] = "Errors exist in form." c["error"] = 'true' else: form = SampleForm(instance=sample, extra=0) c['form'] = form c['status'] = form.errors return HttpResponse(render_response_index(request, 'tardis_portal/experiment_sample.html', c))
def user_guide(request): c = { 'user_guide_location': getattr( settings, 'CUSTOM_USER_GUIDE', 'user_guide/index.html'), } return HttpResponse(render_response_index(request, 'tardis_portal/user_guide.html', c))
def new_sample(request, experiment_id): try: experiment = Experiment.safe.get(request, experiment_id) except PermissionDenied: return return_response_error(request) except Experiment.DoesNotExist: return return_response_not_found(request) c = Context() c['experiment'] = experiment samples = Sample.objects.filter(experiment=experiment_id) c['sample_count'] = samples.count() + 1 if request.method == 'POST': form = SampleForm(request.POST) if form.is_valid(): sample = form.save(experiment_id, commit=False) sample.save_m2m() request.POST = {'status': "Sample Created."} return _redirect(experiment_id) c['status'] = "Errors exist in form." c["error"] = 'true' else: form = SampleForm(extra=1) c['form'] = form c['status'] = form.errors return HttpResponse(render_response_index(request, 'tardis_portal/experiment_sample.html', c))
def user_guide(request): c = { 'user_guide_location': getattr(settings, 'CUSTOM_USER_GUIDE', 'user_guide/index.html'), } return HttpResponse( render_response_index(request, 'tardis_portal/user_guide.html', c))
def get(self, request, *args, **kwargs): """ :param request: a HTTP request object :type request: :class:`django.http.HttpRequest` :return: The Django response object :rtype: :class:`django.http.HttpResponse` """ dataset_id = kwargs.get('dataset_id', None) if dataset_id is None: return return_response_error(request) dataset = Dataset.objects.get(id=dataset_id) if not dataset: return return_response_not_found(request) c = self.get_context_data(request, dataset, **kwargs) template_name = kwargs.get('template_name', None) if template_name is None: template_name = self.template_name return HttpResponse(render_response_index( request, template_name, c) )
def index(request): c = Context({'form': EmbargoSearchForm(), 'subtitle': 'Embargo Periods', 'searched': False, 'header': 'Register Metaman File'}) return HttpResponse(render_response_index(request, 'tardis_portal/embargo_index.html', c))
def get(self, request, *args, **kwargs): """ The index view, intended to render the front page of the MyTardis site listing recent experiments. This default view can be overriden by defining a dictionary INDEX_VIEWS in settings which maps SITE_ID's or domain names to an alternative view function (similar to the DATASET_VIEWS or EXPERIMENT_VIEWS overrides). :param request: a HTTP request object :type request: :class:`django.http.HttpRequest` :return: The Django response object :rtype: :class:`django.http.HttpResponse` """ dataset_id = kwargs.get('dataset_id', None) if dataset_id is None: return return_response_error(request) dataset = Dataset.objects.get(id=dataset_id) if not dataset: return return_response_not_found(request) view_override = self.find_custom_view_override(request, dataset) if view_override is not None: return view_override c = self.get_context_data(request, dataset, **kwargs) template_name = kwargs.get('template_name', None) if template_name is None: template_name = self.template_name return HttpResponse(render_response_index(request, template_name, c))
def get(self, request, *args, **kwargs): """ View an existing experiment. :param request: a HTTP Request instance :type request: :class:`django.http.HttpRequest` :param experiment_id: the ID of the experiment :rtype: :class:`django.http.HttpResponse` """ experiment_id = kwargs.get('experiment_id', None) if experiment_id is None: return return_response_error(request) try: experiment = Experiment.safe.get(request.user, experiment_id) except PermissionDenied: return return_response_error(request) except Experiment.DoesNotExist: return return_response_not_found(request) if not experiment: return return_response_not_found(request) view_override = self.find_custom_view_override(request, experiment) if view_override is not None: return view_override c = self.get_context_data(request, experiment) template_name = kwargs.get('template_name', None) if template_name is None: template_name = self.template_name return HttpResponse(render_response_index(request, template_name, c))
def search_quick(request): get = False experiments = Experiment.objects.all().order_by('title') if 'results' in request.GET: get = True if 'quicksearch' in request.GET \ and len(request.GET['quicksearch']) > 0: experiments = \ experiments.filter( title__icontains=request.GET['quicksearch']) | \ experiments.filter( institution_name__icontains=request.GET['quicksearch']) | \ experiments.filter( experimentauthor__author__name__icontains=request.GET[ 'quicksearch']) | \ experiments.filter( pdbid__pdbid__icontains=request.GET['quicksearch']) experiments = experiments.distinct() logger.debug(experiments) c = {'submitted': get, 'experiments': experiments, 'subtitle': 'Search Experiments'} return HttpResponse(render_response_index(request, 'tardis_portal/search_experiment.html', c))
def retrieve_group_userlist_readonly(request, group_id): from tardis.tardis_portal.forms import ManageGroupPermissionsForm users = User.objects.filter(groups__id=group_id) c = {'users': users, 'group_id': group_id, 'manageGroupPermissionsForm': ManageGroupPermissionsForm()} return HttpResponse(render_response_index(request, 'tardis_portal/ajax/group_user_list_readonly.html', c))
def retrieve_access_list_user(request, experiment_id): from tardis.tardis_portal.forms import AddUserPermissionsForm user_acls = Experiment.safe.user_acls(experiment_id) c = {'user_acls': user_acls, 'experiment_id': experiment_id, 'addUserPermissionsForm': AddUserPermissionsForm()} return HttpResponse(render_response_index(request, 'tardis_portal/ajax/access_list_user.html', c))
def public_data(request): ''' list of public experiments ''' c = {'public_experiments': Experiment.safe.public().order_by('-update_time'), } return HttpResponse(render_response_index( request, 'tardis_portal/public_data.html', c))
def retrieve_access_list_external(request, experiment_id): groups = Experiment.safe.external_users(experiment_id) c = {'groups': groups, 'experiment_id': experiment_id} return HttpResponse( render_response_index(request, 'tardis_portal/ajax/access_list_external.html', c))
def get(self, request, *args, **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.GET.get('next_page', '/')) c = self.get_context_data(request, **kwargs) return render_response_index(request, self.template_name, c)
def retrieve_parameters(request, dataset_file_id): parametersets = DatafileParameterSet.objects.all() parametersets = parametersets.filter(dataset_file__pk=dataset_file_id) c = Context({"parametersets": parametersets}) return HttpResponse(render_response_index(request, "tardis_portal/ajax/parameters.html", c))
def create_user(request): if "user" not in request.POST: c = {"createUserPermissionsForm": CreateUserPermissionsForm()} response = HttpResponse(render_response_index(request, "tardis_portal/ajax/create_user.html", c)) return response authMethod = localdb_auth_key if "user" in request.POST: username = request.POST["user"] if "authMethod" in request.POST: authMethod = request.POST["authMethod"] if "email" in request.POST: email = request.POST["email"] if "password" in request.POST: password = request.POST["password"] try: with transaction.atomic(): validate_email(email) user = User.objects.create_user(username, email, password) authentication = UserAuthentication( userProfile=user.userprofile, username=username, authenticationMethod=authMethod ) authentication.save() except ValidationError: return HttpResponse( "Could not create user %s " "(Email address is invalid: %s)" % (username, email), status=403 ) except: # FIXME return HttpResponse( "Could not create user %s " "(It is likely that this username already exists)" % (username), status=403 ) c = {"user_created": username} transaction.commit() response = HttpResponse(render_response_index(request, "tardis_portal/ajax/create_user.html", c)) return response
def experiment_description(request, experiment_id): """View an existing experiment's description. To be loaded via ajax. :param request: a HTTP Request instance :type request: :class:`django.http.HttpRequest` :param experiment_id: the ID of the experiment to be edited :type experiment_id: string :rtype: :class:`django.http.HttpResponse` """ c = {} try: experiment = Experiment.safe.get(request.user, experiment_id) except PermissionDenied: return return_response_error(request) except Experiment.DoesNotExist: return return_response_not_found(request) c['experiment'] = experiment c['subtitle'] = experiment.title c['nav'] = [{ 'name': 'Data', 'link': '/experiment/view/' }, { 'name': experiment.title, 'link': experiment.get_absolute_url() }] c['authors'] = experiment.experimentauthor_set.all() c['datafiles'] = \ DataFile.objects.filter(dataset__experiments=experiment_id) c['owners'] = experiment.get_owners() # calculate the sum of the datafile sizes c['size'] = DataFile.sum_sizes(c['datafiles']) c['has_download_permissions'] = \ authz.has_experiment_download_access(request, experiment_id) c['has_write_permissions'] = \ authz.has_write_permissions(request, experiment_id) if request.user.is_authenticated(): c['is_owner'] = authz.has_experiment_ownership(request, experiment_id) _add_protocols_and_organizations(request, experiment, c) if 'status' in request.GET: c['status'] = request.GET['status'] if 'error' in request.GET: c['error'] = request.GET['error'] return HttpResponse( render_response_index( request, 'tardis_portal/ajax/experiment_description.html', c))
def view_full_dataset(request, dataset_id): """Displays a MX Dataset and associated information. Shows a full (hundreds of images) dataset its metadata and a list of associated files with the option to show metadata of each file and ways to download those files. With write permission this page also allows uploading and metadata editing. Settings for this view: INSTALLED_APPS += ("tardis.apps.mx_views",) DATASET_VIEWS = [("http://synchrotron.org.au/views/dataset/full", "tardis.apps.mx_views.views.view_full_dataset"),] """ dataset = Dataset.objects.get(id=dataset_id) def get_datafiles_page(): # pagination was removed by someone in the interface but not here. # need to fix. pgresults = 100 paginator = Paginator(dataset.dataset_file_set.all(), pgresults) try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 # If page request (9999) is out of range, deliver last page of results. try: return paginator.page(page) except (EmptyPage, InvalidPage): return paginator.page(paginator.num_pages) display_images = dataset.get_images() image_count = len(display_images) if image_count > 4: # take 4 evenly spaced images from the set display_images = display_images[0::image_count / 4][:4] c = Context({ 'dataset': dataset, 'datafiles': get_datafiles_page(), 'parametersets': dataset.getParameterSets() .exclude(schema__hidden=True), 'has_download_permissions': authz.has_dataset_download_access(request, dataset_id), 'has_write_permissions': authz.has_dataset_write(request, dataset_id), 'from_experiment': \ get_experiment_referer(request, dataset_id), 'other_experiments': \ authz.get_accessible_experiments_for_dataset(request, dataset_id), 'display_images': display_images, }) return HttpResponse(render_response_index( request, 'mx_views/view_full_dataset.html', c))
def view_full_dataset(request, dataset_id): """Displays a HRMC Dataset as a single scatter plot of x,y values from grfinalXX.dat and gerr.dat files Requires BDPMytardis with single Settings for this view: INSTALLED_APPS += ("tardis.apps.hrmc_views",) DATASET_VIEWS = [("http://rmit.edu.au/schemas/hrmcdataset", "tardis.apps.hrmc_views.views.view_full_dataset"),] """ logger.debug("got to hrmc views") dataset = Dataset.objects.get(id=dataset_id) # FIXME: as single image, can remove this def get_datafiles_page(): # pagination was removed by someone in the interface but not here. # need to fix. pgresults = 100 paginator = Paginator(dataset.dataset_file_set.all(), pgresults) try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 # If page request (9999) is out of range, deliver last page of results. try: return paginator.page(page) except (EmptyPage, InvalidPage): return paginator.page(paginator.num_pages) display_images = [] image_to_show = get_image_to_show(dataset) if image_to_show: display_images.append(image_to_show) c = Context({ 'dataset': dataset, 'datafiles': get_datafiles_page(), 'parametersets': dataset.getParameterSets() .exclude(schema__hidden=True), 'has_download_permissions': authz.has_dataset_download_access(request, dataset_id), 'has_write_permissions': authz.has_dataset_write(request, dataset_id), 'from_experiment': \ get_experiment_referer(request, dataset_id), 'other_experiments': \ authz.get_accessible_experiments_for_dataset(request, dataset_id), 'display_images': display_images, }) return HttpResponse( render_response_index(request, 'hrmc_views/view_full_dataset.html', c))
def return_response_datafile_private(request, exp): c = Context({ 'exp_id': exp.id, 'exp_name': exp.title, 'owner_name': exp.created_by.get_full_name(), 'owner_email': exp.created_by.email }) return HttpResponseNotFound( render_response_index(request, 'hpctardis/contact_download.html', c))
def index(request): if request.method == 'GET': context = {'introduction': getattr( settings, 'PUBLICATION_INTRODUCTION', "<p><strong>... introduction and publication agreement " "...</strong></p>")} return HttpResponse(render_response_index( request, 'form.html', context=context)) return process_form(request)
def add_par_alt(request, parentObject, otype, stype): all_schema = Schema.objects.filter(type=stype) if 'schema_id' in request.GET: schema_id = request.GET['schema_id'] else: schema_id = all_schema[0].id schema = Schema.objects.get(id=schema_id) parameternames = ParameterName.objects.filter( schema__namespace=schema.namespace) success = False valid = True if request.method == 'POST': class DynamicForm( create_datafile_add_form_alt(schema.namespace, parentObject, request=request)): pass form = DynamicForm(request.POST) if form.is_valid(): save_datafile_add_form(schema.namespace, parentObject, request) success = True else: valid = False else: class DynamicForm( create_datafile_add_form_alt(schema.namespace, parentObject)): pass form = DynamicForm() c = Context({ 'schema': schema, 'form': form, 'parameternames': parameternames, 'type': otype, 'success': success, 'valid': valid, 'parentObject': parentObject, 'all_schema': all_schema, 'schema_id': schema.id, }) return HttpResponse( render_response_index(request, 'tardis_portal/ajax/parameteradd.html', c))
def view_full_dataset(request, dataset_id): """Displays a HRMC Dataset as a single scatter plot of x,y values from grfinalXX.dat and gerr.dat files Requires BDPMytardis with single Settings for this view: INSTALLED_APPS += ("tardis.apps.hrmc_views",) DATASET_VIEWS = [("http://rmit.edu.au/schemas/hrmcdataset", "tardis.apps.hrmc_views.views.view_full_dataset"),] """ logger.debug("got to hrmc views") dataset = Dataset.objects.get(id=dataset_id) # FIXME: as single image, can remove this def get_datafiles_page(): # pagination was removed by someone in the interface but not here. # need to fix. pgresults = 100 paginator = Paginator(dataset.dataset_file_set.all(), pgresults) try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 # If page request (9999) is out of range, deliver last page of results. try: return paginator.page(page) except (EmptyPage, InvalidPage): return paginator.page(paginator.num_pages) display_images = [] image_to_show = get_image_to_show(dataset) if image_to_show: display_images.append(image_to_show) c = Context({ 'dataset': dataset, 'datafiles': get_datafiles_page(), 'parametersets': dataset.getParameterSets() .exclude(schema__hidden=True), 'has_download_permissions': authz.has_dataset_download_access(request, dataset_id), 'has_write_permissions': authz.has_dataset_write(request, dataset_id), 'from_experiment': \ get_experiment_referer(request, dataset_id), 'other_experiments': \ authz.get_accessible_experiments_for_dataset(request, dataset_id), 'display_images': display_images, }) return HttpResponse(render_response_index( request, 'hrmc_views/view_full_dataset.html', c))
def index(request): if request.method == 'GET': context = {'introduction': getattr( settings, 'PUBLICATION_INTRODUCTION', "<p><strong>... introduction and publication agreement " "...</strong></p>")} return HttpResponse(render_response_index( request, 'form.html', context=context)) else: return process_form(request)
def view(request, dataset_file_id): df = Dataset_File.objects.get(id=dataset_file_id) context = Context({ 'filename': os.path.splitext(df.filename)[0], 'dataset_file_id': dataset_file_id, }) return HttpResponse(render_response_index( request, "jolecule/index.html", context))
def send_retry_response(request, form, status): '''Returns the form te be filled out again''' c = Context({ 'form': form, 'status': status, 'subtitle': 'Register Experiment', 'searchDatafileSelectionForm': getNewSearchDatafileSelectionForm()}) return HttpResponse(render_response_index(request, 'tardis_portal/register_experiment.html', c))
def retrieve_parameters(request, dataset_file_id): parametersets = DatafileParameterSet.objects.all() parametersets = parametersets.filter(dataset_file__pk=dataset_file_id) c = Context({'parametersets': parametersets}) return HttpResponse( render_response_index(request, 'tardis_portal/ajax/parameters.html', c))
def control_panel(request): experiments = Experiment.safe.owned(request.user) if experiments: experiments = experiments.order_by('title') c = {'experiments': experiments, 'subtitle': 'Experiment Control Panel'} return HttpResponse( render_response_index(request, 'tardis_portal/control_panel.html', c))
def change_user_permissions(request, experiment_id, username): try: user = User.objects.get(username=username) except User.DoesNotExist: return return_response_error(request) try: experiment = Experiment.objects.get(pk=experiment_id) except Experiment.DoesNotExist: return return_response_error(request) try: expt_acls = Experiment.safe.user_acls(experiment_id) acl = None for eacl in expt_acls: if eacl.pluginId == 'django_user' and \ eacl.get_related_object().id == user.id: acl = eacl #acl = expt_acls.filter(entityId=str(user.id)) if acl is None: raise ObjectACL.DoesNotExist owner_acls = [oacl for oacl in expt_acls if oacl.isOwner] except ObjectACL.DoesNotExist: return return_response_error(request) if request.method == 'POST': form = ChangeUserPermissionsForm(request.POST, instance=acl) if form.is_valid(): if 'isOwner' in form.changed_data and \ form.cleaned_data['isOwner'] is False and \ len(owner_acls) == 1: owner = owner_acls[0].get_related_object() plugin = owner_acls[0].pluginId if plugin == 'django_user' and owner.id == user.id: return render_error_message( request, 'Cannot remove ownership, every experiment must have at ' 'least one user owner.', status=409) form.save() url = reverse('tardis.tardis_portal.views.control_panel') return HttpResponseRedirect(url) else: form = ChangeUserPermissionsForm(instance=acl) c = { 'form': form, 'header': "Change User Permissions for '%s'" % user.username } return HttpResponse( render_response_index(request, 'tardis_portal/form_template.html', c))
def about(request): c = {'subtitle': 'About', 'about_pressed': True, 'nav': [{'name': 'About', 'link': '/about/'}], 'version': settings.MYTARDIS_VERSION, 'custom_about_section': getattr( settings, 'CUSTOM_ABOUT_SECTION_TEMPLATE', 'tardis_portal/about_include.html'), } return HttpResponse(render_response_index(request, 'tardis_portal/about.html', c))
def index(request, experiment_id): template = 'related_info/index.html' c = Context() if request.user.is_authenticated(): c['has_write_permissions'] = authz.has_write_permissions(request, experiment_id) rih = RelatedInfoHandler(experiment_id) c['related_info_list'] = rih.info_list() c['experiment_id'] = int(experiment_id) c['other_info'] = ExperimentParameter.objects.filter(name__schema__namespace=auxiliary_schema_namespace, parameterset__experiment=experiment_id) return HttpResponse(render_response_index(request, template, c))
def upload_button(request, dataset_id): ''' renders the filepicker button/widget via an ajax call ''' filepicker_api_key = filepicker_settings.filepicker_api_key c = { 'filepicker_api_key': filepicker_api_key, 'dataset_id': dataset_id, } return render_response_index(request, 'filepicker/filepicker.html', c)
def list_trips(request): ''' List trips for driving data ''' driving_admins = getattr(settings, 'DRIVING_ADMIN_GROUP', default_settings.DRIVING_ADMIN_GROUP) # Logged-in user needs to be a member of driving admin group # or they need to be a superuser to view this page: if not request.user.groups.filter(name=driving_admins).exists() and \ not request.user.is_superuser: return return_response_error(request) trips = [] driving_instrument_names = getattr(settings, 'DRIVING_INSTRUMENTS', default_settings.DRIVING_INSTRUMENTS) csv_dir_prefix = getattr(settings, 'DRIVING_CSV_DIR_PREFIX', default_settings.DRIVING_CSV_DIR_PREFIX) instruments = Instrument.objects.filter(name__in=driving_instrument_names) datasets = Dataset.objects.filter(instrument__in=instruments) for dataset in datasets: exp = dataset.experiments.first() study = exp.title exp_id = exp.id participant = dataset.description dfs = DataFile.objects.filter(dataset=dataset, directory__startswith=csv_dir_prefix, filename__endswith='.csv') for datafile in dfs: with datafile.file_object as fileobj: reader = csv.reader(fileobj) rows = list(reader) for row in rows: if len(row) < 7: continue try: trip_number = int(row[0]) except ValueError: continue trip = dict(exp_id=exp_id, dataset_id=dataset.id, study=study, participant=participant, number=trip_number, start=row[1], end=row[2], duration=row[3], distance=row[4]) trips.append(trip) context = dict(trips=trips) return render_response_index(request, 'trips.html', context)