access.py 25.6 KB
Newer Older
1 2
"""
This file contains (or should), all access control logic for the courseware.
3
Ideally, it will be the only place that needs to know about any special settings
4 5 6 7 8 9 10 11
like DISABLE_START_DATES.

Note: The access control logic in this file does NOT check for enrollment in
  a course.  It is expected that higher layers check for enrollment so we
  don't have to hit the enrollments table on every module load.

  If enrollment is to be checked, use get_course_with_access in courseware.courses.
  It is a wrapper around has_access that additionally checks for enrollment.
12
"""
13
import logging
14
from datetime import datetime, timedelta
15
import pytz
16 17

from django.conf import settings
Ned Batchelder committed
18
from django.contrib.auth.models import AnonymousUser
19 20 21
from django.utils.timezone import UTC

from opaque_keys.edx.keys import CourseKey, UsageKey
22

23
from xblock.core import XBlock
24

25 26 27
from xmodule.course_module import (
    CourseDescriptor, CATALOG_VISIBILITY_CATALOG_AND_ABOUT,
    CATALOG_VISIBILITY_ABOUT)
28
from xmodule.error_module import ErrorDescriptor
29
from xmodule.x_module import XModule, DEPRECATION_VSCOMPAT_EVENT
30
from xmodule.split_test_module import get_split_user_partitions
31
from xmodule.partitions.partitions import NoSuchUserPartitionError, NoSuchUserPartitionGroupError
32
from xmodule.util.django import get_current_request_hostname
33

34
from external_auth.models import ExternalAuthMap
35
from courseware.masquerade import get_masquerade_role, is_masquerading_as_student
36
from student import auth
37
from student.models import CourseEnrollmentAllowed
38
from student.roles import (
39 40 41
    GlobalStaff, CourseStaffRole, CourseInstructorRole,
    OrgStaffRole, OrgInstructorRole, CourseBetaTesterRole
)
42 43 44 45
from util.milestones_helpers import (
    get_pre_requisite_courses_not_completed,
    any_unfulfilled_milestones,
)
cewing committed
46
from ccx_keys.locator import CCXLocator
47

48 49
import dogstats_wrapper as dog_stats_api

50
DEBUG_ACCESS = False
51 52 53

log = logging.getLogger(__name__)

54

55 56 57 58 59
def debug(*args, **kwargs):
    # to avoid overly verbose output, this is off by default
    if DEBUG_ACCESS:
        log.debug(*args, **kwargs)

60

61
def has_access(user, action, obj, course_key=None):
62 63 64 65 66 67
    """
    Check whether a user has the access to do action on obj.  Handles any magic
    switching based on various settings.

    Things this module understands:
    - start dates for modules
68
    - visible_to_staff_only for modules
69
    - DISABLE_START_DATES
70
    - different access for instructor, staff, course staff, and students.
71
    - mobile_available flag for course modules
72

73 74
    user: a Django user object. May be anonymous. If none is passed,
                    anonymous is assumed
75

76 77
    obj: The object to check access for.  A module, descriptor, location, or
                    certain special strings (e.g. 'global')
78 79 80 81 82 83

    action: A string specifying the action that the client is trying to perform.

    actions depend on the obj type, but include e.g. 'enroll' for courses.  See the
    type-specific functions below for the known actions for that type.

84
    course_key: A course_key specifying which course run this access is for.
85 86 87
        Required when accessing anything other than a CourseDescriptor, 'global',
        or a location with category 'course'

88 89 90
    Returns a bool.  It is up to the caller to actually deny access in a way
    that makes sense in context.
    """
91 92 93 94
    # Just in case user is passed in as None, make them anonymous
    if not user:
        user = AnonymousUser()

cewing committed
95 96 97
    if isinstance(course_key, CCXLocator):
        course_key = course_key.to_course_locator()

98 99 100
    # delegate the work to type-specific functions.
    # (start with more specific types, then get more general)
    if isinstance(obj, CourseDescriptor):
101
        return _has_access_course_desc(user, action, obj)
102

103
    if isinstance(obj, ErrorDescriptor):
104
        return _has_access_error_desc(user, action, obj, course_key)
105

106
    if isinstance(obj, XModule):
107
        return _has_access_xmodule(user, action, obj, course_key)
108

