def showCurveFile(request, user, file_id): try: cf = mmodels.CurveFile.objects.get(id=file_id, deleted=False) except ObjectDoesNotExist: raise VoltPyNotAllowed(user) if not cf.canBeReadBy(user): raise VoltPyNotAllowed(user) if (__debug__): print(cf) plotScr, plotDiv = generate_plot(request=request, user=user, plot_type='file', value_id=cf.id) context = { 'scripts': plotScr, 'mainPlot': plotDiv, 'user': user, 'curvefile_id': curvefile_id, 'form': form } return voltpy_render(request=request, template_name='manager/showFile.html', context=context)
def wrap(*args, **kwargs): user_id = kwargs.pop('user_id', None) try: user_id = int(user_id) except (TypeError, ValueError): raise VoltPyNotAllowed(None) try: user = mmodels.User.objects.get(id=user_id) except ObjectDoesNotExist: raise VoltPyNotAllowed(None) kwargs['user'] = user return fun(*args, **kwargs)
def process(self, user): # TODO: Perms to what are required (?) if not user.has_perm('rw', self.cs): raise VoltPyNotAllowed('Not allowed to change the dataset.') for cd in self.cs.curves_data.all(): name = self.cleaned_data.get('curve_%d_name' % cd.id, None) comment = self.cleaned_data.get('curve_%d_comment' % cd.id, None) if name is None or comment is None: raise VoltPyNotAllowed('Incomplete form, please try again.') cd.curve.name = name cd.curve.comment = comment cd.curve.save() return True
def generate_share_link(user: User, perm: str, obj: Generic) -> str: import random import string if obj.owner != user: raise VoltPyNotAllowed() try: old = manager.models.SharedLink.get(object_type=obj.__class__.__name__, object_id=obj.id, permissions=perm) return old.getLink() except: pass gen_string = ''.join([ random.choice(string.ascii_letters + string.digits) for _ in range(32) ]) while manager.models.SharedLink.objects.filter(link=gen_string).exists(): gen_string = ''.join([ random.choice(string.ascii_letters + string.digits) for _ in range(32) ]) sl = manager.models.SharedLink(object_type=obj.__class__.__name__, object_id=obj.id, permissions=perm, link=gen_string) sl.save() return sl.getLink()
def delete_generic(request, user, item): """ The generic function to which offers ability to delete model istance with user confirmation. """ if item == None: return HttpResponseRedirect(reverse('index', args=[user.id])) itemclass = str(item.__class__.__name__) if not item.canBeUpdatedBy(user): raise VoltPyNotAllowed(user) if request.method == 'POST': form = mforms.DeleteForm(item, request.POST) if form.is_valid(): a = form.process(user, item) if a: return HttpResponseRedirect( reverse('browse' + itemclass, args=[user.id])) else: form = mforms.DeleteForm(item) context = { 'scripts': mpm.PlotManager.required_scripts, 'form': form, 'item': item, 'user': user } return voltpy_render(request=request, template_name='manager/deleteGeneric.html', context=context)
def accept(self): if self.deleted: raise VoltPyNotAllowed() if not self.owner.profile.owned_groups.filter( id=self.group.id).exists(): raise VoltPyNotAllowed() if manager.helpers.functions.get_user() != self.invited_user: raise VoltPyNotAllowed() self.invited_user.groups.add(self.group) self.accepted = True gu = manager.helpers.functions.get_user manager.helpers.functions.get_user = lambda: self.owner try: self.save() finally: manager.helpers.functions.get_user = gu
def process(self, group): if group.id != int(self.cleaned_data['group_id']): raise VoltPyNotAllowed('Error in form') inv_user_disp = self.cleaned_data['username'] inv_user = User.objects.filter(username=inv_user_disp) is_member = False if not inv_user.exists(): inv_user = None else: inv_user = inv_user[0] is_member = inv_user.groups.filter(id=group.id).exists() alread_exists = mmodels.GroupInvitation.objects.filter( invited_user_disp=inv_user_disp, group=group, deleted=False, accepted=False, ).exists() if alread_exists or is_member: return False inv = mmodels.GroupInvitation( invited_user=inv_user, invited_user_disp=self.cleaned_data['username'], group=group, ) inv.save() return True
def delete(self): user = manager.helpers.functions.get_user() if user.has_perm('del', self): self.deleted = True super().save() else: raise VoltPyNotAllowed('Operation not allowed.')
def showAnalysis(request, user, analysis_id): try: an = mmodels.Analysis.objects.get(id=analysis_id) except ObjectDoesNotExist: an = None if not an.canBeReadBy(user): raise VoltPyNotAllowed(user) if an.completed == False: return HttpResponseRedirect(reverse('analyze', args=[user.id, an.id])) mm = mmm.MethodManager(user=user, analysis_id=analysis_id) info = mm.getInfo(request=request, user=user) plotScr, plotDiv = generate_plot(request=request, user=user, plot_type='curveset', value_id=an.curveSet.id) context = { 'scripts': plotScr, 'mainPlot': plotDiv, 'head': info.get('head', ''), 'user': user, 'analysis': an, 'text': info.get('body', '') } return voltpy_render(request=request, template_name='manager/showAnalysis.html', context=context)
def wrap(request, *args, **kwargs): try: user = request.user except (AttributeError, TypeError, ValueError, ObjectDoesNotExist) as e: print("Got user errro! ", repr(e)) raise VoltPyNotAllowed("General permission error.") kwargs['user'] = user with_user._user = user return fun(request, *args, **kwargs)
def save(self, *args, **kwargs): if self.id is None: if self.__current_samples_changed: self._current_samples.save() self.__current_samples_changed = False self.potential = np.array(self.potential) self.current = np.array(self.current) self.time = np.array(self.time) super().save(*args, **kwargs) else: raise VoltPyNotAllowed( "CurveData is read only model. Update CurveData via Dataset.updateCurve method." )
def save(self): user = manager.helpers.functions.get_user() if self.id is None: # it is new object in DB, so user is owner self.owner = user super().save() if user is not None: assign_perm('rw', user, self) assign_perm('del', user, self) return if user.has_perm('rw', self): super().save() else: raise VoltPyNotAllowed('Operation not allowed.')
def process(self, user): if not user.has_perm('rw', self.cs): raise VoltPyNotAllowed('Operation not allowed.') a = None if int(self.cleaned_data.get('existingAnalyte', -1)) == -1: analyteName = self.cleaned_data['newAnalyte'] try: a = mmodels.Analyte.objects.get(name=analyteName) except mmodels.Analyte.DoesNotExist: a = mmodels.Analyte(name=analyteName, owner=user) a.save() else: a = mmodels.Analyte.objects.get( id=self.cleaned_data['existingAnalyte']) units = self.cleaned_data['units'] conc = self.cs.analytes_conc.get(a.id, {}) for name, val in self.cleaned_data.items(): if "curve_" in name: curve_id = int(name[6:]) try: self.cs.curves_data.get(id=curve_id) except ObjectDoesNotExist: raise VoltPyDoesNotExists('Curve id %d does not exists.' % curve_id) conc[curve_id] = float(val) if not self.cs.analytes.filter(id=a.id).exists(): self.cs.analytes.add(a) if all([ manager.helpers.functions.is_number(self.original_id), a.id != self.original_id ]): self.cs.analytes_conc.pop(self.original_id, None) self.cs.analytes_conc_unit.pop(self.original_id, None) try: a_org = mmodels.Analyte.objects.get(id=self.original_id) self.cs.analytes.remove(a_org) except ObjectDoesNotExist: pass self.cs.analytes_conc[a.id] = conc self.cs.analytes_conc_unit[a.id] = units self.cs.analytes.add(a) self.cs.save() return True
def process(self, user, obj): for key, val in self.cleaned_data.items(): if not key.startswith('group_'): continue gr_id = int(key[6:]) group = Group.objects.filter(id=gr_id) if not group.exists(): raise VoltPyNotAllowed() group = group.all()[0] if group.name == 'registered_users': raise VoltPyNotAllowed() if not user.groups.filter(id=gr_id).exists(): raise VoltPyNotAllowed() if val == 'ns': remove_perm('ro', group, obj) remove_perm('rw', group, obj) elif val == 'ro': remove_perm('rw', group, obj) assign_perm('ro', group, obj) elif val == 'rw': remove_perm('ro', group, obj) assign_perm('rw', group, obj) else: raise VoltPyNotAllowed('Wrong permission')
def showCurveSet(request, user, curveset_id): try: cs = mmodels.CurveSet.objects.get(id=curveset_id) except ObjectDoesNotExist: raise VoltPyDoesNotExists() if not cs.canBeReadBy(user): raise VoltPyNotAllowed(user) plotScr, plotDiv = generate_plot(request=request, user=user, plot_type='curveset', value_id=cs.id) context = { 'scripts': plotScr, 'mainPlot': plotDiv, 'user': user, 'curveset_id': curveset_id, } return voltpy_render(request=request, template_name='manager/showCurveSet.html', context=context)
def check_permission(sender, instance, **kwargs): if not isinstance(instance, VoltPyModel): return user = manager.helpers.functions.get_user() if not user.has_perm('rw', instance): raise VoltPyNotAllowed('Operation not allowed.')
def save(self, *args, **kwargs): user = manager.helpers.functions.get_user() if not user.has_perm('rw', self.dataset): raise VoltPyNotAllowed('Operation not allowed.') super().save(*args, **kwargs)
def __init__(self, user, *args, **kwargs): self.toCloneCS = kwargs.pop('toCloneCS', []) self.toCloneCF = kwargs.pop('toCloneCF', []) if len(self.toCloneCF) > 0 and len(self.toCloneCS) > 0: raise VoltPyNotAllowed('Can only clone one type of data.') newName = '' try: if len(self.toCloneCS) == 1: csToClone = mmodels.Dataset.get(id=self.toCloneCS[0]) newName = csToClone.name + '_copy' if len(self.toCloneCF) == 1: csToClone = mmodels.File.get(id=self.toCloneCF[0]) newName = csToClone.name + '_copy' except: newName = '' # self.toClone = -1 super(SelectCurvesForDatasetForm, self).__init__(*args, **kwargs) from django.db.models import Prefetch self.fields['name'] = forms.CharField(max_length=124, required=True, initial=newName) self.fields['name'].maintype = 'name' self.fields['name'].mainid = 0 files = mmodels.File.all() csInFiles = [] for f in files: fname = 'File_{0}'.format(f.id) initial = False if f.id in self.toCloneCF: initial = True self.fields[fname] = forms.BooleanField(label=f, required=False, initial=initial) self.fields[fname].widget.attrs['class'] = 'parent' self.fields[fname].maintype = 'file' self.fields[fname].cptype = 'parent' csInFiles.append(f.id) for cd in f.curves_data.all().only("id", "curve").prefetch_related( Prefetch('curve', queryset=mmodels.Curve.objects.only('id', 'name'))): cname = "File_{1}_curveData_{0}".format(cd.id, f.id) self.fields[cname] = forms.BooleanField(label=cd.curve, required=False) self.fields[cname].widget.attrs['class'] = 'child' self.fields[cname].maintype = 'file' self.fields[cname].cptype = 'child' css = mmodels.Dataset.all().only("id", "name") for cs in css: if cs.id in csInFiles: continue csname = 'dataset_{0}'.format(cs.id) initial = False if cs.id in self.toCloneCS: initial = True self.fields[csname] = forms.BooleanField(label=cs, required=False, initial=initial) self.fields[csname].maintype = 'dataset' self.fields[csname].widget.attrs['class'] = 'parent' self.fields[csname].cptype = 'parent' for cd in cs.curves_data.only("id", "curve").prefetch_related( Prefetch('curve', queryset=mmodels.Curve.objects.only('id', 'name'))): cname = "dataset_{1}_curveData_{0}".format(cd.id, cs.id) self.fields[cname] = forms.BooleanField(label=cd.curve, required=False) self.fields[cname].widget.attrs['class'] = 'child' self.fields[cname].maintype = 'dataset' self.fields[cname].cptype = 'child'
def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) if user is None: raise VoltPyNotAllowed('Operation not allowed') super(SettingsForm, self).__init__(*args, **kwargs)
def editCurveSet(request, user, curveset_id): try: cs = mmodels.CurveSet.objects.get(id=curveset_id) except ObjectDoesNotExist: raise VoltPyDoesNotExists('Cannot be accessed.') if not cs.canBeUpdatedBy(user): raise VoltPyNotAllowed(user) txt = '' if (cs.locked): txt = "This curveset is used by analysis method and cannot be modified." mm = mmm.MethodManager(user=user, curveset_id=curveset_id) if request.method == 'POST': if ('startAnalyze' in request.POST): formGenerate = mm.getAnalysisSelectionForm(request.POST) if (formGenerate.is_valid()): analyzeid = formGenerate.process(user, cs) return HttpResponseRedirect( reverse('analyze', args=[user.id, analyzeid])) else: formGenerate = mm.getAnalysisSelectionForm() if (not cs.locked and 'startProcessing' in request.POST): formProc = mm.getProcessingSelectionForm(request.POST) if (formProc.is_valid()): procid = formProc.process(user, cs) return HttpResponseRedirect( reverse('process', args=[user.id, procid])) else: formProc = mm.getProcessingSelectionForm(disabled=cs.locked) if ('submitFormAnalyte' in request.POST): formAnalyte = mforms.AddAnalytesForm(user, "CurveSet", curveset_id, request.POST) if formAnalyte.is_valid(): if (formAnalyte.process(user) == True): return HttpResponseRedirect( reverse('showCurveSet', args=[user.id, curveset_id])) else: formAnalyte = mforms.AddAnalytesForm(user, "CurveSet", curveset_id) else: formAnalyte = mforms.AddAnalytesForm(user, "CurveSet", curveset_id) formGenerate = mm.getAnalysisSelectionForm() formProc = mm.getProcessingSelectionForm(disabled=cs.locked) try: cs = mmodels.CurveSet.objects.get(id=curveset_id) if not cs.canBeReadBy(user): raise VoltPyNotAllowed(user) except ObjectDoesNotExist: raise VoltPyNotAllowed(user) cal_disp = "" plotScr, plotDiv = generate_plot(request=request, user=user, plot_type='curveset', value_id=cs.id) context = { 'scripts': plotScr + formProc.getJS(request) + formGenerate.getJS(request), 'mainPlot': plotDiv, 'formAnalyte': formAnalyte, 'startAnalyze': formGenerate, 'startProcessing': formProc, 'user': user, 'curveset_id': curveset_id, 'cal_disp': cal_disp } return voltpy_render(request=request, template_name='manager/editCurveSet.html', context=context)
def apply(self, user, dataset): if self.model.completed is not True: raise VoltPyNotAllowed('Incomplete procedure.') self.__perform(dataset)
def generate_plot(request: HttpRequest, user: User, to_plot: Optional[str] = None, plot_type: Optional[str] = None, value_id: Optional[int] = None, **kwargs) -> List: assert (to_plot is not None and plot_type is None) or (to_plot is None and plot_type is not None) if to_plot is not None: if isinstance(to_plot, mmodels.File): plot_type = 'file' elif isinstance(to_plot, mmodels.Dataset): plot_type = 'dataset' elif isinstance(to_plot, mmodels.Fileset): plot_type = 'fileset' elif isinstance(to_plot, mmodels.Analysis): plot_type = 'analysis' else: raise VoltPyFailed('Could not plot') allowedTypes = [ 'file', 'analysis', 'dataset', 'fileset', ] if plot_type not in allowedTypes: raise VoltPyNotAllowed('Operation not allowed.') vtype = kwargs.get('vtype', plot_type) vid = kwargs.get('vid', value_id) addTo = kwargs.get('add', None) pm = mpm.PlotManager() data = [] if plot_type == 'file': if to_plot is None: cf = mmodels.File.get(id=value_id) else: cf = to_plot data = pm.datasetHelper(user, cf) pm.xlabel = pm.xLabelHelper(user) pm.include_x_switch = True elif plot_type == 'dataset': if to_plot is None: cs = mmodels.Dataset.get(id=value_id) else: cs = to_plot data = pm.datasetHelper(user, cs) pm.xlabel = pm.xLabelHelper(user) pm.include_x_switch = True elif plot_type == 'analysis': if to_plot is None: data = pm.analysisHelper(user, value_id) else: data = to_plot pm.xlabel = pm.xLabelHelper(user) pm.include_x_switch = False elif plot_type == 'fileset': if to_plot is None: fs = mmodels.Fileset.get(id=value_id) else: fs = to_plot data = [] for f in fs.files.all(): data.extend(pm.datasetHelper(user, f)) pm.xlabel = pm.xLabelHelper(user) pm.include_x_switch = True pm.ylabel = 'i / µA' pm.setInteraction(kwargs.get('interactionName', 'none')) for d in data: pm.add(**d) if addTo: for a in addTo: pm.add(**a) return pm.getEmbeded(request, user, vtype, vid)