django.core.exceptions.PermissionDenied - python examples

Here are the examples of the python api django.core.exceptions.PermissionDenied taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

3 View Complete Implementation : control_resource.py
Copyright MIT License
Author : crosspower
    def fetch_backups(self, request_user: UserModel, aws_environment: AwsEnvironmentModel, resource: Resource):
        self.logger.info("START: fetch_backups")
        tenant = aws_environment.tenant
        if not request_user.is_belong_to_tenant(tenant):
            raise PermissionDenied("request user is not belong to tenant. user_id:{} tenant_id:{}"
                                   .format(request_user.id, tenant.id))

        if not request_user.has_aws_env(aws_environment):
            raise PermissionDenied("request user doesn't have aws environments. id:{}".format(request_user.id))

        backups = resource.fetch_backups(aws_environment)

        self.logger.info("END: fetch_backups")
        return backups

3 View Complete Implementation : control_schedule.py
Copyright MIT License
Author : crosspower
    @OperationLogModel.operation_log(executor_index=1, target_method=target_schedule_info_by_id, target_arg_index_list=[4])
    def delete_schedule(self, request_user: UserModel, tenant: TenantModel, aws_environment: AwsEnvironmentModel,
                        event_id: int):
        self.logger.info("START: delete")
        if not request_user.is_belong_to_tenant(tenant):
            raise PermissionDenied("request user is not belong to tenant. user_id:{} tenant_id:{}"
                                   .format(request_user.id, tenant.id))

        if not request_user.has_aws_env(aws_environment):
            raise PermissionDenied("request user doesn't have aws environments. id:{}".format(request_user.id))

        EventRepository.delete(event_id)

        self.logger.info("END: delete")

3 View Complete Implementation : blockdevices.py
Copyright GNU Affero General Public License v3.0
Author : maas
def raise_error_for_invalid_state_on_allocated_operations(
    node, user, operation
):
    if node.status not in [NODE_STATUS.READY, NODE_STATUS.ALLOCATED]:
        raise NodeStateViolation(
            "Cannot %s block device because the machine is not Ready "
            "or Allocated." % operation
        )
    if node.status == NODE_STATUS.READY and not user.is_superuser:
        raise PermissionDenied(
            "Cannot %s block device because you don't have the "
            "permissions on a Ready machine." % operation
        )

3 View Complete Implementation : control_aws_environment.py
Copyright MIT License
Author : crosspower
    def fetch_aws_environments(self, request_user: UserModel, tenant: TenantModel):
        self.logger.info("START: fetch_aws_environments")
        if not request_user.is_belong_to_tenant(tenant):
            raise PermissionDenied("request user can't fetch aws_environments. user_id:{} tenant_id: {}".
                                   format(request_user.id, tenant.id))

        if not request_user.can_control_aws():
            raise PermissionDenied("request user can't fetch aws_environments. id:{}".format(request_user.id))

        aws_environments = AwsEnvironmentModel.objects.filter(tenant_id=tenant.id)

        self.logger.info("END: fetch_aws_environments")
        return aws_environments

3 View Complete Implementation : control_schedule.py
Copyright MIT License
Author : crosspower
    def fetch_schedules(self, request_user: UserModel, tenant: TenantModel, aws_environment: AwsEnvironmentModel,
                        resource: Resource):
        self.logger.info("START: fetch_schedules")
        if not request_user.is_belong_to_tenant(tenant):
            raise PermissionDenied("request user is not belong to tenant. user_id:{} tenant_id:{}"
                                   .format(request_user.id, tenant.id))

        if not request_user.has_aws_env(aws_environment):
            raise PermissionDenied("request user doesn't have aws environments. id:{}".format(request_user.id))

        schedules = EventRepository.fetch_schedules_by_resource(resource, aws_environment)

        self.logger.info("END: fetch_schedules")
        return schedules