109 110
    # NOTE: any descriptor access checkers need to go above this
    if isinstance(obj, XBlock):
111
        return _has_access_descriptor(user, action, obj, course_key)
112

113 114 115
    if isinstance(obj, CCXLocator):
        return _has_access_ccx_key(user, action, obj)

116 117 118
    if isinstance(obj, CourseKey):
        return _has_access_course_key(user, action, obj)

119
    if isinstance(obj, UsageKey):
120
        return _has_access_location(user, action, obj, course_key)
121

122
    if isinstance(obj, basestring):
stv committed
123
        return _has_access_string(user, action, obj)
124

125 126
    # Passing an unknown object here is a coding error, so rather than
    # returning a default, complain.
127
    raise TypeError("Unknown object type in has_access(): '{0}'"
128 129
                    .format(type(obj)))

130 131

# ================ Implementation helpers ================================
132
def _has_access_course_desc(user, action, course):
133 134 135 136 137 138
    """
    Check if user has access to a course descriptor.

    Valid actions:

    'load' -- load the courseware, see inside the course
139
    'load_forum' -- can load and contribute to the forums (one access level for now)
140
    'load_mobile' -- can load from a mobile context
141 142 143 144
    'enroll' -- enroll.  Checks for enrollment window,
                  ACCESS_REQUIRE_STAFF_FOR_COURSE,
    'see_exists' -- can see that the course exists.
    'staff' -- staff access to course.
145 146
    'see_in_catalog' -- user is able to see the course listed in the course catalog.
    'see_about_page' -- user is able to see the course about page.
147 148
    """
    def can_load():
Calen Pennington committed
149 150
        """
        Can this user load this course?
151 152

        NOTE: this is not checking whether user is actually enrolled in the course.
Calen Pennington committed
153
        """
154
        # delegate to generic descriptor check to check start dates
155
        return _has_access_descriptor(user, 'load', course, course.id)
156

157 158 159 160 161 162 163 164
    def can_load_mobile():
        """
        Can this user access this course from a mobile device?
        """
        return (
            # check start date
            can_load() and
            # check mobile_available flag
165 166
            is_mobile_available_for_user(user, course) and
            (
167
                # either is a staff user or
168
                _has_staff_access_to_descriptor(user, course, course.id) or
169 170
                # check for unfulfilled milestones
                not any_unfulfilled_milestones(course.id, user.id)
171
            )
172 173
        )

174 175
    def can_enroll():
        """
176 177
        First check if restriction of enrollment by login method is enabled, both
            globally and by the course.
Calen Pennington committed
178
        If it is, then the user must pass the criterion set by the course, e.g. that ExternalAuthMap
179 180 181
            was set by 'shib:https://idp.stanford.edu/", in addition to requirements below.
        Rest of requirements:
        (CourseEnrollmentAllowed always overrides)
182
          or
183
        (staff can always enroll)
184 185 186
          or
        Enrollment can only happen in the course enrollment period, if one exists, and
        course is not invitation only.
187
        """
188

189
        # if using registration method to restrict (say shibboleth)
190
        if settings.FEATURES.get('RESTRICT_ENROLL_BY_REG_METHOD') and course.enrollment_domain:
191
            if user is not None and user.is_authenticated() and \
stv committed
192
                    ExternalAuthMap.objects.filter(user=user, external_domain=course.enrollment_domain):
193 194 195 196 197
                debug("Allow: external_auth of " + course.enrollment_domain)
                reg_method_ok = True
            else:
                reg_method_ok = False
        else:
198
            reg_method_ok = True  # if not using this access check, it's always OK.
199

200
        now = datetime.now(UTC())
201 202
        start = course.enrollment_start or datetime.min.replace(tzinfo=pytz.UTC)
        end = course.enrollment_end or datetime.max.replace(tzinfo=pytz.UTC)
203

204 205 206 207
        # if user is in CourseEnrollmentAllowed with right course key then can also enroll
        # (note that course.id actually points to a CourseKey)
        # (the filter call uses course_id= since that's the legacy database schema)
        # (sorry that it's confusing :( )
208
        if user is not None and user.is_authenticated() and CourseEnrollmentAllowed:
209 210
            if CourseEnrollmentAllowed.objects.filter(email=user.email, course_id=course.id):
                return True
211

