permissions.py 4.74 KB
Newer Older
1 2 3 4
"""
Module for checking permissions with the comment_client backend
"""

Mike Chen committed
5
import logging
6
from types import NoneType
7
from django.core import cache
8
from lms.lib.comment_client import Thread
9
from opaque_keys.edx.keys import CourseKey
10 11 12

CACHE = cache.get_cache('default')
CACHE_LIFESPAN = 60
13

Calen Pennington committed
14

15
def cached_has_permission(user, permission, course_id=None):
Mike Chen committed
16 17
    """
    Call has_permission if it's not cached. A change in a user's role or
18
    a role's permissions will only become effective after CACHE_LIFESPAN seconds.
Mike Chen committed
19
    """
20
    assert isinstance(course_id, (NoneType, CourseKey))
21 22
    key = u"permission_{user_id:d}_{course_id}_{permission}".format(
        user_id=user.id, course_id=course_id, permission=permission)
23
    val = CACHE.get(key, None)
24 25
    if val not in [True, False]:
        val = has_permission(user, permission, course_id=course_id)
26
        CACHE.set(key, val, CACHE_LIFESPAN)
27 28
    return val

Calen Pennington committed
29

30
def has_permission(user, permission, course_id=None):
31
    assert isinstance(course_id, (NoneType, CourseKey))
32 33 34
    for role in user.roles.filter(course_id=course_id):
        if role.has_permission(permission):
            return True
Mike Chen committed
35 36 37
    return False


38
CONDITIONS = ['is_open', 'is_author', 'is_question_author']
Calen Pennington committed
39 40


41 42
def _check_condition(user, condition, content):
    def check_open(user, content):
Rocky Duan committed
43
        try:
44
            return content and not content['closed']
Rocky Duan committed
45 46
        except KeyError:
            return False
Mike Chen committed
47

48
    def check_author(user, content):
Rocky Duan committed
49
        try:
50
            return content and content['user_id'] == str(user.id)
Rocky Duan committed
51 52
        except KeyError:
            return False
Mike Chen committed
53

54 55 56 57 58 59 60 61 62 63 64 65
    def check_question_author(user, content):
        if not content:
            return False
        try:
            if content["type"] == "thread":
                return content["thread_type"] == "question" and content["user_id"] == str(user.id)
            else:
                # N.B. This will trigger a comments service query
                return check_question_author(user, Thread(id=content["thread_id"]).to_dict())
        except KeyError:
            return False

66
    handlers = {
Calen Pennington committed
67 68
        'is_open': check_open,
        'is_author': check_author,
69
        'is_question_author': check_question_author,
70
    }
Mike Chen committed
71

72
    return handlers[condition](user, content)
73

74

75
def _check_conditions_permissions(user, permissions, course_id, content):
76 77
    """
    Accepts a list of permissions and proceed if any of the permission is valid.
78
    Note that ["can_view", "can_edit"] will proceed if the user has either
79 80
    "can_view" or "can_edit" permission. To use AND operator in between, wrap them in
    a list.
81
    """
82 83 84 85

    def test(user, per, operator="or"):
        if isinstance(per, basestring):
            if per in CONDITIONS:
86
                return _check_condition(user, per, content)
87
            return cached_has_permission(user, per, course_id=course_id)
88 89
        elif isinstance(per, list) and operator in ["and", "or"]:
            results = [test(user, x, operator="and") for x in per]
90 91 92
            if operator == "or":
                return True in results
            elif operator == "and":
David Baumgold committed
93
                return False not in results
Kevin Chugh committed
94
    return test(user, permissions, operator="or")
95 96 97


VIEW_PERMISSIONS = {
98 99 100 101
    'update_thread': ['edit_content', ['update_thread', 'is_open', 'is_author']],
    'create_comment': [["create_comment", "is_open"]],
    'delete_thread': ['delete_thread', ['update_thread', 'is_author']],
    'update_comment': ['edit_content', ['update_comment', 'is_open', 'is_author']],
102
    'endorse_comment': ['endorse_comment', 'is_question_author'],
103 104 105 106 107 108
    'openclose_thread': ['openclose_thread'],
    'create_sub_comment': [['create_sub_comment', 'is_open']],
    'delete_comment': ['delete_comment', ['update_comment', 'is_open', 'is_author']],
    'vote_for_comment': [['vote', 'is_open']],
    'undo_vote_for_comment': [['unvote', 'is_open']],
    'vote_for_thread': [['vote', 'is_open']],
109 110 111 112
    'flag_abuse_for_thread': ['vote'],
    'un_flag_abuse_for_thread': ['vote'],
    'flag_abuse_for_comment': ['vote'],
    'un_flag_abuse_for_comment': ['vote'],
113
    'undo_vote_for_thread': [['unvote', 'is_open']],
114 115
    'pin_thread': ['openclose_thread'],
    'un_pin_thread': ['openclose_thread'],
116 117 118 119 120 121 122
    'follow_thread': ['follow_thread'],
    'follow_commentable': ['follow_commentable'],
    'follow_user': ['follow_user'],
    'unfollow_thread': ['unfollow_thread'],
    'unfollow_commentable': ['unfollow_commentable'],
    'unfollow_user': ['unfollow_user'],
    'create_thread': ['create_thread'],
123 124
}

125 126

def check_permissions_by_view(user, course_id, content, name):
127
    assert isinstance(course_id, CourseKey)
128 129 130 131
    try:
        p = VIEW_PERMISSIONS[name]
    except KeyError:
        logging.warning("Permission for view named %s does not exist in permissions.py" % name)
132
    return _check_conditions_permissions(user, p, course_id, content)