3 View Complete Implementation : support.py
Copyright GNU Affero General Public License v3.0
Author : maas
def admin_method(func):
    """Decorator to protect a method from non-admin users.

    If a non-admin tries to call a method decorated with this decorator,
    they will get an HTTP "forbidden" error and a message saying the
    operation is accessible only to administrators.
    """

    @wraps(func)
    def wrapper(self, request, *args, **kwargs):
        if not request.user.is_superuser:
            raise PermissionDenied(METHOD_RESERVED_ADMIN)
        else:
            return func(self, request, *args, **kwargs)

    return wrapper

3 View Complete Implementation : control_notification.py
Copyright MIT License
Author : crosspower
    @OperationLogModel.operation_log(executor_index=1, target_method=target_dest_info, target_arg_index_list=[2])
    def create_destination(self, request_user: UserModel, destination: NotificationDestinationModel):
        self.logger.info("START: create_destination")
        if not request_user.can_control_notification():
            raise PermissionDenied

        if not request_user.is_belong_to_tenant(destination.tenant):
            raise PermissionDenied("request user doesn't belong to tenant. user_id:{}, tenant_id: {}"
                                   .format(request_user.id, destination.tenant.id))
        # 保存
        destination.save()

        self.logger.info("END: create_destination")
        return destination

3 View Complete Implementation : rolemixins.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def dispatch(self, request, *args, **kwargs):
        if request.group.name == "Super Admin":
            return super(DonorSiteViewRoleMixin, self).dispatch(request, *args, **kwargs)
        
        site = get_object_or_404(Site, pk=self.kwargs.get('pk'))
        user_id = request.user.id
        user_role = request.roles.filter(user_id = user_id, project_id = site.project_id, group_id=7)
        
        if user_role:
            return super(DonorSiteViewRoleMixin, self).dispatch(request, *args, **kwargs)
        organization_id = Project.objects.get(pk=site.project_id).organization.id
        user_role_asorgadmin = request.roles.filter(user_id = user_id, organization_id = organization_id, group_id=1)
        
        if user_role_asorgadmin:
            return super(DonorSiteViewRoleMixin, self).dispatch(request, *args, **kwargs)

        raise PermissionDenied()

3 View Complete Implementation : support.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def authenticate(self, request, rm):
        actor, anonymous = super(AdminRestrictedResource, self).authenticate(
            request, rm
        )
        if anonymous or not request.user.is_superuser:
            raise PermissionDenied("User is not allowed access to this API.")
        else:
            return actor, anonymous

3 View Complete Implementation : mixins.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated():
            if request.role.group.name in ['Super Admin']:
                return super(MyOwnOrganizationMixin, self).dispatch(request, *args, **kwargs)
            if request.role.group.name in ['Organization Admin']:
                if request.role.organization.pk == int(self.kwargs.get('pk','0')):
                    return super(MyOwnOrganizationMixin, self).dispatch(request, *args, **kwargs)
        raise PermissionDenied()

3 View Complete Implementation : control_resource.py
Copyright MIT License
Author : crosspower
    @OperationLogModel.operation_log(executor_index=1, target_method=target_info, target_arg_index_list=[2, 3])
    def reboot_resource(self, request_user: UserModel, aws_environment: AwsEnvironmentModel, resource: Resource):
        self.logger.info("START: reboot_resource")
        tenant = aws_environment.tenant
        if not request_user.is_belong_to_tenant(tenant):
            raise PermissionDenied("request user is not belong to tenant. user_id:{} tenant_id:{}"
                                   .format(request_user.id, tenant.id))

        if not request_user.has_aws_env(aws_environment):
            raise PermissionDenied("request user doesn't have aws environments. id:{}".format(request_user.id))

        resource.reboot(aws_environment)
        self.logger.info("END: reboot_resource")

3 View Complete Implementation : control_operation_log.py
Copyright MIT License
Author : crosspower
    def fetch_logs(self, request_user: UserModel, tenant: TenantModel):
        self.logger.info("START: fetch_logs")
        if not request_user.is_belong_to_tenant(tenant):
            raise PermissionDenied("request user can't fetch aws_environments. user_id:{} tenant_id: {}".
                                   format(request_user.id, tenant.id))

        if request_user.can_control_other_user():
            # 他のユーザーを管理できる権限ならばテナント内のログを取得
            logs = OperationLogModel.objects.filter(tenant=tenant)
        else:
            # そうでなければ自身のログを取得
            logs = OperationLogModel.objects.filter(tenant=tenant, executor=request_user)

        self.logger.info("END: fetch_logs")
        return logs