212 213 214 215 216 217 218 219 220 221 222
        if _has_staff_access_to_descriptor(user, course, course.id):
            return True

        # Invitation_only doesn't apply to CourseEnrollmentAllowed or has_staff_access_access
        if course.invitation_only:
            debug("Deny: invitation only")
            return False

        if reg_method_ok and start < now < end:
            debug("Allow: in enrollment period")
            return True
223 224 225 226 227 228 229 230 231 232 233 234 235

    def see_exists():
        """
        Can see if can enroll, but also if can load it: if user enrolled in a course and now
        it's past the enrollment period, they should still see it.

        TODO (vshnayder): This means that courses with limited enrollment periods will not appear
        to non-staff visitors after the enrollment period is over.  If this is not what we want, will
        need to change this logic.
        """
        # VS[compat] -- this setting should go away once all courses have
        # properly configured enrollment_start times (if course should be
        # staff-only, set enrollment_start far in the future.)
236
        if settings.FEATURES.get('ACCESS_REQUIRE_STAFF_FOR_COURSE'):
237 238 239 240 241 242 243 244
            dog_stats_api.increment(
                DEPRECATION_VSCOMPAT_EVENT,
                tags=(
                    "location:has_access_course_desc_see_exists",
                    u"course:{}".format(course),
                )
            )

245 246
            # if this feature is on, only allow courses that have ispublic set to be
            # seen by non-staff
Calen Pennington committed
247
            if course.ispublic:
248
                debug("Allow: ACCESS_REQUIRE_STAFF_FOR_COURSE and ispublic")
249
                return True
250
            return _has_staff_access_to_descriptor(user, course, course.id)
251 252 253

        return can_enroll() or can_load()

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
    def can_see_in_catalog():
        """
        Implements the "can see course in catalog" logic if a course should be visible in the main course catalog
        In this case we use the catalog_visibility property on the course descriptor
        but also allow course staff to see this.
        """
        return (
            course.catalog_visibility == CATALOG_VISIBILITY_CATALOG_AND_ABOUT or
            _has_staff_access_to_descriptor(user, course, course.id)
        )

    def can_see_about_page():
        """
        Implements the "can see course about page" logic if a course about page should be visible
        In this case we use the catalog_visibility property on the course descriptor
        but also allow course staff to see this.
        """
        return (
            course.catalog_visibility == CATALOG_VISIBILITY_CATALOG_AND_ABOUT or
            course.catalog_visibility == CATALOG_VISIBILITY_ABOUT or
            _has_staff_access_to_descriptor(user, course, course.id)
        )

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
    def can_view_courseware_with_prerequisites():  # pylint: disable=invalid-name
        """
        Checks if prerequisite courses feature is enabled and course has prerequisites
        and user is neither staff nor anonymous then it returns False if user has not
        passed prerequisite courses otherwise return True.
        """
        if settings.FEATURES['ENABLE_PREREQUISITE_COURSES'] \
                and not _has_staff_access_to_descriptor(user, course, course.id) \
                and course.pre_requisite_courses \
                and not user.is_anonymous() \
                and get_pre_requisite_courses_not_completed(user, [course.id]):
            return False
        else:
            return True

292 293
    checkers = {
        'load': can_load,
294
        'view_courseware_with_prerequisites': can_view_courseware_with_prerequisites,
295
        'load_mobile': can_load_mobile,
296 297
        'enroll': can_enroll,
        'see_exists': see_exists,
298 299
        'staff': lambda: _has_staff_access_to_descriptor(user, course, course.id),
        'instructor': lambda: _has_instructor_access_to_descriptor(user, course, course.id),
300 301
        'see_in_catalog': can_see_in_catalog,
        'see_about_page': can_see_about_page,
302
    }
303 304 305

    return _dispatch(checkers, action, user, course)

306

307
def _has_access_error_desc(user, action, descriptor, course_key):
308 309 310 311 312 313 314 315
    """
    Only staff should see error descriptors.

    Valid actions:
    'load' -- load this descriptor, showing it to the user.
    'staff' -- staff access to descriptor.
    """
    def check_for_staff():
316
        return _has_staff_access_to_descriptor(user, descriptor, course_key)
317 318 319

    checkers = {
        'load': check_for_staff,
320 321
        'staff': check_for_staff,
        'instructor': lambda: _has_instructor_access_to_descriptor(user, descriptor, course_key)
322
    }
