def mutate(cls, root, info, **input): _piano = Piano.objects.get(codice=input['codice_piano']) _procedura_vas = ProceduraVAS.objects.get(piano=_piano) if info.context.user and rules.test_rule( 'strt_core.api.can_edit_piano', info.context.user, _piano): try: _next_fase = cls.get_next_phase(_piano.fase) if rules.test_rule( 'strt_core.api.fase_{next}_completa'.format( next=_next_fase), _piano, _procedura_vas): _piano.fase = _fase = Fase.objects.get(nome=_next_fase) piano_phase_changed.send(sender=Piano, user=info.context.user, piano=_piano) _piano.save() cls.update_actions_for_phase(_fase, _piano, _procedura_vas) return PromozionePiano(piano_aggiornato=_piano, errors=[]) else: return GraphQLError(_("Not Allowed"), code=405) except BaseException as e: tb = traceback.format_exc() logger.error(tb) return GraphQLError(e, code=500) else: return GraphQLError(_("Forbidden"), code=403)
def mutate(cls, root, info, **input): if info.context.user and rules.test_rule( 'strt_core.api.can_access_private_area', info.context.user): # Fetching input arguments _id = input['risorsa_id'] _uuid_cc = input['codice'] # TODO: Andrebbe controllato se la risorsa in funzione del tipo e della fase del piano è eliminabile o meno try: _conferenza_copianificazione = ConferenzaCopianificazione.objects.get( uuid=_uuid_cc) if rules.test_rule('strt_core.api.can_edit_piano', info.context.user, _conferenza_copianificazione.piano): _risorsa = Risorsa.objects.get(uuid=_id) _success = DeleteRisorsaBase.handle_downloaded_data( _risorsa) return DeleteRisorsaCopianificazione( conferenza_copianificazione_aggiornata= _conferenza_copianificazione, success=_success) else: return GraphQLError(_("Forbidden"), code=403) except BaseException as e: tb = traceback.format_exc() logger.error(tb) return GraphQLError(e, code=500) # Something went wrong return GraphQLError(_("Not Allowed"), code=405)
def mutate_and_get_payload(cls, root, info, **input): _piano = Piano.objects.get(codice=input['codice_piano']) _procedura_vas = ProceduraVAS.objects.get(piano=_piano) _token = info.context.session[ 'token'] if 'token' in info.context.session else None _organization = _piano.ente if info.context.user and \ rules.test_rule('strt_core.api.can_edit_piano', info.context.user, _piano) and \ (rules.test_rule('strt_core.api.is_actor', _token or (info.context.user, _organization), 'Comune') or rules.test_rule('strt_core.api.is_actor', _token or (info.context.user, _organization), 'AC')): try: nuova_consultazione_vas = ConsultazioneVAS() nuova_consultazione_vas.user = info.context.user nuova_consultazione_vas.procedura_vas = _procedura_vas _consultazioni_vas_expire_days = getattr( settings, 'CONSULTAZIONI_SCA_EXPIRE_DAYS', 90) nuova_consultazione_vas.data_scadenza = datetime.datetime.now(timezone.get_current_timezone()) + \ datetime.timedelta(days=_consultazioni_vas_expire_days) nuova_consultazione_vas.save() return cls(nuova_consultazione_vas=nuova_consultazione_vas) except BaseException as e: tb = traceback.format_exc() logger.error(tb) return GraphQLError(e, code=500) else: return GraphQLError(_("Forbidden"), code=403)
def mutate(cls, root, info, **input): _procedura_vas = ProceduraVAS.objects.get(uuid=input['uuid']) _piano = _procedura_vas.piano _token = info.context.session['token'] if 'token' in info.context.session else None _organization = _piano.ente if info.context.user and \ rules.test_rule('strt_core.api.can_edit_piano', info.context.user, _piano) and \ rules.test_rule('strt_core.api.is_actor', _token or (info.context.user, _organization), 'Comune'): try: cls.update_actions_for_phase(_piano.fase, _piano, _procedura_vas) if _piano.is_eligible_for_promotion: _piano.fase = _fase = Fase.objects.get(nome=_piano.next_phase) # Notify Users piano_phase_changed.send( sender=Piano, user=info.context.user, piano=_piano, message_type="piano_phase_changed") _piano.save() fase.promuovi_piano(_fase, _piano) return UploadElaboratiVAS( vas_aggiornata=_procedura_vas, errors=[] ) except BaseException as e: tb = traceback.format_exc() logger.error(tb) return GraphQLError(e, code=500) else: return GraphQLError(_("Forbidden"), code=403)
def mutate(cls, root, info, **input): _procedura_vas = ProceduraVAS.objects.get(uuid=input['uuid']) _piano = _procedura_vas.piano _token = info.context.session['token'] if 'token' in info.context.session else None _organization = _piano.ente if info.context.user and \ rules.test_rule('strt_core.api.can_edit_piano', info.context.user, _piano) and \ rules.test_rule('strt_core.api.is_actor', _token or (info.context.user, _organization), 'AC'): try: _pareri_verifica_sca = _piano.azioni.filter( tipologia=TIPOLOGIA_AZIONE.pareri_verifica_sca).first() if _pareri_verifica_sca and _pareri_verifica_sca.stato != STATO_AZIONE.nessuna: return GraphQLError(_("Forbidden"), code=403) if not _procedura_vas.verifica_effettuata and \ _procedura_vas.tipologia in (TIPOLOGIA_VAS.verifica, TIPOLOGIA_VAS.semplificata): cls.update_actions_for_phase(_piano.fase, _piano, _procedura_vas) else: return GraphQLError(_("Forbidden"), code=403) return AssoggettamentoVAS( vas_aggiornata=_procedura_vas, errors=[] ) except BaseException as e: tb = traceback.format_exc() logger.error(tb) return GraphQLError(e, code=500) else: return GraphQLError(_("Forbidden"), code=403)
def __init__(self, user, *args, **kwargs): super(CitationForm, self).__init__( *args, **kwargs) self.user = user if not self.is_bound: if not self.fields['record_status_value'].initial: self.fields['record_status_value'].initial = CuratedMixin.ACTIVE # disable fields user doesn't have access to if self.instance.pk: # Don't let the user change type_controlled. #self.fields['type_controlled'].widget.attrs['readonly'] = True #self.fields['type_controlled'].widget.attrs['disabled'] = True self.fields['title'].widget.attrs['placeholder'] = "No title" self.fields['type_controlled'].widget = forms.widgets.HiddenInput() if self.instance.type_controlled in [Citation.REVIEW, Citation.CHAPTER, Citation.ARTICLE, Citation.ESSAY_REVIEW]: self.fields['physical_details'].widget = forms.widgets.HiddenInput() self.fields['book_series'].widget = forms.widgets.HiddenInput() if self.instance.type_controlled in [Citation.THESIS]: self.fields['book_series'].widget = forms.widgets.HiddenInput() for field in self.fields: can_update = rules.test_rule('can_update_citation_field', user, (field, self.instance.pk)) if not can_update: self.fields[field].widget.attrs['readonly'] = True self.fields[field].widget.attrs['disabled'] = True can_view = rules.test_rule('can_view_citation_field', user, (field, self.instance.pk)) if not can_view: self.fields[field] = forms.CharField(widget=NoViewInput()) self.fields[field].widget.attrs['readonly'] = True self.fields[field].widget.attrs['disabled'] = True
def mutate(cls, root, info, file, **input): if info.context.user and rules.test_rule( 'strt_core.api.can_access_private_area', info.context.user): # Fetching input arguments _uuid_avvio = input['codice'] _tipo_file = input['tipo_file'] try: # Validating 'Procedura VAS' _procedura_avvio = ProceduraAvvio.objects.get(uuid=_uuid_avvio) if rules.test_rule('strt_core.api.can_edit_piano', info.context.user, _procedura_avvio.piano): _resources = UploadBaseBase.handle_uploaded_data( file, _uuid_avvio, _procedura_avvio.piano.fase, _tipo_file, info.context.user) _success = False if _resources and len(_resources) > 0: _success = True for _risorsa in _resources: RisorseAvvio(procedura_avvio=_procedura_avvio, risorsa=_risorsa).save() return UploadRisorsaAvvio( procedura_avvio_aggiornata=_procedura_avvio, success=_success, file_name=_resources[0].nome) else: return GraphQLError(_("Forbidden"), code=403) except BaseException as e: tb = traceback.format_exc() logger.error(tb) return GraphQLError(e, code=500) # Something went wrong return GraphQLError(_("Not Allowed"), code=405)
def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(PatientTransferForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal hn-form admittance' self.helper.form_method = 'POST' self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-8' self.helper.layout = Layout( Fieldset('Patient Transfer Form', 'doctor', 'hospital', 'reason' ), FormActions( Submit('submit', 'Submit'), HTML( '<a class="btn btn-default" href={% if next_url %}{{ next_url }}{% else %}' '{% url "registry:home" %}{% endif %}>Cancel</a>' ) ) ) # Filter the fields for doctor and hospital based on the user requesting transfer # A doctor will see his name and the hospital he works at # An admin will see his hospital and the doctors that work there if rules.test_rule('is_doctor', user): self.fields['doctor'].queryset = Doctor.objects.filter(uuid=user.uuid) self.fields['hospital'].queryset = user.hospitals.all() elif rules.test_rule('is_administrator', user): self.fields['doctor'].queryset = Doctor.objects.filter(hospitals__name__exact=user.hospital.name) self.fields['hospital'].queryset = Hospital.objects.filter(name=user.hospital.name)
def mutate_and_get_payload(cls, root, info, **input): _piano = Piano.objects.get(codice=input['codice_piano']) _procedura_vas_data = input.get('procedura_vas') if info.context.user and \ rules.test_rule('strt_core.api.can_edit_piano', info.context.user, _piano) and \ rules.test_rule('strt_core.api.can_update_piano', info.context.user, _piano): try: # ProceduraVAS (M) _procedura_vas_data['piano'] = _piano # Ente (M) _procedura_vas_data['ente'] = _piano.ente # Note (O) if 'note' in _procedura_vas_data: _data = _procedura_vas_data.pop('note') _procedura_vas_data['note'] = _data[0] _procedura_vas = ProceduraVAS() _procedura_vas.piano = _piano _procedura_vas_data['id'] = _procedura_vas.id _procedura_vas_data['uuid'] = _procedura_vas.uuid nuova_procedura_vas = update_create_instance( _procedura_vas, _procedura_vas_data) return cls(nuova_procedura_vas=nuova_procedura_vas) except BaseException as e: tb = traceback.format_exc() logger.error(tb) return GraphQLError(e, code=500) else: return GraphQLError(_("Forbidden"), code=403)
def mutate(cls, root, info, **input): _procedura_adozione = ProceduraAdozione.objects.get(uuid=input['uuid']) _piano = _procedura_adozione.piano _token = info.context.session[ 'token'] if 'token' in info.context.session else None _organization = _piano.ente if info.context.user and rules.test_rule('strt_core.api.can_edit_piano', info.context.user, _piano) and \ rules.test_rule('strt_core.api.is_actor', _token or (info.context.user, _organization), 'Regione'): try: cls.update_actions_for_phase(_piano.fase, _piano, _procedura_adozione, info.context.user, _token) # Notify Users piano_phase_changed.send( sender=Piano, user=info.context.user, piano=_piano, message_type="esito_conferenza_paesaggistica") return EsitoConferenzaPaesaggistica( adozione_aggiornata=_procedura_adozione, errors=[]) except BaseException as e: tb = traceback.format_exc() logger.error(tb) return GraphQLError(e, code=500) else: return GraphQLError(_("Forbidden"), code=403)
def mutate_and_get_payload(cls, root, info, **input): _piano = Piano.objects.get(codice=input['codice_piano']) _procedura_adozione_data = input.get('procedura_adozione') if info.context.user and \ rules.test_rule('strt_core.api.can_edit_piano', info.context.user, _piano) and \ rules.test_rule('strt_core.api.can_update_piano', info.context.user, _piano): try: # ProceduraAdozione (M) _procedura_adozione_data['piano'] = _piano # Ente (M) _procedura_adozione_data['ente'] = _piano.ente _procedura_adozione = ProceduraAdozione() _procedura_adozione.piano = _piano _procedura_adozione.ente = _piano.ente _procedura_adozione_data['id'] = _procedura_adozione.id _procedura_adozione_data['uuid'] = _procedura_adozione.uuid nuova_procedura_adozione = update_create_instance( _procedura_adozione, _procedura_adozione_data) _piano.procedura_adozione = nuova_procedura_adozione _piano.save() return cls(nuova_procedura_adozione=nuova_procedura_adozione) except BaseException as e: tb = traceback.format_exc() logger.error(tb) return GraphQLError(e, code=500) else: return GraphQLError(_("Forbidden"), code=403)
def mutate(cls, root, info, **input): _procedura_avvio = ProceduraAvvio.objects.get(uuid=input['uuid']) _piano = _procedura_avvio.piano _token = info.context.session[ 'token'] if 'token' in info.context.session else None _organization = _piano.ente if info.context.user and rules.test_rule('strt_core.api.can_edit_piano', info.context.user, _piano) and \ rules.test_rule('strt_core.api.is_actor', _token or (info.context.user, _organization), 'Comune'): try: cls.update_actions_for_phase(_piano.fase, _piano, _procedura_avvio, info.context.user) # Notify Users """ TODO """ # piano_phase_changed.send( # sender=Piano, # user=info.context.user, # piano=_piano, # message_type="piano_phase_changed") return IntegrazioniRichieste(avvio_aggiornato=_procedura_avvio, errors=[]) except BaseException as e: tb = traceback.format_exc() logger.error(tb) return GraphQLError(e, code=500) else: return GraphQLError(_("Forbidden"), code=403)
def test_rule_can_read_datasource_pubic(self): d = DataSource.objects.get(name='PublicD1') owner = User.objects.get(email='*****@*****.**') other = User.objects.get(email='*****@*****.**') admin = User.objects.get(email='*****@*****.**') self.assertTrue(rules.test_rule('can_read_datasource', owner, d)) self.assertTrue(rules.test_rule('can_read_datasource', other, d)) self.assertTrue(rules.test_rule('can_read_datasource', admin, d))
def update_actions_for_phase(cls, fase, piano, procedura_adozione, user, token): # Update Azioni Piano # - Complete Current Actions _order = piano.azioni.count() # - Update Action state accordingly if fase.nome == FASE.avvio: _osservazioni_enti = piano.azioni.filter( tipologia=TIPOLOGIA_AZIONE.osservazioni_enti).first() _osservazioni_regione = piano.azioni.filter( tipologia=TIPOLOGIA_AZIONE.osservazioni_regione).first() _upload_osservazioni_privati = piano.azioni.filter( tipologia=TIPOLOGIA_AZIONE.upload_osservazioni_privati).first( ) _organization = piano.ente if rules.test_rule('strt_core.api.is_actor', token or (user, _organization), 'Regione'): if _osservazioni_regione and _osservazioni_regione.stato != STATO_AZIONE.nessuna: _osservazioni_regione.stato = STATO_AZIONE.nessuna _osservazioni_regione.data = datetime.datetime.now( timezone.get_current_timezone()) _osservazioni_regione.save() if _osservazioni_enti and _osservazioni_enti.stato != STATO_AZIONE.nessuna: _osservazioni_enti.stato = STATO_AZIONE.nessuna _osservazioni_enti.data = datetime.datetime.now( timezone.get_current_timezone()) _osservazioni_enti.save() if rules.test_rule('strt_core.api.is_actor', token or (user, _organization), 'Comune'): if _upload_osservazioni_privati and _upload_osservazioni_privati.stato != STATO_AZIONE.nessuna: _upload_osservazioni_privati.stato = STATO_AZIONE.nessuna _upload_osservazioni_privati.data = datetime.datetime.now( timezone.get_current_timezone()) _upload_osservazioni_privati.save() if _upload_osservazioni_privati.stato == STATO_AZIONE.nessuna and \ _osservazioni_regione.stato == STATO_AZIONE.nessuna: _controdeduzioni = Azione( tipologia=TIPOLOGIA_AZIONE.controdeduzioni, attore=TIPOLOGIA_ATTORE.comune, order=_order, stato=STATO_AZIONE.attesa) _controdeduzioni.save() _order += 1 AzioniPiano.objects.get_or_create(azione=_controdeduzioni, piano=piano) else: raise Exception( _("Fase Piano incongruente con l'azione richiesta"))
def __init__(self, user, authority_id, *args, **kwargs): super(PersonForm, self).__init__( *args, **kwargs) self.user = user self.authority_id = authority_id if authority_id: can_update = rules.test_rule('can_update_authority_field', user, ('person', authority_id)) can_view = rules.test_rule('can_view_authority_field', user, ('person', authority_id)) set_field_access(can_update, can_view, self.fields)
def mutate(cls, root, info, **input): _procedura_vas = ProceduraVAS.objects.get(uuid=input['uuid']) _piano = _procedura_vas.piano _token = info.context.session['token'] if 'token' in info.context.session else None _organization = _piano.ente if info.context.user and \ rules.test_rule('strt_core.api.can_edit_piano', info.context.user, _piano) and \ rules.test_rule('strt_core.api.is_actor', _token or (info.context.user, _organization), 'SCA'): try: _pareri_vas_count = ParereVerificaVAS.objects.filter( user=info.context.user, procedura_vas=_procedura_vas ) if _pareri_vas_count.count() == 0: _parere_vas = ParereVerificaVAS( inviata=True, user=info.context.user, procedura_vas=_procedura_vas ) _parere_vas.save() elif _pareri_vas_count.count() != 1: return GraphQLError(_("Forbidden"), code=403) _tutti_pareri_inviati = True for _sca in _piano.soggetti_sca.all(): _pareri_vas_count = ParereVerificaVAS.objects.filter( user=_sca.user, procedura_vas=_procedura_vas ).count() if _pareri_vas_count != 1: _tutti_pareri_inviati = False break if _tutti_pareri_inviati: # Notify Users piano_phase_changed.send( sender=Piano, user=info.context.user, piano=_piano, message_type="tutti_pareri_inviati") cls.update_actions_for_phase(_piano.fase, _piano, _procedura_vas) return InvioPareriVerificaVAS( vas_aggiornata=_procedura_vas, errors=[] ) except BaseException as e: tb = traceback.format_exc() logger.error(tb) return GraphQLError(e, code=500) else: return GraphQLError(_("Forbidden"), code=403)
def _get_validation_exclusions(self): exclude = super(CitationForm, self)._get_validation_exclusions() # remove fields that user isn't allowed to modify if self.instance.pk: for field in self.fields: can_update = rules.test_rule('can_update_citation_field', self.user, (field, self.instance.pk)) can_view = rules.test_rule('can_view_citation_field', self.user, (field, self.instance.pk)) if not can_update or not can_view: exclude.append(field) return exclude
def check_rule(rule, fn: callable = None, **kwargs): """ Return a middleware that validates if the current user respects the given rule. """ import rules if fn is None: test = (lambda r: rules.test_rule(rule, r.user)) else: test = (lambda r: rules.test_rule(rule, r.user, fn(r))) return access_control(test, **kwargs)
def test_default_permission(self): self.assertTrue( rules.test_rule('exportdb.can_export', self.super_user) ) self.assertFalse( rules.test_rule('exportdb.can_export', self.normal_user) ) self.assertFalse( rules.test_rule('exportdb.can_export', self.staff_user) )
def _get_validation_exclusions(self): exclude = super(PersonForm, self)._get_validation_exclusions() if self.authority_id: # remove fields that user isn't allowed to modify can_update = rules.test_rule('can_update_authority_field', self.user, ('person', self.authority_id)) can_view = rules.test_rule('can_view_authority_field', self.user, ('person', self.authority_id)) for field in self.fields: if not can_update or not can_view: exclude.append(field) return exclude
def test_rule_can_read_datasource_internal(self): d = DataSource.objects.get(name='InternalD1') owner = User.objects.get(email='*****@*****.**') other = User.objects.get(email='*****@*****.**') admin = User.objects.get(email='*****@*****.**') suser = User.objects.get(email='*****@*****.**') guser = User.objects.get(email='*****@*****.**') self.assertTrue(rules.test_rule('can_read_datasource', owner, d)) self.assertTrue(rules.test_rule('can_read_datasource', admin, d)) self.assertFalse(rules.test_rule('can_read_datasource', other, d)) self.assertTrue(rules.test_rule('can_read_datasource', suser, d)) self.assertTrue(rules.test_rule('can_read_datasource', guser, d))
def _get_validation_exclusions(self): exclude = super(PartDetailsForm, self)._get_validation_exclusions() # remove fields that user isn't allowed to modify if self.citation_id: can_update = rules.test_rule('can_update_citation_field', self.user, ('part_details', self.citation_id)) can_view = rules.test_rule('can_view_citation_field', self.user, ('part_details', self.citation_id)) for field in self.fields: if not can_update or not can_view: exclude.append(field) return exclude
def is_valid(self, boby): valid = super(UploadUsersForm, self).is_valid() if not valid: return False if not rules.test_rule('can_upload_users', boby): raise PermissionDenied return True
def mutate(cls, root, info, file, **input): if rules.test_rule('strt_core.api.can_access_private_area', info.context.user): # Fetching input arguments _uuid_vas = input['codice'] _tipo_file = input['tipo_file'] try: # Validating 'Procedura VAS' _procedura_vas = ProceduraVAS.objects.get(uuid=_uuid_vas) _resources = UploadBaseBase.handle_uploaded_data( file, _uuid_vas, _procedura_vas.piano.fase, _tipo_file ) _success = False if _resources and len(_resources) > 0: _success = True for _risorsa in _resources: RisorseVas(procedura_vas=_procedura_vas, risorsa=_risorsa).save() return UploadRisorsaVAS(procedura_vas_aggiornata=_procedura_vas, success=_success) except BaseException as e: tb = traceback.format_exc() logger.error(tb) return GraphQLError(e, code=500) # Something went wrong return GraphQLError(_("Not Allowed"), code=405)
def process_view(self, request, view_func, view_args, view_kwargs): request.is_appadmin = False # the admin has to use localcosmos_server.urls to not conflict with the commercial installation # online_content needs the correct urlconf if '/app-admin/' in request.path: request.is_appadmin = True if 'app_uid' not in view_kwargs: raise ImproperlyConfigured( 'all app-admin urls require app_uid as an url kwarg') app = App.objects.get(uid=view_kwargs['app_uid']) request.app = app login_path = reverse('log_in') if login_path not in request.path: user = request.user if not user.is_authenticated: url = '{0}?next={1}'.format(reverse('log_in'), request.path) return redirect(url) has_access = rules.test_rule('app_admin.has_access', user, app) if not has_access: raise PermissionDenied request.urlconf = 'localcosmos_server.urls' set_urlconf('localcosmos_server.urls') return None
def get(self, request, *args, **kwargs): """Check that the object to be edited belongs to user that created it""" self.object = self.get_object() if rules.test_rule('edit_author', self.request.user, self.object): return self.render_to_response(self.get_context_data()) messages.error(self.request, CONTEXT_MESSAGES['OPERATION_FAILED']) return redirect(self.get_success_url())
def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(AppointmentSchedulingForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal hn-form appointment' self.helper.form_method = 'POST' self.helper.form_action = reverse_lazy('registry:appt_create') self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-8' self.helper.layout = Layout( Fieldset('Appointment Scheduling', Div( Div('time', css_class='col-lg-3'), css_class='row', ), 'doctor', 'patient', 'location', ), FormActions( Submit('submit', 'Submit'), HTML( '<a class="btn btn-default" href={% if next_url %}{{ next_url }}{% else %}' '{% url "registry:home" %}{% endif %}>Cancel</a>') ) ) if rules.test_rule('is_patient', user): self.fields['patient'].queryset = Patient.objects.filter(uuid=user.uuid) # elif rules.test_rule('is_doctor', user): # self.fields['patient'].queryset = Patient.objects.filter(provider=user) # elif rules.test_rule('is_nurse', user): # self.fields['patient'].queryset = Patient.objects.filter(pref_hospital=user.hospital) self.fields['time'].widget.attrs['timepicker'] = True
def post(self, request, *args, **kwargs): self.object = self.get_object() community = self.object try: user_subscription = CommunitySubscription.objects.get( user=request.user, community=community) except CommunitySubscription.DoesNotExist: messages.warning( request, 'You cannot unsubscribe when you are not subscribed') return redirect(community) if not rules.test_rule('can_unsubscribe', request.user, user_subscription): messages.error( request, 'You cannot unsubscribe when you are the last owner') return redirect(community) EventRSVP.objects.filter(event__pk__in=Event.objects.upcoming().filter( community=community).values_list('pk', flat=True), user=request.user).delete() user_subscription.delete() messages.success( request, 'Successfully unsubscribed from "{}"'.format(community.name)) return redirect(community)
def mutate(cls, root, info, **input): _piano = Piano.objects.get(codice=input['codice_piano']) if info.context.user and rules.test_rule( 'strt_core.api.can_edit_piano', info.context.user, _piano): try: if _piano.is_eligible_for_promotion: _piano.fase = _fase = Fase.objects.get( nome=_piano.next_phase) # Notify Users piano_phase_changed.send( sender=Piano, user=info.context.user, piano=_piano, message_type="piano_phase_changed") _piano.save() fase.promuovi_piano(_fase, _piano) return PromozionePiano(piano_aggiornato=_piano, errors=[]) else: return GraphQLError(_("Not Allowed"), code=405) except BaseException as e: tb = traceback.format_exc() logger.error(tb) return GraphQLError(e, code=500) else: return GraphQLError(_("Forbidden"), code=403)
def dispatch(self, request, *args, **kwargs): has_access = rules.test_rule('app.is_admin', request.user, request.app) if not has_access: raise PermissionDenied return super().dispatch(request, *args, **kwargs)
def init_with_context(self, context): self.available_children.append(modules.LinkList) # Initiatives self.children.append(RecentInitiatives()) self.children.append(MyReviewingInitiatives()) # Activities self.children.append(RecentActivities()) self.children.append(RecentEvents()) self.children.append(RecentFunding()) self.children.append(RecentAssignments()) # Payouts self.children.append(PayoutsReadForApprovalDashboardModule()) # Other self.children.append( modules.RecentActions(_('Recent Actions'), 10, column=0, order=0)) self.children.append(RecentMembersDashboard()) if rules.test_rule('exportdb.can_export', context['request'].user): metrics_children = [ { 'title': _('Export metrics'), 'url': reverse_lazy('exportdb_export'), }, ] self.children.append( LinkList(_('Export Metrics'), children=metrics_children))
def qs(self): # The query context can be found in self.request. _enti = [] _memberships = None if rules.test_rule('strt_core.api.can_access_private_area', self.request.user): _memberships = self.request.user.memberships if _memberships: for _m in _memberships.all(): if _m.type.code == settings.RESPONSABILE_ISIDE_CODE: # RESPONSABILE_ISIDE_CODE cannot access to Piani at all continue else: _enti.append(_m.organization.code) token = self.request.session.get('token', None) if token: _allowed_pianos = [ _pt.piano.codice for _pt in PianoAuthTokens.objects.filter(token__key=token) ] return super(PianoUserMembershipFilter, self).qs.filter( codice__in=_allowed_pianos).order_by('-last_update') else: return super( PianoUserMembershipFilter, self).qs.filter(ente__code__in=_enti).order_by('-last_update')
def mutate(cls, root, info, file, **input): if rules.test_rule('strt_core.api.can_access_private_area', info.context.user): # Fetching input arguments _codice_piano = input['codice'] _tipo_file = input['tipo_file'] try: # Validating 'Piano' _piano = Piano.objects.get(codice=_codice_piano) _resources = UploadBaseBase.handle_uploaded_data( file, _codice_piano, _piano.fase, _tipo_file ) _success = False if _resources and len(_resources) > 0: _success = True for _risorsa in _resources: RisorsePiano(piano=_piano, risorsa=_risorsa).save() return UploadFile(piano_aggiornato=_piano, success=_success,file_name=_resources[0].nome) except BaseException as e: tb = traceback.format_exc() logger.error(tb) return GraphQLError(e, code=500) # Something went wrong return GraphQLError(_("Not Allowed"), code=405)
def mutate_and_get_payload(cls, root, info, **input): _procedura_avvio = ProceduraAvvio.objects.get(uuid=input['uuid']) _procedura_avvio_data = input.get('procedura_avvio') if 'piano' in _procedura_avvio_data: # This cannot be changed _procedura_avvio_data.pop('piano') _piano = _procedura_avvio.piano _token = info.context.session[ 'token'] if 'token' in info.context.session else None _ente = _piano.ente if info.context.user and \ rules.test_rule('strt_core.api.can_edit_piano', info.context.user, _piano): try: if 'uuid' in _procedura_avvio_data: _procedura_avvio_data.pop('uuid') # This cannot be changed if 'data_creazione' in _procedura_avvio_data: _procedura_avvio_data.pop('data_creazione') # This cannot be changed # Ente (M) if 'ente' in _procedura_avvio_data: _procedura_avvio_data.pop('ente') # This cannot be changed # Tipologia (O) if 'conferenza_copianificazione' in _procedura_avvio_data and \ (rules.test_rule('strt_users.is_superuser', info.context.user) or is_RUP(info.context.user) or rules.test_rule('strt_core.api.is_actor', _token or (info.context.user, _ente), 'Comune')): _conferenza_copianificazione = _procedura_avvio_data.pop( 'conferenza_copianificazione') if _conferenza_copianificazione and _conferenza_copianificazione in TIPOLOGIA_CONF_COPIANIFIZAZIONE: _procedura_avvio_data[ 'conferenza_copianificazione'] = _conferenza_copianificazione procedura_avvio_aggiornata = update_create_instance( _procedura_avvio, _procedura_avvio_data) return cls( procedura_avvio_aggiornata=procedura_avvio_aggiornata) except BaseException as e: tb = traceback.format_exc() logger.error(tb) return GraphQLError(e, code=500) else: return GraphQLError(_("Forbidden"), code=403)
def mutate(self, info, **input): if info.context.user and rules.test_rule('strt_users.can_access_private_area', info.context.user) and \ (rules.test_rule('strt_users.is_superuser', info.context.user) or is_RUP(info.context.user)): # Fetching input arguments _id = input['uuid'] try: _contatto = Contatto.objects.get(uuid=_id) _contatto.delete() return DeleteContatto(success=True, uuid=_id) except BaseException as e: tb = traceback.format_exc() logger.error(tb) return GraphQLError(e, code=500) return DeleteContatto(success=False)
def has_object_permission(self, request, view, obj): # Read permissions are allowed following rule 'can_read_datasource', if request.method in permissions.SAFE_METHODS: return rules.test_rule('can_read_workspace', request.user, obj) # Write permissions are only allowed to the owner of the snippet. return obj.owner == request.user
def validate_fields_with_rules(user, data, error_message='Not found', **kwargs): for field, rule_name in kwargs.items(): assert rules.rule_exists(rule_name) if field in data and not rules.test_rule(rule_name, user, data[field]): raise ApplicationValidationError(field, [error_message])
def post(self, request, *args, **kwargs): user_social_auth = self.get_object() if not rules.test_rule('can_delete_user_social_auth', request.user, user_social_auth): messages.error(request, "Can not remove the last social account unless a password has been set.") return redirect('profile') assert isinstance(user_social_auth, UserSocialAuth) user_social_auth.delete() return redirect('profile')
def get_object(self, qs=None): if qs: self.object = qs.get(id=self.kwargs['pk']) if not rules.test_rule('can_change_snip', self.request, self.object): raise PermissionDenied return self.object raise ValueError('Queryset is none')
def post(self, request, *args, **kwargs): subscription = self.get_object() if rules.test_rule('is_last_owner', request.user, subscription): messages.error(request, 'You cannot change your role when you are the last owner') return redirect(subscription.community) subscription.role = kwargs['role'] subscription.save() return redirect(subscription.community)
def __init__(self, user, *args, **kwargs): super(AuthorityForm, self).__init__(*args, **kwargs) if not self.is_bound: if not self.fields['record_status_value'].initial: self.fields['record_status_value'].initial = CuratedMixin.ACTIVE self.user = user # disable fields user doesn't have access to if self.instance.pk: for field in self.fields: can_update = rules.test_rule('can_update_authority_field', user, (field, self.instance.pk)) if not can_update: self.fields[field].widget.attrs['readonly'] = True can_view = rules.test_rule('can_view_authority_field', user, (field, self.instance.pk)) if not can_view: self.fields[field] = forms.CharField(widget=NoViewInput()) self.fields[field].widget.attrs['readonly'] = True
def __init__(self, user, citation_id=None, *args, **kwargs): super(PartDetailsForm, self).__init__( *args, **kwargs) self.user = user self.citation_id = citation_id self.fields['volume_begin'].widget.attrs['placeholder'] = "Begin #" self.fields['volume_end'].widget.attrs['placeholder'] = "End #" self.fields['volume_free_text'].widget.attrs['placeholder'] = "Volume" self.fields['issue_begin'].widget.attrs['placeholder'] = "Begin #" self.fields['issue_end'].widget.attrs['placeholder'] = "End #" self.fields['issue_free_text'].widget.attrs['placeholder'] = "Issue" self.fields['page_begin'].widget.attrs['placeholder'] = "Begin #" self.fields['page_end'].widget.attrs['placeholder'] = "End #" self.fields['pages_free_text'].widget.attrs['placeholder'] = "Pages" self.fields['extent'].widget.attrs['placeholder'] = "Extent" self.fields['extent_note'].widget.attrs['placeholder'] = "Extent note" if citation_id: can_update = rules.test_rule('can_update_citation_field', user, ('part_details', citation_id)) can_view = rules.test_rule('can_view_citation_field', user, ('part_details', citation_id)) set_field_access(can_update, can_view, self.fields)
def get(self, request, *args, **kwargs): self.object = self.get_object() community = self.object try: user_subscription = CommunitySubscription.objects.get( user=request.user, community=community) except CommunitySubscription.DoesNotExist: messages.warning(request, 'You cannot unsubscribe when you are not subscribed') return redirect(community) if not rules.test_rule('can_unsubscribe', request.user, user_subscription): messages.error(request, 'You cannot unsubscribe when you are the last owner') return redirect(community) return super().get(request, *args, **kwargs)
def post(self, request, *args, **kwargs): self.object = self.get_object() community = self.object try: user_subscription = CommunitySubscription.objects.get( user=request.user, community=community) except CommunitySubscription.DoesNotExist: messages.warning(request, 'You cannot unsubscribe when you are not subscribed') return redirect(community) if not rules.test_rule('can_unsubscribe', request.user, user_subscription): messages.error(request, 'You cannot unsubscribe when you are the last owner') return redirect(community) EventRSVP.objects.upcoming.filter( event__community=community, user=request.user).delete() user_subscription.delete() messages.success(request, 'Successfully unsubscribed from "{}"'.format(community.name)) return redirect(community)
def dispatch(self, request, *args, **kwargs): if not rules.test_rule('exportdb.can_export', request.user): raise PermissionDenied return super(ExportPermissionMixin, self).dispatch(request, *args, **kwargs)
def test_single(self, user, rule): """ Return True if user has permission. """ return user.is_superuser or rules.test_rule(rule, user, self.model)
def test_permission_testings(self): with mock.patch('rules.is_staff', return_value=True): self.assertTrue( rules.test_rule('exportdb.can_export', self.normal_user) ) permission_mock.assert_called_with(self.normal_user)