cert_whitelist.py 4 KB
Newer Older
1 2 3 4
"""
Management command which sets or gets the certificate whitelist for a given
user/course
"""
David Baumgold committed
5
from __future__ import print_function
6 7
from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
8
from opaque_keys import InvalidKeyError
9 10
from opaque_keys.edx.keys import CourseKey
from opaque_keys.edx.locations import SlashSeparatedCourseKey
11 12 13
from certificates.models import CertificateWhitelist
from django.contrib.auth.models import User

14

15 16 17 18 19 20 21 22 23 24 25 26
def get_user_from_identifier(identifier):
    """
     This function takes the string identifier and fetch relevant user object from database
    """
    identifier = identifier.strip()
    if '@' in identifier:
        user = User.objects.get(email=identifier)
    else:
        user = User.objects.get(username=identifier)
    return user


27
class Command(BaseCommand):
28 29 30 31
    """
    Management command to set or get the certificate whitelist
    for a given user(s)/course
    """
32 33 34

    help = """
    Sets or gets the certificate whitelist for a given
35
    user(s)/course
36

37
        Add a user or list of users to the whitelist for a course
38 39

        $ ... cert_whitelist --add joe -c "MITx/6.002x/2012_Fall"
40 41
        OR
        $ ... cert_whitelist --add joe,jenny,tom,jerry -c "MITx/6.002x/2012_Fall"
42

43
        Remove a user or list of users from the whitelist for a course
44

45
        $ ... cert_whitelist --del joe -c "MITx/6.002x/2012_Fall"
46 47
        OR
        $ ... cert_whitelist --del joe,jenny,tom,jerry -c "MITx/6.002x/2012_Fall"
48 49 50

        Print out who is whitelisted for a course

51
        $ ... cert_whitelist -c "MITx/6.002x/2012_Fall"
52 53 54 55 56 57 58 59

    """

    option_list = BaseCommand.option_list + (
        make_option('-a', '--add',
                    metavar='USER',
                    dest='add',
                    default=False,
60
                    help='user or list of users to add to the certificate whitelist'),
61 62 63 64 65

        make_option('-d', '--del',
                    metavar='USER',
                    dest='del',
                    default=False,
66
                    help='user or list of users to remove from the certificate whitelist'),
67

68 69 70 71 72 73 74 75 76 77 78
        make_option('-c', '--course-id',
                    metavar='COURSE_ID',
                    dest='course_id',
                    default=False,
                    help="course id to query"),
    )

    def handle(self, *args, **options):
        course_id = options['course_id']
        if not course_id:
            raise CommandError("You must specify a course-id")
79

80 81 82 83 84 85 86 87 88 89 90
        def update_user_whitelist(username, add=True):
            """
            Update the status of whitelist user(s)
            """
            user = get_user_from_identifier(username)
            cert_whitelist, _created = CertificateWhitelist.objects.get_or_create(
                user=user, course_id=course
            )
            cert_whitelist.whitelist = add
            cert_whitelist.save()

91 92 93 94
        # try to parse the serialized course key into a CourseKey
        try:
            course = CourseKey.from_string(course_id)
        except InvalidKeyError:
95 96
            print(("Course id {} could not be parsed as a CourseKey; "
                   "falling back to SSCK.from_dep_str").format(course_id))
97 98
            course = SlashSeparatedCourseKey.from_deprecated_string(course_id)

99
        if options['add'] and options['del']:
100
            raise CommandError("Either remove or add a user, not both")
101 102 103

        if options['add'] or options['del']:
            user_str = options['add'] or options['del']
104 105 106 107 108
            add_to_whitelist = True if options['add'] else False
            users_list = user_str.split(",")
            for username in users_list:
                if username.strip():
                    update_user_whitelist(username, add=add_to_whitelist)
109

110
        whitelist = CertificateWhitelist.objects.filter(course_id=course)
David Baumgold committed
111 112 113 114 115
        wl_users = '\n'.join(
            "{u.user.username} {u.user.email} {u.whitelist}".format(u=u)
            for u in whitelist
        )
        print("User whitelist for course {0}:\n{1}".format(course_id, wl_users))