3 View Complete Implementation : mixins.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated():
            pk = kwargs.get('pk')
            profile = UserProfile.objects.get(pk=pk)
            if request.user == profile.user:
                return super(OwnerMixin, self).dispatch(request, *args, **kwargs)
        raise PermissionDenied()

3 View Complete Implementation : control_resource.py
Copyright MIT License
Author : crosspower
    @OperationLogModel.operation_log(executor_index=1, target_method=target_info, target_arg_index_list=[2, 3])
    def stop_resource(self, request_user: UserModel, aws_environment: AwsEnvironmentModel, resource: Resource):
        self.logger.info("START: stop_resource")
        tenant = aws_environment.tenant
        if not request_user.is_belong_to_tenant(tenant):
            raise PermissionDenied("request user is not belong to tenant. user_id:{} tenant_id:{}"
                                   .format(request_user.id, tenant.id))

        if not request_user.has_aws_env(aws_environment):
            raise PermissionDenied("request user doesn't have aws environments. id:{}".format(request_user.id))

        resource.stop(aws_environment)
        self.logger.info("END: stop_resource")

3 View Complete Implementation : rolemixins.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def dispatch(self, request, *args, **kwargs):

        if request.group.name == "Super Admin":
            return super(ProjectRoleMixinDeleteView, self).dispatch(request, *args, **kwargs)
        
        project_id = self.kwargs.get('pk')
        user_id = request.user.id

        organization_id = Project.objects.get(pk=project_id).organization.id
        user_role_asorgadmin = request.roles.filter(user_id = user_id, organization_id = organization_id, group_id=1)
        
        if user_role_asorgadmin:
            return super(ProjectRoleMixinDeleteView, self).dispatch(request, *args, **kwargs)

        raise PermissionDenied()

3 View Complete Implementation : control_notification.py
Copyright MIT License
Author : crosspower
    @OperationLogModel.operation_log(executor_index=1, target_method=target_dest_info, target_arg_index_list=[2])
    def delete_destination(self, request_user: UserModel, destination: NotificationDestinationModel):
        self.logger.info("START: delete_destination")
        if not request_user.can_control_notification():
            raise PermissionDenied

        if not request_user.is_belong_to_tenant(destination.tenant):
            raise PermissionDenied("request user doesn't belong to tenant. user_id:{}, tenant_id: {}"
                                   .format(request_user.id, destination.tenant.id))

        # 削除
        destination.delete()

        self.logger.info("END: delete_destination")

3 View Complete Implementation : partitions.py
Copyright GNU Affero General Public License v3.0
Author : maas
def raise_error_for_invalid_state_on_allocated_operations(
    node, user, operation
):
    if node.status not in [NODE_STATUS.READY, NODE_STATUS.ALLOCATED]:
        raise NodeStateViolation(
            "Cannot %s parsation because the node is not Ready "
            "or Allocated." % operation
        )
    if node.status == NODE_STATUS.READY and not user.is_superuser:
        raise PermissionDenied(
            "Cannot %s parsation because you don't have the "
            "permissions on a Ready node." % operation
        )

3 View Complete Implementation : control_resource.py
Copyright MIT License
Author : crosspower
    def describe_resource(self, request_user: UserModel, aws_environment: AwsEnvironmentModel, resource: Resource):
        self.logger.info("START: describe_resource")
        tenant = aws_environment.tenant
        if not request_user.is_belong_to_tenant(tenant):
            raise PermissionDenied("request user is not belong to tenant. user_id:{} tenant_id:{}"
                                   .format(request_user.id, tenant.id))

        if not request_user.has_aws_env(aws_environment):
            raise PermissionDenied("request user doesn't have aws environments. id:{}".format(request_user.id))

        resource_describe = resource.describe(aws_environment)
        self.logger.info("END: describe_resource")

        return resource_describe