323 324 325 326

    return _dispatch(checkers, action, user, descriptor)


327 328 329 330 331
def _has_group_access(descriptor, user, course_key):
    """
    This function returns a boolean indicating whether or not `user` has
    sufficient group memberships to "load" a block (the `descriptor`)
    """
332 333 334 335
    if len(descriptor.user_partitions) == len(get_split_user_partitions(descriptor.user_partitions)):
        # Short-circuit the process, since there are no defined user partitions that are not
        # user_partitions used by the split_test module. The split_test module handles its own access
        # via updating the children of the split_test module.
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
        return True

    # use merged_group_access which takes group access on the block's
    # parents / ancestors into account
    merged_access = descriptor.merged_group_access
    # check for False in merged_access, which indicates that at least one
    # partition's group list excludes all students.
    if False in merged_access.values():
        log.warning("Group access check excludes all students, access will be denied.", exc_info=True)
        return False

    # resolve the partition IDs in group_access to actual
    # partition objects, skipping those which contain empty group directives.
    # if a referenced partition could not be found, access will be denied.
    try:
        partitions = [
            descriptor._get_user_partition(partition_id)  # pylint:disable=protected-access
            for partition_id, group_ids in merged_access.items()
            if group_ids is not None
        ]
    except NoSuchUserPartitionError:
        log.warning("Error looking up user partition, access will be denied.", exc_info=True)
        return False

    # next resolve the group IDs specified within each partition
    partition_groups = []
    try:
        for partition in partitions:
            groups = [
                partition.get_group(group_id)
                for group_id in merged_access[partition.id]
            ]
            if groups:
                partition_groups.append((partition, groups))
    except NoSuchUserPartitionGroupError:
        log.warning("Error looking up referenced user partition group, access will be denied.", exc_info=True)
        return False

    # look up the user's group for each partition
    user_groups = {}
    for partition, groups in partition_groups:
        user_groups[partition.id] = partition.scheme.get_group_for_user(
            course_key,
            user,
            partition,
        )

    # finally: check that the user has a satisfactory group assignment
    # for each partition.
Andy Armstrong committed
385
    if not all(user_groups.get(partition.id) in groups for partition, groups in partition_groups):
386 387 388 389 390 391
        return False

    # all checks passed.
    return True


392
def _has_access_descriptor(user, action, descriptor, course_key=None):
393 394 395 396 397 398 399 400 401 402 403 404
    """
    Check if user has access to this descriptor.

    Valid actions:
    'load' -- load this descriptor, showing it to the user.
    'staff' -- staff access to descriptor.

    NOTE: This is the fallback logic for descriptors that don't have custom policy
    (e.g. courses).  If you call this method directly instead of going through
    has_access(), it will not do the right thing.
    """
    def can_load():
405 406 407 408 409 410
        """
        NOTE: This does not check that the student is enrolled in the course
        that contains this module.  We may or may not want to allow non-enrolled
        students to see modules.  If not, views should check the course, so we
        don't have to hit the enrollments table on every module load.
        """
411 412 413
        if descriptor.visible_to_staff_only and not _has_staff_access_to_descriptor(user, descriptor, course_key):
            return False

414 415 416 417 418 419
        # enforce group access
        if not _has_group_access(descriptor, user, course_key):
            # if group_access check failed, deny access unless the requestor is staff,
            # in which case immediately grant access.
            return _has_staff_access_to_descriptor(user, descriptor, course_key)

420
        # If start dates are off, can always load
421
        if settings.FEATURES['DISABLE_START_DATES'] and not is_masquerading_as_student(user, course_key):
422
            debug("Allow: DISABLE_START_DATES")
423 424 425
            return True

        # Check start date
426
        if 'detached' not in descriptor._class_tags and descriptor.start is not None:
427
            now = datetime.now(UTC())
428 429 430
            effective_start = _adjust_start_date_for_beta_testers(
                user,
                descriptor,
431
                course_key=course_key
432
            )
433
            if in_preview_mode() or now > effective_start:
434
                # after start date, everyone can see it
435
                debug("Allow: now > effective start date")
436 437
                return True
            # otherwise, need staff access
438
            return _has_staff_access_to_descriptor(user, descriptor, course_key)
439 440

        # No start date, so can always load.
441
        debug("Allow: no start date")
