示例#1
0
    def test_filter_rules(self):
        self.assertEqual(len(rules.filter_rules([], ['notag'])), 0)

        rule_list = []
        rules.add_rule(rule_list, 1, 1, 'oneway', 'tag1')
        self.assertEqual(len(rules.filter_rules(rule_list, 'notag')), 0)
        self.assertEqual(len(rules.filter_rules(rule_list, 'oneway')), 1)
        self.assertEqual(len(rules.filter_rules(rule_list, 'tag1')), 1)
示例#2
0
 def init_urls(self):
     #initialize urls
     for v in rules.merge_rules():
         appname, endpoint, url, kw = v
         static = kw.pop('static', None)
         if static:
             conf.static_views.append(endpoint)
         rules.add_rule(conf.url_map, url, endpoint, **kw)
示例#3
0
 def init_urls(self):
     #initialize urls
     for v in rules.merge_rules():
         appname, endpoint, url, kw = v
         static = kw.pop('static', None)
         if static:
             static_views.append(endpoint)
         try:
             rules.add_rule(url_map, url, endpoint, **kw)
         except:
             log.error("Wrong url url=%s, endpoint=%s" % (url, endpoint))
             raise
示例#4
0
 def init_urls(self):
     #initialize urls
     for v in rules.merge_rules():
         appname, endpoint, url, kw = v
         static = kw.pop('static', None)
         if static:
             static_views.append(endpoint)
         try:
             rules.add_rule(url_map, url, endpoint, **kw)
         except:
             log.error("Wrong url url=%s, endpoint=%s" % (url, endpoint))
             raise
示例#5
0
@rules.predicate
def is_org_admin(user):
    if not user or not user.employee:
        return False
    return user.employee.is_org_admin


@rules.predicate
def is_ou_manager(user, orgunit):
    if not user or not user.employee:
        return False
    return orgunit.manager == user.employee


@rules.predicate
def is_employee_manager(employee, user):
    return user.is_staff | user.is_org_admin | employee.supervisor == user


# Rules

rules.add_rule('change_orgunit', is_staff | is_org_admin | is_ou_manager)
rules.add_rule('delete_orgunit', is_staff | is_org_admin)
rules.add_rule('create_orgunit', is_staff | is_org_admin)

# Permissions

rules.add_perm('organization.change_orgunit',
               is_staff | is_org_admin | is_ou_manager)
rules.add_perm('organization.delete_orgunit', is_staff | is_org_admin)
from simplify import *
from rules import add_rule

""" sin_rule = Rule(F('sin', AC0('*', E(separate_2, 'k'), Var('x', 'complex'))), #bal oldal (source)
                AC0('*', F('sin', AC0('*', Var('k', 'integer'), Var('x', 'complex'))), F('cos', AC0('*', Var('k', 'integer'), Var('x', 'complex')))), #jobb oldal (target)
                'trig') """
trig_rules = []

add_rule(trig_rules,
	F('tan', Var('x','complex')), # bal oldal
	A0('/', F('sin', Var('x','complex')), F('cos', Var('x','complex'))), # jobb oldal
	'trig')
 
add_rule(trig_rules,
	F('cot', Var('x','complex')), # bal oldal
	A0('/', F('cos', Var('x','complex')), F('sin', Var('x','complex'))), # jobb oldal
	'trig')

add_rule(trig_rules,
	F('sin', AC0('+', Var('x','complex'), Var('y', 'complex'))), 
	AC0('+', AC1('*', F('sin', Var('x','complex')), F('cos', Var('y','complex'))), AC1('*', F('cos', Var('x','complex')), F('sin', Var('y','complex')))),
	'trig')    

add_rule(trig_rules,
	F('cos', AC0('+', Var('x','complex'), Var('y', 'complex'))), 
	F('-', AC1('*', F('cos', Var('x','complex')), F('cos', Var('y','complex'))), AC1('*', F('sin', Var('x','complex')), F('sin', Var('y','complex')))),
	'trig') 