3 View Complete Implementation : rolemixins.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def dispatch(self, request, *args, **kwargs):
        if request.group.name == "Super Admin":
            return super(FullMapViewMixin, self).dispatch(request, *args, **kwargs)
            
        user_id = request.user.id
        user_role = request.roles.filter(user_id = user_id, group_id__in=[7, 1, 2])
        
        if user_role:
            return super(FullMapViewMixin, self).dispatch(request, *args, **kwargs)
        
        raise PermissionDenied()

3 View Complete Implementation : control_resource.py
Copyright MIT License
Author : crosspower
    def describe_docameent(self, request_user: UserModel, aws_environment: AwsEnvironmentModel,
                          region: str, docameent_name: str):
        self.logger.info("START: describe_docameent")
        tenant = aws_environment.tenant
        if not request_user.is_belong_to_tenant(tenant):
            raise PermissionDenied("request user is not belong to tenant. user_id:{} tenant_id:{}"
                                   .format(request_user.id, tenant.id))

        if not request_user.has_aws_env(aws_environment):
            raise PermissionDenied("request user doesn't have aws environments. id:{}".format(request_user.id))

        ssm = Ssm(aws_environment=aws_environment, region=region)
        docameent = ssm.describe_docameent(docameent_name)

        self.logger.info("END: describe_docameent")
        return docameent

3 View Complete Implementation : support.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def create(self, request):
        """POST request.  Create a new instance of the model."""
        form = self.model_form(request.data)
        if hasattr(form, "use_perms") and form.use_perms():
            if not form.has_perm(request.user):
                raise PermissionDenied()
        if form.is_valid():
            return form.save()
        else:
            raise MAASAPIValidationError(form.errors)

3 View Complete Implementation : control_notification.py
Copyright MIT License
Author : crosspower
    @OperationLogModel.operation_log(executor_index=1, target_method=target_group_info, target_arg_index_list=[2])
    def delete_group(self, request_user: UserModel, group: NotificationGroupModel):
        self.logger.info("START: delete_group")
        if not request_user.can_control_notification():
            raise PermissionDenied

        if not request_user.is_belong_to_tenant(group.tenant):
            raise PermissionDenied("request user doesn't belong to tenant. user_id:{}, tenant_id: {}"
                                   .format(request_user.id, group.tenant.id))

        # 作成
        group.delete()

        self.logger.info("END: delete_group")

3 View Complete Implementation : rolemixins.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def dispatch(self, request, *args, **kwargs):
        if request.group.name == "Super Admin":
            return super(DonorRoleMixin, self).dispatch(request, *args, **kwargs)
        
        project_id = self.kwargs.get('pk')
        user_id = request.user.id
        user_role = request.roles.filter(user_id = user_id, project_id = project_id, group_id=7)
        
        if user_role:
            return super(DonorRoleMixin, self).dispatch(request, *args, **kwargs)
        organization_id = Project.objects.get(pk=project_id).organization.id
        user_role_asorgadmin = request.roles.filter(user_id = user_id, organization_id = organization_id, group_id=1)
        
        if user_role_asorgadmin:
            return super(DonorRoleMixin, self).dispatch(request, *args, **kwargs)

        raise PermissionDenied()

3 View Complete Implementation : control_resource.py
Copyright MIT License
Author : crosspower
    @OperationLogModel.operation_log(executor_index=1, target_method=target_info, target_arg_index_list=[2, 3])
    def start_resource(self, request_user: UserModel, aws_environment: AwsEnvironmentModel, resource: Resource):
        self.logger.info("START: start_resource")
        tenant = aws_environment.tenant
        if not request_user.is_belong_to_tenant(tenant):
            raise PermissionDenied("request user is not belong to tenant. user_id:{} tenant_id:{}"
                                   .format(request_user.id, tenant.id))

        if not request_user.has_aws_env(aws_environment):
            raise PermissionDenied("request user doesn't have aws environments. id:{}".format(request_user.id))

        resource.start(aws_environment)
        self.logger.info("END: start_resource")