442 443 444 445
        return True

    checkers = {
        'load': can_load,
446 447 448
        'staff': lambda: _has_staff_access_to_descriptor(user, descriptor, course_key),
        'instructor': lambda: _has_instructor_access_to_descriptor(user, descriptor, course_key)
    }
449 450 451 452

    return _dispatch(checkers, action, user, descriptor)


453
def _has_access_xmodule(user, action, xmodule, course_key):
454 455 456 457 458 459 460
    """
    Check if user has access to this xmodule.

    Valid actions:
      - same as the valid actions for xmodule.descriptor
    """
    # Delegate to the descriptor
461
    return has_access(user, action, xmodule.descriptor, course_key)
462 463


464
def _has_access_location(user, action, location, course_key):
465 466 467 468 469 470 471 472 473 474 475
    """
    Check if user has access to this location.

    Valid actions:
    'staff' : True if the user has staff access to this location

    NOTE: if you add other actions, make sure that

     has_access(user, location, action) == has_access(user, get_item(location), action)
    """
    checkers = {
476 477
        'staff': lambda: _has_staff_access_to_location(user, location, course_key)
    }
478 479 480 481

    return _dispatch(checkers, action, user, location)


482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
def _has_access_course_key(user, action, course_key):
    """
    Check if user has access to the course with this course_key

    Valid actions:
    'staff' : True if the user has staff access to this location
    'instructor' : True if the user has staff access to this location
    """
    checkers = {
        'staff': lambda: _has_staff_access_to_location(user, None, course_key),
        'instructor': lambda: _has_instructor_access_to_location(user, None, course_key),
    }

    return _dispatch(checkers, action, user, course_key)

497

498
def _has_access_ccx_key(user, action, ccx_key):
499 500 501 502 503
    """Check if user has access to the course for this ccx_key

    Delegates checking to _has_access_course_key
    Valid actions: same as for that function
    """
504 505 506
    course_key = ccx_key.to_course_locator()
    return _has_access_course_key(user, action, course_key)

507

stv committed
508
def _has_access_string(user, action, perm):
509 510 511 512 513 514 515 516 517 518 519 520 521 522
    """
    Check if user has certain special access, specified as string.  Valid strings:

    'global'

    Valid actions:

    'staff' -- global staff access.
    """

    def check_staff():
        if perm != 'global':
            debug("Deny: invalid permission '%s'", perm)
            return False
523
        return GlobalStaff().has_user(user)
524 525 526

    checkers = {
        'staff': check_staff
527
    }
528 529 530 531

    return _dispatch(checkers, action, user, perm)


532 533 534 535 536 537 538 539 540 541 542 543
#####  Internal helper methods below

def _dispatch(table, action, user, obj):
    """
    Helper: call table[action], raising a nice pretty error if there is no such key.

    user and object passed in only for error messages and debugging
    """
    if action in table:
        result = table[action]()
        debug("%s user %s, object %s, action %s",
              'ALLOWED' if result else 'DENIED',
544
              user,
545
              obj.location.to_deprecated_string() if isinstance(obj, XBlock) else str(obj),
546
              action)
547 548
        return result

549
    raise ValueError(u"Unknown action for object type '{0}': '{1}'".format(
550 551
        type(obj), action))

552

553
def _adjust_start_date_for_beta_testers(user, descriptor, course_key=None):  # pylint: disable=invalid-name
554 555 556 557 558 559 560 561 562 563
    """
    If user is in a beta test group, adjust the start date by the appropriate number of
    days.

    Arguments:
       user: A django user.  May be anonymous.
       descriptor: the XModuleDescriptor the user is trying to get access to, with a
       non-None start date.

    Returns:
564
        A datetime.  Either the same as start, or earlier for beta testers.
565 566 567 568 569 570 571

    NOTE: number of days to adjust should be cached to avoid looking it up thousands of
    times per query.

    NOTE: For now, this function assumes that the descriptor's location is in the course
    the user is looking at.  Once we have proper usages and definitions per the XBlock
    design, this should use the course the usage is in.
572

573
    NOTE: If testing manually, make sure FEATURES['DISABLE_START_DATES'] = False
574
    in envs/dev.py!
575
    """
Calen Pennington committed
576
    if descriptor.days_early_for_beta is None:
