access.py 29.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
15

16
from ccx_keys.locator import CCXLocator
17 18
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
19
from pytz import UTC
20 21 22
from opaque_keys.edx.keys import CourseKey, UsageKey
from xblock.core import XBlock

23 24 25 26 27
from courseware.access_response import (
    MilestoneAccessError,
    MobileAvailabilityError,
    VisibilityError,
)
28 29 30 31 32 33
from courseware.access_utils import (
    ACCESS_DENIED,
    ACCESS_GRANTED,
    adjust_start_date,
    check_start_date,
    debug,
34 35
    in_preview_mode,
    check_course_open_for_learner,
36
)
37
from courseware.masquerade import get_masquerade_role, is_masquerading_as_student
38 39 40
from lms.djangoapps.ccx.custom_exception import CCXLocatorValidationException
from lms.djangoapps.ccx.models import CustomCourseForEdX
from mobile_api.models import IgnoreMobileAvailableFlagConfig
41 42
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from openedx.core.djangoapps.external_auth.models import ExternalAuthMap
43
from student import auth
44
from student.models import CourseEnrollmentAllowed
45
from student.roles import (
46
    CourseBetaTesterRole,
47
    CourseCcxCoachRole,
48 49 50 51 52
    CourseInstructorRole,
    CourseStaffRole,
    GlobalStaff,
    OrgInstructorRole,
    OrgStaffRole,
53
    SupportStaffRole
54
)
55
from util import milestones_helpers as milestones_helpers
56
from util.milestones_helpers import (
57
    any_unfulfilled_milestones,
58 59
    get_pre_requisite_courses_not_completed,
    is_prerequisite_courses_enabled
60
)
61 62 63 64
from xmodule.course_module import CATALOG_VISIBILITY_ABOUT, CATALOG_VISIBILITY_CATALOG_AND_ABOUT, CourseDescriptor
from xmodule.error_module import ErrorDescriptor
from xmodule.partitions.partitions import NoSuchUserPartitionError, NoSuchUserPartitionGroupError
from xmodule.x_module import XModule
65

66 67
log = logging.getLogger(__name__)

68

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
def has_ccx_coach_role(user, course_key):
    """
    Check if user is a coach on this ccx.

    Arguments:
        user (User): the user whose descriptor access we are checking.
        course_key (CCXLocator): Key to CCX.

    Returns:
        bool: whether user is a coach on this ccx or not.
    """
    if hasattr(course_key, 'ccx'):
        ccx_id = course_key.ccx
        role = CourseCcxCoachRole(course_key)

        if role.has_user(user):
            list_ccx = CustomCourseForEdX.objects.filter(
                course_id=course_key.to_course_locator(),
                coach=user
            )
            if list_ccx.exists():
                coach_ccx = list_ccx[0]
                return str(coach_ccx.id) == ccx_id
    else:
        raise CCXLocatorValidationException("Invalid CCX key. To verify that "
                                            "user is a coach on CCX, you must provide key to CCX")
    return False


98
def has_access(user, action, obj, course_key=None):
99 100 101 102 103 104
    """
    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
105
    - visible_to_staff_only for modules
106
    - DISABLE_START_DATES
107
    - different access for instructor, staff, course staff, and students.
108
    - mobile_available flag for course modules
109

110 111
    user: a Django user object. May be anonymous. If none is passed,
                    anonymous is assumed
112

113 114
    obj: The object to check access for.  A module, descriptor, location, or
                    certain special strings (e.g. 'global')
115 116 117 118 119 120

    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.

121
    course_key: A course_key specifying which course run this access is for.
122 123 124
        Required when accessing anything other than a CourseDescriptor, 'global',
        or a location with category 'course'

125 126
    Returns an AccessResponse object.  It is up to the caller to actually
    deny access in a way that makes sense in context.
127
    """
128 129 130 131
    # Just in case user is passed in as None, make them anonymous
    if not user:
        user = AnonymousUser()

132 133 134
    # Preview mode is only accessible by staff.
    if in_preview_mode() and course_key:
        if not has_staff_access_to_preview_mode(user, course_key):