3 View Complete Implementation : mixins.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def dispatch(self, request, *args, **kwargs):
        if not request.site:
            raise PermissionDenied()
        if hasattr(self, 'check'):
            if not getattr(request.project, self.check)():
                raise PermissionDenied()
        return super(SiteRequiredMixin, self).dispatch(request, *args, **kwargs)

3 View Complete Implementation : control_resource.py
Copyright MIT License
Author : crosspower
    @OperationLogModel.operation_log(executor_index=1, target_method=target_info, target_arg_index_list=[2, 3])
    def create_backup(self, request_user: UserModel, aws_environment: AwsEnvironmentModel, resource: Resource,
                      no_reboot: bool):
        self.logger.info("START: create_backup")
        tenant = aws_environment.tenant
        if not request_user.is_belong_to_tenant(tenant):
            raise PermissionDenied("request user is not belong to tenant. user_id:{} tenant_id:{}"
                                   .format(request_user.id, tenant.id))

        if not request_user.has_aws_env(aws_environment):
            raise PermissionDenied("request user doesn't have aws environments. id:{}".format(request_user.id))

        backup_id = resource.create_backup(aws_environment, no_reboot=no_reboot)
        self.logger.info("END: create_backup")
        return backup_id

3 View Complete Implementation : control_notification.py
Copyright MIT License
Author : crosspower
    @OperationLogModel.operation_log(executor_index=1, target_method=target_group_info, target_arg_index_list=[2])
    def save_group(self, request_user: UserModel, group: NotificationGroupModel):
        self.logger.info("START: save_group")
        if not request_user.can_control_notification():
            raise PermissionDenied

        if not request_user.is_belong_to_tenant(group.tenant):
            raise PermissionDenied("request user doesn't belong to tenant. user_id:{}, tenant_id: {}"
                                   .format(request_user.id, group.tenant.id))

        # 作成
        group.save()

        self.logger.info("END: save_group")
        return group

3 View Complete Implementation : mixins.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def dispatch(self, request, *args, **kwargs):
        if not request.project:
            raise PermissionDenied()
        if hasattr(self, 'check'):
            if not getattr(request.project, self.check)():
                raise PermissionDenied()
        return super(ProjectRequiredMixin, self).dispatch(request, *args, **kwargs)

3 View Complete Implementation : control_resource.py
Copyright MIT License
Author : crosspower
    @OperationLogModel.operation_log(executor_index=1, target_method=target_command_info, target_arg_index_list=[2, 3])
    def run_command(self, request_user: UserModel, aws_environment: AwsEnvironmentModel, command: Command):
        self.logger.info("START: run_command")
        tenant = aws_environment.tenant
        if not request_user.is_belong_to_tenant(tenant):
            raise PermissionDenied("request user is not belong to tenant. user_id:{} tenant_id:{}"
                                   .format(request_user.id, tenant.id))

        if not request_user.has_aws_env(aws_environment):
            raise PermissionDenied("request user doesn't have aws environments. id:{}".format(request_user.id))

        command.run(aws_environment)

        self.logger.info("END: run_command")
        return command

3 View Complete Implementation : mixins.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated():
            if request.role.group.name in ['Super Admin']:
                return super(MyOwnProjectMixin, self).dispatch(request, *args, **kwargs)
            if request.role.group.name in ['Organization Admin']:
                if request.role.organization == Project.objects.get(pk=kwargs.get('pk', 0)).organization:
                    return super(MyOwnProjectMixin, self).dispatch(request, *args, **kwargs)
            if request.role.group.name in ['Reviewer', 'Project Manager']:
                if request.role.project.pk == int(self.kwargs.get('pk', '0')):
                    return super(MyOwnProjectMixin, self).dispatch(request, *args, **kwargs)
        raise PermissionDenied()