577
        # bail early if no beta testing is set up
Calen Pennington committed
578
        return descriptor.start
579

580
    if CourseBetaTesterRole(course_key).has_user(user):
581
        debug("Adjust start time: user in beta role for %s", descriptor)
Calen Pennington committed
582 583
        delta = timedelta(descriptor.days_early_for_beta)
        effective = descriptor.start - delta
584
        return effective
585

Calen Pennington committed
586
    return descriptor.start
587

Calen Pennington committed
588

589 590 591 592
def _has_instructor_access_to_location(user, location, course_key=None):
    if course_key is None:
        course_key = location.course_key
    return _has_access_to_course(user, 'instructor', course_key)
593 594


595
def _has_staff_access_to_location(user, location, course_key=None):
596 597 598
    if course_key is None:
        course_key = location.course_key
    return _has_access_to_course(user, 'staff', course_key)
599

600

601
def _has_access_to_course(user, access_level, course_key):
602 603
    '''
    Returns True if the given user has access_level (= staff or
604 605 606
    instructor) access to the course with the given course_key.
    This ensures the user is authenticated and checks if global staff or has
    staff / instructor access.
607 608

    access_level = string, either "staff" or "instructor"
609 610
    '''
    if user is None or (not user.is_authenticated()):
611
        debug("Deny: no user or anon user")
612
        return False
613

614
    if is_masquerading_as_student(user, course_key):
615 616
        return False

617
    if GlobalStaff().has_user(user):
618
        debug("Allow: user.is_staff")
619 620
        return True

621
    if access_level not in ('staff', 'instructor'):
622
        log.debug("Error in access._has_access_to_course access_level=%s unknown", access_level)
623 624
        debug("Deny: unknown access level")
        return False
625

626
    staff_access = (
627 628
        CourseStaffRole(course_key).has_user(user) or
        OrgStaffRole(course_key.org).has_user(user)
629 630 631 632 633 634 635
    )

    if staff_access and access_level == 'staff':
        debug("Allow: user has course staff access")
        return True

    instructor_access = (
636 637
        CourseInstructorRole(course_key).has_user(user) or
        OrgInstructorRole(course_key.org).has_user(user)
638 639 640 641 642 643 644
    )

    if instructor_access and access_level in ('staff', 'instructor'):
        debug("Allow: user has course instructor access")
        return True

    debug("Deny: user did not have correct access")
645 646
    return False

647

648
def _has_instructor_access_to_descriptor(user, descriptor, course_key):  # pylint: disable=invalid-name
649 650 651 652 653
    """Helper method that checks whether the user has staff access to
    the course of the location.

    descriptor: something that has a location attribute
    """
654
    return _has_instructor_access_to_location(user, descriptor.location, course_key)
655

656

657
def _has_staff_access_to_descriptor(user, descriptor, course_key):
658 659 660
    """Helper method that checks whether the user has staff access to
    the course of the location.

661
    descriptor: something that has a location attribute
662
    """
663
    return _has_staff_access_to_location(user, descriptor.location, course_key)
664 665


666
def is_mobile_available_for_user(user, descriptor):
667 668 669 670 671
    """
    Returns whether the given course is mobile_available for the given user.
    Checks:
        mobile_available flag on the course
        Beta User and staff access overrides the mobile_available flag
672 673
    Arguments:
        descriptor (CourseDescriptor|CourseOverview): course or overview of course in question
674 675
    """
    return (
676 677 678
        descriptor.mobile_available or
        auth.has_access(user, CourseBetaTesterRole(descriptor.id)) or
        _has_staff_access_to_descriptor(user, descriptor, descriptor.id)
679 680 681
    )


682
def get_user_role(user, course_key):
683 684 685 686
    """
    Return corresponding string if user has staff, instructor or student
    course role in LMS.
    """
687 688 689
    role = get_masquerade_role(user, course_key)
    if role:
        return role
690
    elif has_access(user, 'instructor', course_key):
691
        return 'instructor'
692
    elif has_access(user, 'staff', course_key):
693 694 695
        return 'staff'
    else:
        return 'student'
696 697 698 699 700 701 702 703


def in_preview_mode():
    """
    Returns whether the user is in preview mode or not.
    """
    hostname = get_current_request_hostname()
    return hostname and settings.PREVIEW_DOMAIN in hostname.split('.')