135 136
            return ACCESS_DENIED

137 138 139
    # delegate the work to type-specific functions.
    # (start with more specific types, then get more general)
    if isinstance(obj, CourseDescriptor):
140
        return _has_access_course(user, action, obj)
141

142
    if isinstance(obj, CourseOverview):
143
        return _has_access_course(user, action, obj)
144

145
    if isinstance(obj, ErrorDescriptor):
146
        return _has_access_error_desc(user, action, obj, course_key)
147

148
    if isinstance(obj, XModule):
149
        return _has_access_xmodule(user, action, obj, course_key)
150

151 152
    # NOTE: any descriptor access checkers need to go above this
    if isinstance(obj, XBlock):
153
        return _has_access_descriptor(user, action, obj, course_key)
154

155 156 157
    if isinstance(obj, CourseKey):
        return _has_access_course_key(user, action, obj)

158
    if isinstance(obj, UsageKey):
159
        return _has_access_location(user, action, obj, course_key)
160

161
    if isinstance(obj, basestring):
stv committed
162
        return _has_access_string(user, action, obj)
163

164 165
    # Passing an unknown object here is a coding error, so rather than
    # returning a default, complain.
166
    raise TypeError("Unknown object type in has_access(): '{0}'"
167 168
                    .format(type(obj)))

169

170
def has_staff_access_to_preview_mode(user, course_key):
171
    """
172 173
    Checks if given user can access course in preview mode.
    A user can access a course in preview mode only if User has staff access to course.
174
    """
175
    has_admin_access_to_course = any(administrative_accesses_to_course_for_user(user, course_key))
176

177
    return has_admin_access_to_course or is_masquerading_as_student(user, course_key)
178 179


180 181 182 183 184 185 186 187 188 189
def _can_view_courseware_with_prerequisites(user, course):  # pylint: disable=invalid-name
    """
    Checks if a user has access to a course based on its prerequisites.

    If the user is staff or anonymous, immediately grant access.
    Else, return whether or not the prerequisite courses have been passed.

    Arguments:
        user (User): the user whose course access we are checking.
        course (AType): the course for which we are checking access.
190 191 192
            where AType is CourseDescriptor, CourseOverview, or any other
            class that represents a course and has the attributes .location
            and .id.
193
    """
194 195 196 197 198

    def _is_prerequisites_disabled():
        """
        Checks if prerequisites are disabled in the settings.
        """
199
        return ACCESS_DENIED if is_prerequisite_courses_enabled() else ACCESS_GRANTED
200

201
    return (
202
        _is_prerequisites_disabled()
203 204
        or _has_staff_access_to_descriptor(user, course, course.id)
        or user.is_anonymous()
205
        or _has_fulfilled_prerequisites(user, [course.id])
206 207 208 209 210 211 212 213 214 215 216 217
    )


def _can_load_course_on_mobile(user, course):
    """
    Checks if a user can view the given course on a mobile device.

    This function only checks mobile-specific access restrictions. Other access
    restrictions such as start date and the .visible_to_staff_only flag must
    be checked by callers in *addition* to the return value of this function.

    Arguments:
218
        user (User): the user whose course access we are checking.
219 220 221 222 223 224 225 226 227 228
        course (CourseDescriptor|CourseOverview): the course for which we are
            checking access.

    Returns:
        bool: whether the course can be accessed on mobile.
    """
    return (
        is_mobile_available_for_user(user, course) and
        (
            _has_staff_access_to_descriptor(user, course, course.id) or
229
            _has_fulfilled_all_milestones(user, course.id)
230 231 232 233
        )
    )


