permissions.py 4.04 KB
Newer Older
Mike Chen committed
1 2 3
from .models import Role, Permission
from django.db.models.signals import post_save
from django.dispatch import receiver
4 5
from student.models import CourseEnrollment

Mike Chen committed
6
import logging
7
from util.cache import cache
8 9
from django.core import cache
cache = cache.get_cache('default')
10

11
def cached_has_permission(user, permission, course_id=None):
Mike Chen committed
12 13
    """
    Call has_permission if it's not cached. A change in a user's role or
14
    a role's permissions will only become effective after CACHE_LIFESPAN seconds.
Mike Chen committed
15 16
    """
    CACHE_LIFESPAN = 60
17 18 19 20
    key = "permission_%d_%s_%s" % (user.id, str(course_id), permission)
    val = cache.get(key, None)
    if val not in [True, False]:
        val = has_permission(user, permission, course_id=course_id)
Mike Chen committed
21
        cache.set(key, val, CACHE_LIFESPAN)
22 23 24
    return val

def has_permission(user, permission, course_id=None):
25 26 27
    for role in user.roles.filter(course_id=course_id):
        if role.has_permission(permission):
            return True
Mike Chen committed
28 29 30
    return False


31 32 33
CONDITIONS = ['is_open', 'is_author']
def check_condition(user, condition, course_id, data):
    def check_open(user, condition, course_id, data):
Rocky Duan committed
34 35 36 37
        try:
            return data and not data['content']['closed']
        except KeyError:
            return False
Mike Chen committed
38

39
    def check_author(user, condition, course_id, data):
Rocky Duan committed
40 41 42 43
        try:
            return data and data['content']['user_id'] == str(user.id)
        except KeyError:
            return False
Mike Chen committed
44

45 46 47 48
    handlers = {
        'is_open'      : check_open,
        'is_author'    : check_author,
    }
Mike Chen committed
49

50
    return handlers[condition](user, condition, course_id, data)
51

52 53

def check_conditions_permissions(user, permissions, course_id, **kwargs):
54 55
    """
    Accepts a list of permissions and proceed if any of the permission is valid.
56
    Note that ["can_view", "can_edit"] will proceed if the user has either
57 58
    "can_view" or "can_edit" permission. To use AND operator in between, wrap them in
    a list.
59
    """
60 61 62 63 64

    def test(user, per, operator="or"):
        if isinstance(per, basestring):
            if per in CONDITIONS:
                return check_condition(user, per, course_id, kwargs)
65
            return cached_has_permission(user, per, course_id=course_id)
66 67
        elif isinstance(per, list) and operator in ["and", "or"]:
            results = [test(user, x, operator="and") for x in per]
68 69 70 71 72
            if operator == "or":
                return True in results
            elif operator == "and":
                return not False in results

73
    return test(user, permissions, operator="or")
74 75 76


VIEW_PERMISSIONS = {
77 78
    'update_thread'     :       ['edit_content', ['update_thread', 'is_open', 'is_author']],
    'create_comment'    :       [["create_comment", "is_open"]],
79
    'delete_thread'     :       ['delete_thread', ['update_thread', 'is_author']],
80
    'update_comment'    :       ['edit_content', ['update_comment', 'is_open', 'is_author']],
81 82 83
    'endorse_comment'   :       ['endorse_comment'],
    'openclose_thread'  :       ['openclose_thread'],
    'create_sub_comment':       [['create_sub_comment', 'is_open']],
84
    'delete_comment'    :       ['delete_comment', ['update_comment', 'is_open', 'is_author']],
85 86 87 88 89
    'vote_for_comment'  :       [['vote', 'is_open']],
    'undo_vote_for_comment':    [['unvote', 'is_open']],
    'vote_for_thread'   :       [['vote', 'is_open']],
    'undo_vote_for_thread':     [['unvote', 'is_open']],
    'follow_thread'     :       ['follow_thread'],
90
    'follow_commentable':       ['follow_commentable'],
91 92 93 94 95
    'follow_user'       :       ['follow_user'],
    'unfollow_thread'   :       ['unfollow_thread'],
    'unfollow_commentable':     ['unfollow_commentable'],
    'unfollow_user'     :       ['unfollow_user'],
    'create_thread'     :       ['create_thread'],
Rocky Duan committed
96
    'update_moderator_status' : ['manage_moderator'],
97 98
}

99 100

def check_permissions_by_view(user, course_id, content, name):
101 102 103 104
    try:
        p = VIEW_PERMISSIONS[name]
    except KeyError:
        logging.warning("Permission for view named %s does not exist in permissions.py" % name)
105
    return check_conditions_permissions(user, p, course_id, content=content)