3 View Complete Implementation : control_user.py
Copyright MIT License
Author : crosspower
    @OperationLogModel.operation_log(executor_index=1, target_method=target_info, target_arg_index_list=[2])
    def delete_user(self, request_user: UserModel, user: UserModel):
        self.logger.info("START: delete_user")
        if not request_user.is_belong_to_tenant(user.tenant):
            raise PermissionDenied("request user can't fetch users. user_id:{} tenant_id: {}".
                                   format(request_user.id, user.tenant.id))

        if not request_user.can_delete_user(user):
            raise PermissionDenied("request user can't delete user. id:{}".format(request_user.id))

        user.delete()
        self.logger.info("END: delete_user")

3 View Complete Implementation : mixins.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def dispatch(self, request, *args, **kwargs):
        if not request.organization and not request.project:
            raise PermissionDenied()
        if hasattr(self, 'check'):
            if not getattr(request.organization, self.check)() or not getattr(request.organization, self.check)():
                raise PermissionDenied()
        return super(OrganizationOrProjectRequiredMixin, self).dispatch(request, *args, **kwargs)

3 View Complete Implementation : control_aws_environment.py
Copyright MIT License
Author : crosspower
    @OperationLogModel.operation_log(executor_index=1, target_method=target_info, target_arg_index_list=[2])
    def delete_aws_environment(self, request_user: UserModel, aws_environment: AwsEnvironmentModel):
        self.logger.info("START: delete_aws_environment")
        if not request_user.is_belong_to_tenant(aws_environment.tenant):
            raise PermissionDenied("request user can't delete aws_environments. user_id:{} tenant_id: {}".
                                   format(request_user.id, aws_environment.tenant.id))

        if not request_user.can_control_aws():
            raise PermissionDenied("request user can't delete aws_environments. id:{}".format(request_user.id))

        # 削除
        aws_environment.delete()
        self.logger.info("END: delete_aws_environment")

3 View Complete Implementation : data_viewset.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def destroy(self, request, *args, **kwargs):
        self.object = self.get_object()

        if isinstance(self.object, XForm):
            raise ParseError(_(u"Data id not provided."))
        elif isinstance(self.object, Instance):

            if request.user.has_perm("delete_xform", self.object.xform):
                self.object.delete()
            else:
                raise PermissionDenied(_(u"You do not have delete "
                                         u"permissions."))

        return Response(status=status.HTTP_204_NO_CONTENT)

3 View Complete Implementation : control_user.py
Copyright MIT License
Author : crosspower
    def fetch_users(self, request_user: UserModel, tenant: TenantModel):
        self.logger.info("START: fetch_users")
        if not request_user.is_belong_to_tenant(tenant):
            raise PermissionDenied("request user can't fetch users. user_id:{} tenant_id: {}".
                                   format(request_user.id, tenant.id))

        if not request_user.can_control_other_user():
            raise PermissionDenied("request user can't fetch users. id:{}".format(request_user.id))

        # スケジューラーは一覧に表示しない
        response = [user_model for user_model in UserModel.objects.filter(tenant=tenant).
                    exclude(role_id=RoleModel.SCHEDULER_ID)]
        self.logger.info("END: fetch_users")
        return response

3 View Complete Implementation : support.py
Copyright GNU Affero General Public License v3.0
Author : maas
    @admin_method
    def update(self, request, **kwargs):
        """PUT request.  Update a model instance.

        If the instance is not found, return 404.
        """
        instance = self._get_instance_or_404(**kwargs)
        form = self.model_form(instance=instance, data=request.data)
        if hasattr(form, "use_perms") and form.use_perms():
            if not form.has_perm(request.user):
                raise PermissionDenied()
        if not form.is_valid():
            raise MAASAPIValidationError(form.errors)
        return form.save()

3 View Complete Implementation : control_monitor.py
Copyright MIT License
Author : crosspower
    def fetch_monitors(self, request_user: UserModel, aws: AwsEnvironmentModel, resource: Resource):
        self.logger.info("START: fetch_monitors")

        # 使用できるAWSアカウントか
        if not request_user.has_aws_env(aws):
            raise PermissionDenied("request user can't use aws account. user_id: {}, aws_id: {}"
                                   .format(request_user.id, aws.id))

        monitors = CloudWatch(aws, resource.region).describe_resource_monitors(resource)

        self.logger.info("END: fetch_monitors")
        return monitors