234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
def _can_enroll_courselike(user, courselike):
    """
    Ascertain if the user can enroll in the given courselike object.

    Arguments:
        user (User): The user attempting to enroll.
        courselike (CourseDescriptor or CourseOverview): The object representing the
            course in which the user is trying to enroll.

    Returns:
        AccessResponse, indicating whether the user can enroll.
    """
    enrollment_domain = courselike.enrollment_domain
    # Courselike objects (e.g., course descriptors and CourseOverviews) have an attribute named `id`
    # which actually points to a CourseKey. Sigh.
    course_key = courselike.id

    # If using a registration method to restrict enrollment (e.g., Shibboleth)
    if settings.FEATURES.get('RESTRICT_ENROLL_BY_REG_METHOD') and enrollment_domain:
        if user is not None and user.is_authenticated() and \
                ExternalAuthMap.objects.filter(user=user, external_domain=enrollment_domain):
            debug("Allow: external_auth of " + enrollment_domain)
            reg_method_ok = True
        else:
            reg_method_ok = False
    else:
        reg_method_ok = True

    # If the user appears in CourseEnrollmentAllowed paired with the given course key,
    # they may enroll. Note that as dictated by the legacy database schema, the filter
    # call includes a `course_id` kwarg which requires a CourseKey.
    if user is not None and user.is_authenticated():
        if CourseEnrollmentAllowed.objects.filter(email=user.email, course_id=course_key):
            return ACCESS_GRANTED

    if _has_staff_access_to_descriptor(user, courselike, course_key):
        return ACCESS_GRANTED

    if courselike.invitation_only:
        debug("Deny: invitation only")
        return ACCESS_DENIED

276 277 278
    now = datetime.now(UTC)
    enrollment_start = courselike.enrollment_start or datetime.min.replace(tzinfo=UTC)
    enrollment_end = courselike.enrollment_end or datetime.max.replace(tzinfo=UTC)
279 280 281 282 283 284 285
    if reg_method_ok and enrollment_start < now < enrollment_end:
        debug("Allow: in enrollment period")
        return ACCESS_GRANTED

    return ACCESS_DENIED


286
def _has_access_course(user, action, courselike):
287
    """
288 289 290 291 292 293 294
    Check if user has access to a course.

    Arguments:
        user (User): the user whose course access we are checking.
        action (string): The action that is being checked.
        courselike (CourseDescriptor or CourseOverview): The object
            representing the course that the user wants to access.
295 296 297 298

    Valid actions:

    'load' -- load the courseware, see inside the course
299
    'load_forum' -- can load and contribute to the forums (one access level for now)
300
    'load_mobile' -- can load from a mobile context
301
    'enroll' -- enroll.  Checks for enrollment window.
302 303
    'see_exists' -- can see that the course exists.
    'staff' -- staff access to course.
304 305
    '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.
306 307
    """
    def can_load():
Calen Pennington committed
308 309
        """
        Can this user load this course?
310 311

        NOTE: this is not checking whether user is actually enrolled in the course.
Calen Pennington committed
312
        """
313 314
        response = (
            _visible_to_nonstaff_users(courselike) and
315 316
            check_course_open_for_learner(user, courselike) and
            _can_view_courseware_with_prerequisites(user, courselike)
317 318 319 320 321 322
        )

        return (
            ACCESS_GRANTED if (response or _has_staff_access_to_descriptor(user, courselike, courselike.id))
            else response
        )
323 324

    def can_enroll():
325 326 327 328
        """
        Returns whether the user can enroll in the course.
        """
        return _can_enroll_courselike(user, courselike)
329 330 331 332 333 334

    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.
        """
335
        return ACCESS_GRANTED if (can_load() or can_enroll()) else ACCESS_DENIED
336

337 338 339 340 341 342 343
    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 (
344 345
            _has_catalog_visibility(courselike, CATALOG_VISIBILITY_CATALOG_AND_ABOUT)
            or _has_staff_access_to_descriptor(user, courselike, courselike.id)
346 347 348 349 350 351 352 353 354
        )

    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 (
355 356 357
            _has_catalog_visibility(courselike, CATALOG_VISIBILITY_CATALOG_AND_ABOUT)
            or _has_catalog_visibility(courselike, CATALOG_VISIBILITY_ABOUT)
            or _has_staff_access_to_descriptor(user, courselike, courselike.id)
358 359
        )

360 361
    checkers = {
        'load': can_load,
362
        'load_mobile': lambda: can_load() and _can_load_course_on_mobile(user, courselike),
363 364
        'enroll': can_enroll,
        'see_exists': see_exists,
365 366
        'staff': lambda: _has_staff_access_to_descriptor(user, courselike, courselike.id),
        'instructor': lambda: _has_instructor_access_to_descriptor(user, courselike, courselike.id),
367 368
        'see_in_catalog': can_see_in_catalog,
        'see_about_page': can_see_about_page,
369
    }
370

371
    return _dispatch(checkers, action, user, courselike)
372 373


374
def _has_access_error_desc(user, action, descriptor, course_key):
375 376 377 378 379 380 381 382
    """
    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():
