masquerade.py 1.86 KB
Newer Older
ichuang committed
1 2 3 4 5
'''
---------------------------------------- Masequerade ----------------------------------------
Allow course staff to see a student or staff view of courseware.
Which kind of view has been selected is stored in the session state.
'''
ichuang committed
6 7 8 9 10

import json
import logging

from django.http import HttpResponse
11
from django.conf import settings
ichuang committed
12 13 14

log = logging.getLogger(__name__)

15 16
MASQ_KEY = 'masquerade_identity'

ichuang committed
17

ichuang committed
18
def handle_ajax(request, marg):
ichuang committed
19 20 21
    '''
    Handle ajax call from "staff view" / "student view" toggle button
    '''
ichuang committed
22
    if marg == 'toggle':
23 24 25 26 27 28 29
        status = request.session.get(MASQ_KEY, '')
        if status is None or status in ['', 'staff']:
            status = 'student'
        else:
            status = 'staff'
        request.session[MASQ_KEY] = status
    return HttpResponse(json.dumps({'status': status}))
ichuang committed
30 31


32 33 34
def setup_masquerade(request, staff_access=False):
    '''
    Setup masquerade identity (allows staff to view courseware as either staff or student)
ichuang committed
35

36 37 38
    Uses request.session[MASQ_KEY] to store status of masquerading.
    Adds masquerade status to request.user, if masquerading active.
    Return string version of status of view (either 'staff' or 'student')
ichuang committed
39
    '''
40 41
    if request.user is None:
        return None
ichuang committed
42

43 44 45
    if not settings.MITX_FEATURES.get('ENABLE_MASQUERADE', False):
        return None

ichuang committed
46
    if not staff_access:  # can masquerade only if user has staff access to course
47
        return None
ichuang committed
48

49 50 51 52 53
    usertype = request.session.get(MASQ_KEY, '')
    if usertype is None or not usertype:
        request.session[MASQ_KEY] = 'staff'
        usertype = 'staff'

ichuang committed
54
    if usertype == 'student':
55
        request.user.masquerade_as_student = True
ichuang committed
56

57
    return usertype
ichuang committed
58 59


60
def is_masquerading_as_student(user):
ichuang committed
61 62 63
    '''
    Return True if user is masquerading as a student, False otherwise
    '''
64
    masq = getattr(user, 'masquerade_as_student', False)
65
    return masq==True