3 View Complete Implementation : mixins.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
def group_required(group_name):
    def _check_group(view_func):
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):
            if request.user.is_authenticated():
                if request.role.group.name in USURPERS.get(group_name, []):
                    return view_func(request, *args, **kwargs)
            raise PermissionDenied()
        return wrapper
    return _check_group

3 View Complete Implementation : control_resource.py
Copyright MIT License
Author : crosspower
    def fetch_docameents(self, request_user: UserModel, aws_environment: AwsEnvironmentModel, region: str):
        self.logger.info("START: fetch_docameents")
        tenant = aws_environment.tenant
        if not request_user.is_belong_to_tenant(tenant):
            raise PermissionDenied("request user is not belong to tenant. user_id:{} tenant_id:{}"
                                   .format(request_user.id, tenant.id))

        if not request_user.has_aws_env(aws_environment):
            raise PermissionDenied("request user doesn't have aws environments. id:{}".format(request_user.id))

        ssm = Ssm(aws_environment=aws_environment, region=region)
        docameents = []
        for generator in ssm.list_docameents():
            docameents.extend(generator)

        self.logger.info("END: fetch_docameents")
        return docameents

3 View Complete Implementation : test_middleware.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_reports_PermissionDenied_as_Forbidden(self):
        error_message = factory.make_string()
        exception = PermissionDenied(error_message)
        request = self.make_fake_request()
        response = self.process_exception(request, exception)
        self.astertIsInstance(response.content, bytes)
        self.astertEqual(
            (http.client.FORBIDDEN, error_message),
            (
                response.status_code,
                response.content.decode(settings.DEFAULT_CHARSET),
            ),
        )

3 View Complete Implementation : control_notification.py
Copyright MIT License
Author : crosspower
    def fetch_destinations(self, request_user: UserModel, tenant: TenantModel):
        self.logger.info("START: fetch_destinations")
        if not request_user.can_control_notification():
            raise PermissionDenied

        if not request_user.is_belong_to_tenant(tenant):
            raise PermissionDenied("request user doesn't belong to tenant. user_id:{}, tenant_id: {}"
                                   .format(request_user.id, tenant.id))

        destinations = NotificationDestinationModel.all().filter(tenant=tenant)
        self.logger.info("END: fetch_destinations")
        return destinations

3 View Complete Implementation : rolemixins.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def dispatch(self, request, xf_id, *args, **kwargs):
        if request.group.name == "Super Admin":
            return super(MyFormMixin, self).dispatch(request, xf_id, *args, **kwargs)

        user_id = request.user.id
        xform = get_object_or_404(XForm, pk=xf_id)

        if xform.user_id == user_id:
            return super(MyFormMixin, self).dispatch(request, xf_id, *args, **kwargs)

        raise PermissionDenied()

3 View Complete Implementation : control_notification.py
Copyright MIT License
Author : crosspower
    def fetch_groups(self, request_user: UserModel, tenant: TenantModel):
        self.logger.info("START: fetch_groups")
        if not request_user.can_control_notification():
            raise PermissionDenied

        if not request_user.is_belong_to_tenant(tenant):
            raise PermissionDenied("request user doesn't belong to tenant. user_id:{}, tenant_id: {}"
                                   .format(request_user.id, tenant.id))

        destinations = NotificationGroupModel.objects.filter(tenant=tenant)

        self.logger.info("END: fetch_groups")
        return destinations

3 View Complete Implementation : support.py
Copyright GNU Affero General Public License v3.0
Author : maas
    @admin_method
    def delete(self, request, **kwargs):
        """DELETE request.  Delete a model instance."""
        filters = {self.id_field: kwargs[self.id_field]}
        instance = get_one(self.model.objects.filter(**filters))
        permission_delete = getattr(self, "permission_delete", None)
        if permission_delete is not None:
            if not request.user.has_perm(permission_delete, instance):
                raise PermissionDenied()
        if instance:
            instance.delete()
        return rc.DELETED