383
        return _has_staff_access_to_descriptor(user, descriptor, course_key)
384 385 386

    checkers = {
        'load': check_for_staff,
387 388
        'staff': check_for_staff,
        'instructor': lambda: _has_instructor_access_to_descriptor(user, descriptor, course_key)
389
    }
390 391 392 393

    return _dispatch(checkers, action, user, descriptor)


394 395 396 397 398
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`)
    """
399 400 401 402
    # Allow staff and instructors roles group access, as they are not masquerading as a student.
    if get_user_role(user, course_key) in ['staff', 'instructor']:
        return ACCESS_GRANTED

403 404 405 406 407 408 409
    # 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)
410
        return ACCESS_DENIED
411 412 413

    # resolve the partition IDs in group_access to actual
    # partition objects, skipping those which contain empty group directives.
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
    # If a referenced partition could not be found, it will be denied
    # If the partition is found but is no longer active (meaning it's been disabled)
    # then skip the access check for that partition.
    partitions = []
    for partition_id, group_ids in merged_access.items():
        try:
            partition = descriptor._get_user_partition(partition_id)  # pylint: disable=protected-access
            if partition.active:
                if group_ids is not None:
                    partitions.append(partition)
            else:
                log.debug(
                    "Skipping partition with ID %s in course %s because it is no longer active",
                    partition.id, course_key
                )
        except NoSuchUserPartitionError:
            log.warning("Error looking up user partition, access will be denied.", exc_info=True)
            return ACCESS_DENIED
432 433 434 435 436 437 438 439 440 441 442 443 444

    # 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)
445
        return ACCESS_DENIED
446 447 448 449 450 451 452 453 454 455 456 457

    # 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
458
    if not all(user_groups.get(partition.id) in groups for partition, groups in partition_groups):
459
        return ACCESS_DENIED
460 461

    # all checks passed.
462
    return ACCESS_GRANTED
463 464


465
def _has_access_descriptor(user, action, descriptor, course_key=None):
466 467 468 469 470 471 472 473 474 475 476 477
    """
    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():
478 479 480 481 482 483
        """
        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.
        """
484 485 486 487 488 489 490 491
        # If the user (or the role the user is currently masquerading as) does not have
        # access to this content, then deny access. The problem with calling _has_staff_access_to_descriptor
        # before this method is that _has_staff_access_to_descriptor short-circuits and returns True
        # for staff users in preview mode.
        if not _has_group_access(descriptor, user, course_key):
            return ACCESS_DENIED

        # If the user has staff access, they can load the module and checks below are not needed.
492 493
        if _has_staff_access_to_descriptor(user, descriptor, course_key):
            return ACCESS_GRANTED
494

495
        return (
496 497 498 499
            _visible_to_nonstaff_users(descriptor) and
            _can_access_descriptor_with_milestones(user, descriptor, course_key) and
            (
                _has_detached_class_tag(descriptor) or
500
                check_start_date(user, descriptor.days_early_for_beta, descriptor.start, course_key)
501
            )
502 503
        )

504 505
    checkers = {
        'load': can_load,
506 507 508
        'staff': lambda: _has_staff_access_to_descriptor(user, descriptor, course_key),
        'instructor': lambda: _has_instructor_access_to_descriptor(user, descriptor, course_key)
    }
509 510 511 512

    return _dispatch(checkers, action, user, descriptor)


513
def _has_access_xmodule(user, action, xmodule, course_key):
514 515 516 517 518 519 520
    """
    Check if user has access to this xmodule.

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


524
def _has_access_location(user, action, location, course_key):
525 526 527 528 529 530 531 532 533 534 535
    """
    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 = {
536 537
        'staff': lambda: _has_staff_access_to_location(user, location, course_key)
    }
538 539 540 541

    return _dispatch(checkers, action, user, location)


542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
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)

557

stv committed
558
def _has_access_string(user, action, perm):
559 560 561 562 563 564 565 566
    """
    Check if user has certain special access, specified as string.  Valid strings:

    'global'

    Valid actions:

    'staff' -- global staff access.
567 568
    'support' -- access to student support functionality
    'certificates' --- access to view and regenerate certificates for other users.
569 570 571
    """

    def check_staff():
572 573 574
        """
        Checks for staff access
        """
575 576
        if perm != 'global':
            debug("Deny: invalid permission '%s'", perm)
577 578
            return ACCESS_DENIED
        return ACCESS_GRANTED if GlobalStaff().has_user(user) else ACCESS_DENIED
579

580 581 582 583 584 585 586 587 588
    def check_support():
        """Check that the user has access to the support UI. """
        if perm != 'global':
            return ACCESS_DENIED
        return (
            ACCESS_GRANTED if GlobalStaff().has_user(user) or SupportStaffRole().has_user(user)
            else ACCESS_DENIED
        )

589
    checkers = {
590 591 592
        'staff': check_staff,
        'support': check_support,
        'certificates': check_support,
593
    }
594 595 596 597

    return _dispatch(checkers, action, user, perm)


598 599 600 601 602 603 604 605 606 607 608 609
#####  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',
610
              user,
611
              obj.location.to_deprecated_string() if isinstance(obj, XBlock) else str(obj),
612
              action)
613 614
        return result

615
    raise ValueError(u"Unknown action for object type '{0}': '{1}'".format(
616 617
        type(obj), action))

618

619
def _adjust_start_date_for_beta_testers(user, descriptor, course_key):  # pylint: disable=invalid-name
620 621 622 623 624 625 626 627 628 629
    """
    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:
630
        A datetime.  Either the same as start, or earlier for beta testers.
631 632 633 634 635 636 637 638

    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.
    """
639
    return adjust_start_date(user, descriptor.days_early_for_beta, descriptor.start, course_key)
640

Calen Pennington committed
641

642 643 644 645
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)
646 647


648
def _has_staff_access_to_location(user, location, course_key=None):
649 650 651
    if course_key is None:
        course_key = location.course_key
    return _has_access_to_course(user, 'staff', course_key)
652

653

654
def _has_access_to_course(user, access_level, course_key):
655
    """
656
    Returns True if the given user has access_level (= staff or
657 658 659
    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.
660 661

    access_level = string, either "staff" or "instructor"
662
    """
663
    if user is None or (not user.is_authenticated()):
664
        debug("Deny: no user or anon user")
665
        return ACCESS_DENIED
666

667
    if is_masquerading_as_student(user, course_key):
668
        return ACCESS_DENIED
669

670 671 672
    global_staff, staff_access, instructor_access = administrative_accesses_to_course_for_user(user, course_key)

    if global_staff:
673
        debug("Allow: user.is_staff")
674
        return ACCESS_GRANTED
675

676
    if access_level not in ('staff', 'instructor'):
677
        log.debug("Error in access._has_access_to_course access_level=%s unknown", access_level)
678
        debug("Deny: unknown access level")
679
        return ACCESS_DENIED
680

681 682
    if staff_access and access_level == 'staff':
        debug("Allow: user has course staff access")
683
        return ACCESS_GRANTED
684 685 686

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

    debug("Deny: user did not have correct access")
690
    return ACCESS_DENIED
691

692

693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
def administrative_accesses_to_course_for_user(user, course_key):
    """
    Returns types of access a user have for given course.
    """
    global_staff = GlobalStaff().has_user(user)

    staff_access = (
        CourseStaffRole(course_key).has_user(user) or
        OrgStaffRole(course_key.org).has_user(user)
    )

    instructor_access = (
        CourseInstructorRole(course_key).has_user(user) or
        OrgInstructorRole(course_key.org).has_user(user)
    )

    return global_staff, staff_access, instructor_access


712
def _has_instructor_access_to_descriptor(user, descriptor, course_key):  # pylint: disable=invalid-name
713 714 715 716 717
    """Helper method that checks whether the user has staff access to
    the course of the location.

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

720

721
def _has_staff_access_to_descriptor(user, descriptor, course_key):
722 723 724
    """Helper method that checks whether the user has staff access to
    the course of the location.

725
    descriptor: something that has a location attribute
726
    """
727
    return _has_staff_access_to_location(user, descriptor.location, course_key)
728 729


730 731 732 733 734 735 736 737 738 739
def _visible_to_nonstaff_users(descriptor):
    """
    Returns if the object is visible to nonstaff users.

    Arguments:
        descriptor: object to check
    """
    return VisibilityError() if descriptor.visible_to_staff_only else ACCESS_GRANTED


740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
def _can_access_descriptor_with_milestones(user, descriptor, course_key):
    """
    Returns if the object is blocked by an unfulfilled milestone.

    Args:
        user: the user trying to access this content
        descriptor: the object being accessed
        course_key: key for the course for this descriptor
    """
    if milestones_helpers.get_course_content_milestones(course_key, unicode(descriptor.location), 'requires', user.id):
        debug("Deny: user has not completed all milestones for content")
        return ACCESS_DENIED
    else:
        return ACCESS_GRANTED


756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
def _has_detached_class_tag(descriptor):
    """
    Returns if the given descriptor's type is marked as detached.

    Arguments:
        descriptor: object to check
    """
    return ACCESS_GRANTED if 'detached' in descriptor._class_tags else ACCESS_DENIED  # pylint: disable=protected-access


def _has_fulfilled_all_milestones(user, course_id):
    """
    Returns whether the given user has fulfilled all milestones for the
    given course.

    Arguments:
        course_id: ID of the course to check
        user_id: ID of the user to check
    """
775
    return MilestoneAccessError() if any_unfulfilled_milestones(course_id, user.id) else ACCESS_GRANTED
776 777 778 779 780 781 782 783 784 785 786


def _has_fulfilled_prerequisites(user, course_id):
    """
    Returns whether the given user has fulfilled all prerequisites for the
    given course.

    Arguments:
        user: user to check
        course_id: ID of the course to check
    """
787
    return MilestoneAccessError() if get_pre_requisite_courses_not_completed(user, course_id) else ACCESS_GRANTED
788 789 790 791 792 793 794 795 796 797 798 799 800


def _has_catalog_visibility(course, visibility_type):
    """
    Returns whether the given course has the given visibility type
    """
    return ACCESS_GRANTED if course.catalog_visibility == visibility_type else ACCESS_DENIED


def _is_descriptor_mobile_available(descriptor):
    """
    Returns if descriptor is available on mobile.
    """
801 802 803 804
    if IgnoreMobileAvailableFlagConfig.is_enabled() or descriptor.mobile_available:
        return ACCESS_GRANTED
    else:
        return MobileAvailabilityError()
805 806


807
def is_mobile_available_for_user(user, descriptor):
808 809 810 811 812
    """
    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
813 814
    Arguments:
        descriptor (CourseDescriptor|CourseOverview): course or overview of course in question
815 816
    """
    return (
817
        auth.user_has_role(user, CourseBetaTesterRole(descriptor.id))
818 819
        or _has_staff_access_to_descriptor(user, descriptor, descriptor.id)
        or _is_descriptor_mobile_available(descriptor)
820 821 822
    )


823
def get_user_role(user, course_key):
824 825 826 827
    """
    Return corresponding string if user has staff, instructor or student
    course role in LMS.
    """
828 829 830
    role = get_masquerade_role(user, course_key)
    if role:
        return role
831
    elif has_access(user, 'instructor', course_key):
832
        return 'instructor'
833
    elif has_access(user, 'staff', course_key):
834 835 836
        return 'staff'
    else:
        return 'student'