add_rule(trig_rules,
	AC0('+',F('^', F('sin', Var('x','complex')), 2), F('^', F('cos', Var('x','complex')), 2) ),
	1,
示例#7
0
@rules.predicate
def is_colleague_of(user1, user2):
    """
    True if two users are colleagues (i.e., both are students in the same
    classroom).
    """
    return NotImplemented


@rules.predicate
def is_teacher_of(teacher, student):
    """
    True if first user is a teacher in a course in which the second user is a
    student.
    """
    return NotImplemented


@rules.predicate
def is_student_of(user1, user2):
    """
    True if first user is a student in a course in which the second user is a
    teacher.
    """
    return NotImplemented


rules.add_perm('classrooms.view_classroom', is_registered)
rules.add_perm('classrooms.edit_classroom', is_owner)
rules.add_rule('classrooms.can_leave', is_student)
示例#8
0
rules.add_perm('registry.view_patient.admin', is_admin_for)
rules.add_perm('registry.view_patient.nurse', is_nurse_for)
rules.add_perm('registry.view_patient.doctor', is_doctor_of)
rules.add_perm('registry.view_patient.self', (is_patient & is_self))

# Has a direct relationship with the patient but not the admin
rules.add_perm('registry.view_patient',
               view_patient & ((is_patient & is_self) | is_nurse_check | is_doctor_check))
# Has a direct relationship with the patient
rules.add_perm('registry.nonmed_patient',
               view_patient & ((is_patient & is_self) | is_admin_check | is_nurse_check | is_doctor_check))
# Can either view their own patient profile page or has general permissions to see patient page
rules.add_perm('registry.view_patient.profile',
               view_patient & ((is_patient & is_self) | is_administrator | is_nurse | is_doctor))

rules.add_perm('registry.view_an', an_profile)

# Define Rules

rules.add_rule('is_self', is_self)
rules.add_rule('is_patient', is_patient)
rules.add_rule('is_doctor', is_doctor)
rules.add_rule('is_doctor_check', is_doctor_check)
rules.add_rule('is_nurse', is_nurse)
rules.add_rule('is_administrator', is_administrator)

rules.add_rule('can_view_patient', has_appointment_check | is_doctor_check | (is_patient & is_self))
rules.add_rule('time_gt', time_gt)
rules.add_rule('has_relationship', (is_patient & is_self) | is_doctor_check | is_nurse_check | is_admin_for)
示例#9
0
#########################################################################

import rules

from strt_users.rules import (
    is_RUP,
    is_recognizable,
    # is_responsabile_ISIDE
)

from .auth import (user as user_rules, piano as piano_rules, vas as vas_rules)

# ############################################################################ #
# RULES
# ############################################################################ #
rules.add_rule('strt_core.api.can_access_private_area', is_recognizable)

rules.add_rule('strt_core.api.can_edit_piano',
               is_RUP | user_rules.can_access_piano)

rules.add_rule(
    'strt_core.api.is_actor',
    user_rules.is_actor_for_token | user_rules.is_actor_for_organization)

rules.add_rule('strt_core.api.can_update_piano', user_rules.can_access_piano)

rules.add_rule('strt_core.api.parere_sca_ok', vas_rules.parere_sca_ok)

rules.add_rule('strt_core.api.parere_verifica_vas_ok',
               vas_rules.parere_verifica_vas_ok)
示例#10
0
    if not hijacker.is_staff:
        return False
    # Staff can not impersonate staff
    if hijacked.is_staff:
        return False
    return True


@rules.predicate
def is_self(user, edited_user):
    return user == edited_user


# A *rule* so we can use check_rule, because check_perm always returns True for
# superusers, defeating the checks in can_impersonate
rules.add_rule('users.can-impersonate', can_impersonate)
rules.add_perm('users.may-impersonate', rules.is_staff)
rules.add_perm('users.search', rules.is_staff)
rules.add_perm('users.edit', rules.is_staff | is_self)
rules.add_perm('users.edit-during-contest', rules.is_staff)
rules.add_perm('users.delete', rules.is_superuser | is_self)
rules.add_perm('users.takeout', rules.is_superuser | is_self)
rules.add_perm('users.external-auth', rules.is_authenticated)


def hijack_authorization_check(hijacker, hijacked):
    """
    Custom check for django-hijack
    """
    return rules.test_rule('users.can-impersonate', hijacker, hijacked)
示例#11
0
def method_add_rule():
    rules.add_rule()
示例#12
0
文件: rules.py 项目: navarrovmn/mspad
        return user.username == archive.owner_username
    else:
        archive.owner_username = user.username
        archive.save()
        return True


@rules.predicate
def page_is_locked(page):
    return page.lock


#@TODO create rule logic
@rules.predicate
def is_editor(user, archive):
    return is_page_owner(user, archive)


@rules.predicate
def can_edit_page(user, page):
    if page_is_locked(page):
        if is_editor(user, page) or is_page_owner(user, page):
            return True
        else:
            return False
    else:
        return True


rules.add_rule('can_edit_page', can_edit_page)
rules.add_rule('is_page_owner', is_page_owner)
示例#13
0
from django.conf import settings

import rules


@rules.predicate
def permission(*args, **kwargs):
    return settings.EXPORTDB_PERMISSION(*args, **kwargs)


rules.add_rule('exportdb.can_export', permission)
示例#14
0
import rules


def is_member_of_groupchat(user, group):
    return group.members.filter(pk=user.pk).exists()


def is_groupchat_owner(user, group):
    return user.pk == group.owner.pk


# 'can view' also means can send messages
rules.add_perm('messaging.view_privatemessagegroup', is_member_of_groupchat)
# 'can edit' means adding new members or changing the groupchat name
rules.add_rule('can_edit_groupchat', is_groupchat_owner)
示例#15
0
from django_extensions.db.models import TimeStampedModel
from stdimage.models import StdImageField


class UserProfile(TimeStampedModel):
    user = models.OneToOneField("auth.User", unique=True)
    avatar = StdImageField(
        upload_to="avatars",
        variations={
            "thumbnail": (400, 400, True),
            "mini": (200, 200, True),
            "tiny": (100, 100, True),
            "micro": (40, 40, True),
        },
        help_text="Image should be square. Otherwise it will be cropped.",
    )

    def get_absolute_url(self):
        return reverse("profile")

    def __str__(self):
        return "Profile of {}".format(self.user.username)


@rules.predicate
def can_delete_user_social_auth(user, user_social_auth):
    return user_social_auth.allowed_to_disconnect(user, user_social_auth.provider)


rules.add_rule("can_delete_user_social_auth", can_delete_user_social_auth)
示例#16
0
from simplify import *
from rules import add_rule

pow_rules = []
"""
# 1^x = 1
add_rule(pow_rules,
	F('^', 1, Var('x', 'complex')),
	1,
	'pow', 'oneway')
# x^1 = x
add_rule(pow_rules,
	F('^', Var('x', 'complex'), 1),
	Var('x', 'complex'),
	'pow', 'oneway')
# x^0 = 1 ### x != 0
add_rule(pow_rules,
	F('^', Var('x', 'complex_nonzero'), 0),
	1,
	'pow', 'oneway')
# x^a * x^b = x^(a+b)
add_rule(pow_rules,
	AC0('*', F('^', Var('x', 'complex'), Var('a', 'complex')), F('^', Var('x', 'complex'), Var('b', 'complex'))),
	F('^', Var('x', 'complex'), AC0('+', Var('a', 'complex'), Var('b', 'complex'))),
	'pow')
"""
# (xy)^a = x^a * y^a
add_rule(
    pow_rules,
    F('^', AC0('*', Var('x', 'complex'), Var('y', 'complex')),
      Var('a', 'complex')),
示例#17
0
import rules


@rules.predicate
def can_read_program(user, program):
    return user.profile.agency.programs.filter(pk=program.id).exists()


rules.add_rule('can_read_program', can_read_program)
示例#18
0
from __future__ import absolute_import

from django.conf.urls import include, url

from curation import views
import rules
from .rules import *

rules.add_rule('is_accessible_by_dataset',is_accessible_by_dataset)
rules.add_rule('can_view_record', can_view_record)
rules.add_rule('can_edit_record', can_edit_record)
rules.add_rule('can_create_record', can_create_record)
rules.add_rule('can_delete_record', can_delete_record)

rules.add_rule('can_view_citation_field', can_view_citation_field & can_view_citation_record_using_id)
rules.add_rule('can_update_citation_field', can_update_citation_field & can_edit_citation_record_using_id)

rules.add_rule('can_view_authority_field', can_view_authority_field & can_view_authority_record_using_id)
rules.add_rule('can_update_authority_field', can_update_authority_field & can_edit_authority_record_using_id)

rules.add_rule('is_user_staff', is_user_staff)
rules.add_rule('is_user_superuser', is_user_superuser)
rules.add_rule('can_view_user_module', can_view_user_module)
rules.add_rule('can_update_user_module', can_update_user_module)

can_access_and_view = is_accessible_by_dataset & can_view_record
rules.add_rule('can_access_and_view', can_access_and_view)

can_access_view_edit = is_accessible_by_dataset & can_view_record & can_edit_record
rules.add_rule('can_access_view_edit', can_access_view_edit)
示例#19
0
@rules.predicate
def is_colleague_of(user1, user2):
    """
    True if two users are colleagues (i.e., both are students in the same
    classroom).
    """
    return NotImplemented


@rules.predicate
def is_teacher_of(teacher, student):
    """
    True if first user is a teacher in a course in which the second user is a
    student.
    """
    return NotImplemented


@rules.predicate
def is_student_of(user1, user2):
    """
    True if first user is a student in a course in which the second user is a
    teacher.
    """
    return NotImplemented


rules.add_perm('classrooms.view_classroom', is_registered)
rules.add_perm('classrooms.edit_classroom', is_owner)
rules.add_rule('classrooms.can_leave', is_student)
示例#20
0

rules.add_perm('community.can_create_event', can_create_community_event)


@rules.predicate
def is_last_owner(user, community_subscription):
    if not user or not community_subscription:
        return False

    return community_subscription.role == CommunitySubscription.ROLE_OWNER and \
        CommunitySubscription.objects.filter(
            community=community_subscription.community, role=CommunitySubscription.ROLE_OWNER).count() == 1


rules.add_rule('is_last_owner', is_last_owner)
rules.add_rule('can_unsubscribe', ~is_last_owner)


@rules.predicate
def can_set_owner(user, community):
    if not user or not community:
        return False

    try:
        return community.community_subscriptions.get(
            user=user).role == CommunitySubscription.ROLE_OWNER
    except CommunitySubscription.DoesNotExist:
        return False

示例#21
0
import rules


@rules.predicate
def can_read_eligibility(user, eligibility):
    return user.profile.agency.agencyeligibilityconfig_set.filter(
        eligibility=eligibility).exists()


rules.add_rule('can_read_eligibility', can_read_eligibility)
示例#22
0
import rules


@rules.predicate
def can_read_client(user, client):
    if user.is_superuser:
        return True

    return user == client.created_by


rules.add_rule('can_read_client', can_read_client)
示例#23
0
def addRules():
    rules.add_rule('1', MMT1_Commission_Check)
    rules.add_rule('2', MMT2_Commission_Check)
    rules.add_rule('3', Booking_Commission_Check)
    rules.add_rule('4', Razorpay_Commission_Check)
    rules.add_rule('5', Mswipe_Commission_Check)
    rules.add_rule('6', Atom_Commission_Check)
    rules.add_rule('7', Bank_Commission_Check)
示例#24
0
# Identification Risques
@rules.predicate
def is_risk_verifier(user, identificationrisque):
    if identificationrisque.get_class == 'ProcessusRisque':
        return is_process_risk_monitor(user, identificationrisque) \
               or is_process_risk_upper_mgt(user, identificationrisque)
    elif identificationrisque.get_class == 'ActiviteRisque':
        return is_activity_risk_monitor(user, identificationrisque) \
               or is_activity_risk_supervisor(user, identificationrisque) \
               or is_activity_risk_upper_mgt(user, identificationrisque)


# ------------rules------------
# Risques
rules.add_rule('change_risque', is_risk_creator)

# Identification Risques
rules.add_rule('verify_risk', is_risk_verifier)

# Processus
rules.add_rule('change_processus', is_process_upper_mgt)
rules.add_rule('delete_processus', is_process_upper_mgt)
rules.add_rule('add_activity_to_process',
               is_process_manager | is_process_upper_mgt)
rules.add_rule('add_process_data', is_process_manager | is_process_upper_mgt)
rules.add_rule('add_process_risk', rules.is_authenticated)

# Activités
rules.add_rule('change_activite',
               is_activity_supervisor | is_activity_upper_mgt)
示例#25
0
        if group in node.groups.all():
            return True

    # If built-in groups did not match we should check LDAP groups
    # LDAP groups can only be check by accessing user.ldap_user attribute
    if hasattr(settings, 'AUTH_LDAP_FIND_GROUP_PERMS'
               ) and settings.AUTH_LDAP_FIND_GROUP_PERMS:
        ldap_groups = Group.objects.filter(name__in=user.ldap_user.group_names)
        for group in ldap_groups:
            if group in node.groups.all():
                return True

    return False


# Check if user / group has inhereted permissions to a folder
@rules.predicate
def has_inherited_permission(user, node):
    # check if user / group specified directly on this node
    if has_direct_permission(user, node):
        return True

    # check if user / group is specified on any ancestor
    for n in node.get_ancestors(ascending=True):
        if has_direct_permission(user, n):
            return True


rules.add_rule('has_direct_permission', has_direct_permission)
rules.add_rule('has_inherited_permission', has_inherited_permission)
示例#26
0
import rules


@rules.predicate
def is_in_relation(boby, relation):
    if boby in (relation.inviter, relation.invited):
        return True
    return False


@rules.predicate
def is_admin(boby):
    return boby.is_staff or boby.is_superuser


rules.add_rule('can_change_bobyrelation', is_in_relation | is_admin)
rules.add_rule('can_upload_users', is_admin)

rules.add_perm('core.change_bobyrelation', is_in_relation | is_admin)
示例#27
0
from django.db import models
from django.contrib.auth.models import User
from rules.contrib.models import RulesModel
import rules


@rules.predicate
def is_alarm_creator(user, alarm):
    return alarm.creator == user


rules.add_rule('can_edit_alarm', is_alarm_creator)
rules.add_perm('alarm.edit_alarm', is_alarm_creator)


# Create your models here.
class Alarm(RulesModel):
    """Model representing an alarm"""
    title = models.CharField(max_length=200,
                             default='Alarm',
                             help_text='Enter a nice name for the alarm')
    creator = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
    sound = models.ForeignKey('Sound',
                              on_delete=models.CASCADE,
                              default=1,
                              help_text='Choose the sound for your alarm')
    time = models.DateTimeField(
        help_text=
        'Choose a date and time for your alarm that is BEFORE the current time'
    )
示例#28
0
import rules

is_faculty = rules.is_group_member('faculty')
can_access_media_files = is_faculty | rules.is_superuser
has_faculty_privilege = is_faculty | rules.is_superuser
can_access_unreleased_problems = has_faculty_privilege


@rules.predicate
def can_access_problem(user, problem):
    return problem.released or can_access_unreleased_problems(user)


@rules.predicate
def can_view_submit(user, submit):
    return has_faculty_privilege(user) or submit.user == user


rules.add_rule('is_faculty', is_faculty)
rules.add_rule('can_access_media_files', can_access_media_files)
rules.add_rule('can_access_unreleased_problems',
               can_access_unreleased_problems)
rules.add_rule('can_access_problem', can_access_problem)
rules.add_rule('can_view_submit', can_view_submit)
示例#29
0
import rules


# Predicates

@rules.predicate
def is_book_author(user, book):
    if not book:
        return False
    return book.author == user


@rules.predicate
def is_boss(user):
    return user.is_superuser


is_editor = rules.is_group_member('editors')

# Rules

rules.add_rule('change_book', is_book_author | is_editor)
rules.add_rule('delete_book', is_book_author)
rules.add_rule('create_book', is_boss)

# Permissions

rules.add_perm('testapp.change_book', is_book_author | is_editor)
rules.add_perm('testapp.delete_book', is_book_author)
示例#30
0
import rules


@rules.predicate
def can_read_client(user, client):
    if user.is_superuser:
        return True

    return user == client.created_by


rules.add_rule("can_read_client", can_read_client)
示例#31
0
# rules.py
import rules
# from rules import Predicate
from rules import predicates

from common import rules as common_rules

rules.add_rule('can_list_workspace', predicates.always_allow)

rules.add_rule('can_edit_workspace',
               common_rules.is_resource_owner | predicates.is_superuser)
rules.add_rule('can_delete_workspace',
               common_rules.is_resource_owner | predicates.is_superuser)
rules.add_rule(
    'can_read_workspace', common_rules.is_public
    | common_rules.is_resource_owner | predicates.is_superuser
    | (common_rules.is_internal &
       (common_rules.is_resource_shareduser
        | common_rules.is_resource_sharedgroupmember)))

rules.add_rule('analysis.list_workspace', predicates.always_allow)

rules.add_perm('analysis.change_workspace',
               common_rules.is_resource_owner | predicates.is_superuser)
rules.add_perm('analysis.delete_workspace',
               common_rules.is_resource_owner | predicates.is_superuser)
rules.add_perm(
    'analysis.read_workspace', common_rules.is_public
    | common_rules.is_resource_owner | predicates.is_superuser
    | (common_rules.is_internal &
       (common_rules.is_resource_shareduser
示例#32
0

@rules.predicate
def is_chapter_story_owner(user, chapter):
    return is_story_owner(user, chapter.parent)


@rules.predicate
def can_delete_story(user, story):
    return story.owner.pk == user.pk


@rules.predicate
def can_edit_comment(user, comment):
    return user.pk == comment.author.pk


@rules.predicate
def can_delete_comment(user, comment):
    return user.pk == comment.author.pk


rules.add_rule('can_edit_comment', can_edit_comment)
rules.add_rule('can_delete_comment', can_delete_comment)
rules.add_rule('can_view_story_draft', is_story_owner)
rules.add_rule('can_view_chapter_draft',
               is_chapter_author | is_chapter_story_owner)
rules.add_perm('stories.change_chapter', can_edit_chapter)
rules.add_perm('stories.change_story', can_edit_story)
rules.add_perm('comment.change_comment', can_edit_comment)
示例#33
0
文件: user.py 项目: dssg/marketplace
import operator

import rules
from rules.predicates import is_authenticated

from marketplace.domain import marketplace

rules.add_perm('user.is_same_user', operator.eq)

rules.add_perm('user.is_authenticated', is_authenticated)

rules.add_rule('user.is_site_staff', marketplace.user.is_site_staff)

rules.add_rule('volunteer.new_user_review', marketplace.user.is_site_staff)
示例#34
0
import rules
from . import predicates

# rules

rules.add_rule('edit_song', predicates.is_song_creator)
示例#35
0
import rules


@rules.predicate
def is_in_relation(boby, relation):
    if boby in (relation.inviter, relation.invited):
        return True
    return False


@rules.predicate
def is_admin(boby):
    return boby.is_staff or boby.is_superuser

rules.add_rule('can_change_bobyrelation', is_in_relation | is_admin)
rules.add_rule('can_upload_users', is_admin)

rules.add_perm('core.change_bobyrelation', is_in_relation | is_admin)
示例#36
0
文件: rules.py 项目: danjac/localhub
# Copyright (c) 2020 by Dan Jacob
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Rulesets for users
"""

# Third Party Libraries
import rules


@rules.predicate
def is_self(user, other):
    return user.is_authenticated and user == other


rules.add_rule("users.is_self", is_self)

rules.add_perm("users.change_user", is_self)
rules.add_perm("users.delete_user", is_self)
rules.add_perm("users.block_user", ~is_self & rules.is_authenticated)
rules.add_perm("users.follow_user", ~is_self & rules.is_authenticated)

rules.add_perm("users.follow_tag", rules.is_authenticated)
rules.add_perm("users.block_tag", rules.is_authenticated)
示例#37
0
import rules


@rules.predicate
def is_gm(user, business_unit):
    return business_unit.bu_manager == user


# rules
rules.add_rule('add_process_to_bu', is_gm)

# permissions
rules.add_perm('users.add_process_to_bu', is_gm)
rules.add_perm('users.add_businessunit', is_gm)




示例#38
0
import rules
from people.models import Classroom
from people.rules import is_admin, is_teacher, is_parent, is_scheduler, is_scheduler_in, is_teacher_in, is_teacher_in_classroom_of

@rules.predicate
def owns_worktimecommitment(user, worktimecommitment):
    return user.active_role() == PARENT and\
        user in worktimecommitment.child.parents

rules.add_rule('main.edit_worktimecommitment',
               is_admin | 
               is_scheduler_in |
               owns_worktimecommitment)

rules.add_perm('main.score_worktime_attendance',
               is_admin | 
               is_teacher_in)
示例#39
0
        pass  # yes, quantifiedcode, this is intentional
    return False

rules.add_perm('community.can_create_event', can_create_community_event)


@rules.predicate
def is_last_owner(user, community_subscription):
    if not user or not community_subscription:
        return False

    return community_subscription.role == CommunitySubscription.ROLE_OWNER and \
        CommunitySubscription.objects.filter(
            community=community_subscription.community, role=CommunitySubscription.ROLE_OWNER).count() == 1

rules.add_rule('is_last_owner', is_last_owner)
rules.add_rule('can_unsubscribe', ~is_last_owner)


@rules.predicate
def can_set_owner(user, community):
    if not user or not community:
        return False

    print('can_set_owner')
    try:
        return community.community_subscriptions.get(user=user).role == CommunitySubscription.ROLE_OWNER
    except CommunitySubscription.DoesNotExist:
        return False

rules.add_perm('community.can_set_owner', can_set_owner)