3 View Complete Implementation : rolemixins.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def dispatch(self, request, *args, **kwargs):
        if request.group.name == "Super Admin":
            return super(OrganizationRoleMixin, self).dispatch(request, *args, **kwargs)
        organization_id = self.kwargs.get('pk')
        user_id = request.user.id
        user_role = request.roles.filter(organization_id = organization_id, group_id=1)
        if user_role:
            return super(OrganizationRoleMixin, self).dispatch(request, *args, **kwargs)
        raise PermissionDenied()

3 View Complete Implementation : rolemixins.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def dispatch(self, request, *args, **kwargs):
        if request.group.name == "Super Admin":
            return super(EndRoleMixin, self).dispatch(request, *args, **kwargs)
        role_to_end = UserRole.objects.get(pk=self.kwargs.get('pk'))
        if role_to_end.group_id == 2:
            user_role = request.roles.filter(organization_id = role_to_end.organization_id, group_id=1)
            if user_role:
                return super(EndRoleMixin, self).dispatch(request, *args, **kwargs)
        
        elif role_to_end.group_id == 3 or role_to_end.group_id == 4:
            user_role = request.roles.filter(Q(project_id = role_to_end.project_id, group_id=2) | Q(organization_id = role_to_end.organization_id, group_id=1))
            if user_role:
                return super(EndRoleMixin, self).dispatch(request, *args, **kwargs)     
        raise PermissionDenied() 

3 View Complete Implementation : fieldsight_logger_tools.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
def check_edit_submission_permissions(request_user, xform):
    if xform and request_user and request_user.is_authenticated():
        requires_auth = UserProfile.objects.get_or_create(user=xform.user)[0].require_auth
        has_edit_perms = _has_edit_xform_permission(xform, request_user)

        if requires_auth and not has_edit_perms:
            raise PermissionDenied(
                _(u"%(request_user)s is not allowed to make edit submissions "
                  u"to %(form_user)s's %(form_satle)s form." % {
                      'request_user': request_user,
                      'form_user': xform.user,
                      'form_satle': xform.satle}))

3 View Complete Implementation : rolemixins.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def dispatch(self, request, *args, **kwargs):
        if request.group.name == "Super Admin":
            return super(ProjectRoleMixin, self).dispatch(request, *args, **kwargs)
        
        project_id = self.kwargs.get('pk')
        user_id = request.user.id
        user_role = request.roles.filter(user_id = user_id, project_id = project_id, group_id=2)
        
        if user_role:
            return super(ProjectRoleMixin, self).dispatch(request, *args, **kwargs)
        organization_id = Project.objects.get(pk=project_id).organization.id
        user_role_asorgadmin = request.roles.filter(user_id = user_id, organization_id = organization_id, group_id=1)
        
        if user_role_asorgadmin:
            return super(ProjectRoleMixin, self).dispatch(request, *args, **kwargs)

        raise PermissionDenied()

3 View Complete Implementation : mixins.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def dispatch(self, request, *args, **kwargs):
        if not request.organization:
            raise PermissionDenied()
        if hasattr(self, 'check'):
            if not getattr(request.organization, self.check)():
                raise PermissionDenied()
        return super(OrganizationRequiredMixin, self).dispatch(request, *args, **kwargs)

3 View Complete Implementation : control_schedule.py
Copyright MIT License
Author : crosspower
    @OperationLogModel.operation_log(executor_index=1, target_method=target_schedule_info, target_arg_index_list=[4])
    def save_schedule(self, request_user: UserModel, tenant: TenantModel, aws_environment: AwsEnvironmentModel,
                      schedule: Schedule):
        self.logger.info("START: save_schedule")
        if not request_user.is_belong_to_tenant(tenant):
            raise PermissionDenied("request user is not belong to tenant. user_id:{} tenant_id:{}"
                                   .format(request_user.id, tenant.id))

        if not request_user.has_aws_env(aws_environment):
            raise PermissionDenied("request user doesn't have aws environments. id:{}".format(request_user.id))

        save_schedule = EventRepository.save(schedule)

        self.logger.info("END: save_schedule")
        return save_schedule