Example #1
0
    def POST(self, request, **kwargs):
        try:
            rep = json.loads(request.read())

            if 'gmail_id' in rep:
                gmail_id = rep.get('gmail_id', '').strip()
                person = get_person_by_gmail_id(gmail_id)
                user = create_user(person)
                return HttpResponse()
            else:
                net_id = netid_from_request(rep)
                user = User.objects.get(net_id=net_id)
                return self.json_response('{"error":"User already exists"}',
                                          status=409)
        except User.DoesNotExist:
            try:
                user = User.objects.add_user(get_person_by_netid(net_id),
                                             priority=PRIORITY_IMMEDIATE)
                return HttpResponse()

            except Exception as err:
                return self.json_response('{"error": "%s"}' % err, status=400)

        except Exception as err:
            return self.json_response('{"error": "%s"}' % err, status=400)
Example #2
0
    def add_group_enrollment_data(self, login_id, section_id, role, status):
        """
        Generates one enrollment for the passed group member.
        """
        try:
            person = get_person_by_netid(login_id)
            if self.add_user_data_for_person(person):
                self.data.add(
                    EnrollmentCSV(section_id=section_id,
                                  person=person,
                                  role=role,
                                  status=status))

        except InvalidLoginIdException:
            try:
                person = get_person_by_gmail_id(login_id)
                if status == ENROLLMENT_ACTIVE:
                    self.data.add(UserCSV(person))

                self.data.add(
                    EnrollmentCSV(section_id=section_id,
                                  person=person,
                                  role=role,
                                  status=status))
            except InvalidLoginIdException as ex:
                self.logger.info("Skip group member {}: {}".format(
                    login_id, ex))
    def _add_admin(self, **kwargs):
        netid = kwargs['net_id']
        regid = kwargs['reg_id']
        self._log.info('ADD: %s is %s in %s' % (netid,
                                                kwargs['role'],
                                                kwargs['account_id']))

        try:
            User.objects.get(reg_id=regid)
        except User.DoesNotExist:
            try:
                person = get_person_by_netid(netid)

                self._log.info('Provisioning admin: %s (%s)' % (
                    person.uwnetid, person.uwregid))

                try:
                    user = get_user_by_sis_id(person.uwregid)
                except DataFailureException as err:
                    if err.status == 404:
                        user = create_user(CanvasUser(
                            name=user_fullname(person),
                            login_id=person.uwnetid,
                            sis_user_id=person.uwregid,
                            email=user_email(person)))

                User.objects.add_user(person)

            except Exception, err:
                self._log.info('Skipped admin: %s (%s)' % (netid, err))
                return
Example #4
0
    def GET(self, request, **kwargs):
        try:
            if 'gmail_id' in request.GET:
                gmail_id = request.GET.get('gmail_id', '').strip()
                person = get_person_by_gmail_id(gmail_id)
                return self.response_for_google_person(person)
            elif 'net_id' in request.GET:
                net_id = netid_from_request(request.GET)
                person = get_person_by_netid(net_id)
                return self.response_for_person(person)
            elif 'reg_id' in request.GET:
                reg_id = regid_from_request(request.GET)
                person = get_person_by_regid(reg_id)
                return self.response_for_person(person)
            else:
                return self.json_response('{"error":"Unrecognized user ID"}',
                                          status=400)

        except DataFailureException as err:
            data = json.loads(err.msg)
            return self.json_response('{"error":"%s %s"}' % (
                err.status, data["StatusDescription"]), status=400)

        except Exception as err:
            return self.json_response('{"error":"%s"}' % err, status=400)
Example #5
0
    def _get_user_from_login(self, login):
        user = AddUser(login=login)
        try:
            try:
                person = get_person_by_gmail_id(login)
                user.login = person.login_id
            except UserPolicyException:
                person = get_person_by_netid(login)
                user.login = person.uwnetid

            user.email = user_email(person)
            user.name = user_fullname(person)
            user.regid = user_sis_id(person)

            if user.regid in self._course_users:
                user.name = self._course_users[user.regid].name
                user.status = 'present'
                user.comment = 'Already in course'

        except DataFailureException as ex:
            if ex.status != 401:
                raise
        except UserPolicyException as ex:
            user.status = 'invalid'
            user.comment = "%s" % self._prettify(str(ex))

        return user
Example #6
0
    def get(self, request, *args, **kwargs):
        json_rep = {'enrollments': []}

        filt_kwargs = None

        if 'queue_id' in request.GET:
            queue_id = request.GET.get('queue_id', '').strip()
            if re.match(r'^[0-9]+$', str(queue_id)):
                filt_kwargs = {'queue_id': queue_id}
            else:
                err = 'invalid queue_id: %s' % queue_id
                logger.error(err)
                return self.error_response(400, err)
        else:
            provisioned_error = request.GET.get('provisioned_error')
            if provisioned_error:
                filt_kwargs = {
                    'provisioned_error': self._is_true(provisioned_error),
                    'queue_id__isnull': True
                }

        if filt_kwargs:
            try:
                filt_kwargs['priority__gt'] = Enrollment.PRIORITY_NONE
                enrollments = list(Enrollment.objects.filter(**filt_kwargs))
                for enrollment in enrollments:
                    json_rep['enrollments'].append(enrollment.json_data())

                return self.json_response(json_rep)
            except Exception as err:
                logger.error('enrollment kwargs search fail: %s' % err)
                return self.error_response(400, err)

        reg_id = None
        try:
            if 'net_id' in request.GET:
                person = get_person_by_netid(
                    self.netid_from_request(request.GET))
                reg_id = person.uwregid
            elif 'reg_id' in request.GET:
                reg_id = self.regid_from_request(request.GET)
            else:
                self._criteria[2]['required'] = True

            filter_terms = self._valid_enrollment_filter(request)
            filter_prefix = '-'.join(filter_terms)
            enrollment_list = list(
                Enrollment.objects.filter(course_id__startswith=filter_prefix,
                                          reg_id=reg_id))

        except EnrollmentInvalidException as err:
            return self.error_response(400, err)
        except Exception as err:
            logger.error('course filter fail: %s' % err)
            return self.error_response(400, err)

        return self.json_response(json_rep)
    def add_all_users(self):
        existing_netids = dict((u, p) for u, p in (
            super(UserManager, self).get_queryset().values_list(
                'net_id', 'priority')))

        for member in get_sis_import_members():
            if (member.name not in existing_netids or
                    existing_netids[member.name] == PRIORITY_NONE):
                try:
                    user = self.add_user(get_person_by_netid(member.name))
                    existing_netids[member.name] = user.priority
                except Exception as err:
                    logger.info('User: SKIP %s, %s' % (member.name, err))
    def handle(self, *args, **options):
        file_path = options.get('file_path')
        workshop_name = options.get('workshop_name')
        term_sis_id = options.get('term_sis_id')
        account_sis_id = options.get('account_sis_id')

        with open(file_path, 'r') as infile:
            file_data = infile.read()
        netids = file_data.splitlines()

        csvdata = Collector()

        for netid in netids:
            try:
                person = get_person_by_netid(netid.strip())
            except UserPolicyException as err:
                print("Skipped user '{}': {}".format(netid, err))
                continue

            if not csvdata.add(UserCSV(person)):
                continue

            course_sis_id = '-'.join([
                term_sis_id,
                re.sub(r'[^\w]', '-', workshop_name.lower()), person.uwnetid
            ])
            short_name = '{} {}'.format(date.today().year, workshop_name)
            long_name = '{} Sandbox'.format(short_name)

            csvdata.add(
                CourseCSV(course_id=course_sis_id,
                          short_name=short_name,
                          long_name=long_name,
                          account_id=account_sis_id,
                          term_id=term_sis_id,
                          status='active'))

            csvdata.add(
                EnrollmentCSV(course_id=course_sis_id,
                              person=person,
                              role=get_instructor_sis_import_role(),
                              status=ENROLLMENT_ACTIVE))

        csv_path = csvdata.write_files()

        if csv_path:
            imp = Import(priority=Course.PRIORITY_DEFAULT,
                         csv_type='course',
                         csv_path=csv_path)
            imp.save()
            imp.import_csv()
    def handle(self, *args, **options):

        if not len(args):
            raise CommandError("Usage: create_workshop_courses <path> "
                               "<workshop_name><term_sis_id>")

        file_path = args[0]
        workshop_name = args[1]
        term_sis_id = args[2]
        account_sis_id = 'course-request-sandbox'

        with open(file_path, 'r') as infile:
            file_data = infile.read()
        netids = file_data.splitlines()

        csvdata = Collector()

        for netid in netids:
            try:
                person = get_person_by_netid(netid.strip())
            except UserPolicyException as err:
                print "Skipped user %s: %s" % (netid, err)
                continue

            if not csvdata.add(UserCSV(person)):
                continue

            course_sis_id = '%s-%s-%s' % (
                term_sis_id,
                re.sub(r'[^\w]', '-', workshop_name.lower()),
                person.uwnetid)
            short_name = '%s %s' % (workshop_name, date.today().year)
            long_name = '%s Sandbox' % short_name

            csvdata.add(CourseCSV(
                course_id=course_sis_id, short_name=short_name,
                long_name=long_name, account_id=account_sis_id,
                term_id=term_sis_id, status='active'))

            csvdata.add(EnrollmentCSV(
                course_id=course_sis_id, person=person,
                role=Enrollment.INSTRUCTOR_ROLE, status='active'))

        csv_path = csvdata.write()

        if csv_path:
            imp = Import(priority=PRIORITY_DEFAULT, csv_type='course',
                         csv_path=csv_path)
            imp.save()
            imp.import_csv()
Example #10
0
    def post(self, request, *args, **kwargs):
        try:
            login_data = request.data['logins']
        except KeyError as ex:
            return RESTDispatch.error_response(400, 'Missing list of logins')

        users = []
        for login in login_data:
            login = login.strip().lower()
            if not any(u.get('login') == login for u in users):
                try:
                    user = {}
                    try:
                        person = get_person_by_gmail_id(login)
                        user['login'] = person.login_id
                        user['full_name'] = person.login_id
                        user['is_person'] = True
                    except UserPolicyException:
                        login = self.strip_domain(login)
                        person = get_person_by_netid(login)
                        user['login'] = person.uwnetid
                        try:
                            user['full_name'] = person.get_formatted_name(
                                '{first} {last}')
                            user['is_person'] = True
                        except AttributeError as ex:
                            user['full_name'] = person.display_name
                            user['is_person'] = False  # UW entity

                    sis_id = user_sis_id(person)
                    if not any(u.get('sis_id') == sis_id for u in users):
                        try:
                            can_access_canvas(user['login'])
                        except UserPolicyException as ex:
                            user['error'] = '{}'.format(ex)

                        user['sis_id'] = sis_id
                        user['email'] = user_email(person)
                        users.append(user)

                except DataFailureException as ex:
                    users.append({'login': login, 'error': ex.msg})

                except UserPolicyException as ex:
                    users.append({'login': login, 'error': '{}'.format(ex)})

        return RESTDispatch.json_response({'users': users})
    def add_group_enrollment_data(self, member, section_id, role, status):
        """
        Generates one enrollment for the passed group member.
        """
        if member.is_uwnetid():
            person = get_person_by_netid(member.name)
            if self.add_user_data_for_person(person):
                self.data.add(EnrollmentCSV(
                    section_id=section_id, person=person, role=role,
                    status=status))

        elif member.is_eppn():
            if status == Enrollment.ACTIVE_STATUS and hasattr(member, 'login'):
                person = get_person_by_gmail_id(member.login)
                self.data.add(UserCSV(person))
            else:
                person = get_person_by_gmail_id(member.name)

            self.data.add(EnrollmentCSV(
                section_id=section_id, person=person, role=role,
                status=status))
    def GET(self, request, **kwargs):
        json_rep = {
            'courses': []
        }

        filt_kwargs = None

        if 'queue_id' in request.GET:
            queue_id = request.GET.get('queue_id', '').strip()
            if re.match(r'^[0-9]+$', str(queue_id)):
                filt_kwargs = {'queue_id': queue_id}
            else:
                err = 'invalid queue_id: %s' % queue_id
                self._log.error(err)
                return self.json_response('{"error":"%s"}' % err, status=400)
        else:
            provisioned_error = request.GET.get('provisioned_error')
            if provisioned_error:
                filt_kwargs = {
                    'provisioned_error': self._is_true(provisioned_error),
                    'queue_id__isnull': True
                }

        if filt_kwargs:
            try:
                filt_kwargs['priority__gt'] = PRIORITY_NONE
                course_list = list(Course.objects.filter(
                    **filt_kwargs).order_by('course_id'))

                include_sws_url = can_view_source_data()
                for course in course_list:
                    json_data = course.json_data(include_sws_url)
                    json_rep['courses'].append(json_data)

                return self.json_response(json.dumps(json_rep))
            except Exception as err:
                self._log.error('course kwargs search fail: %s' + err)
                return self.json_response('{"error":"%s"}' % err, status=400)

        net_id = None
        reg_id = None
        try:
            if 'net_id' in request.GET:
                net_id = netid_from_request(request.GET)
            elif 'reg_id' in request.GET:
                reg_id = regid_from_request(request.GET)
            else:
                self._criteria[2]['required'] = True

            filter_terms = self._validCourseFilter(request)
            filter_prefix = '-'.join(filter_terms)
            course_list = list(Course.objects.filter(
                course_id__startswith=filter_prefix).order_by('course_id'))
        except CourseInvalidException as err:
            return self.json_response('{"error":"%s"}' % err, status=400)
        except Exception as err:
            self._log.error('course filter fail: %s' % err)
            return self.json_response('{"error":"%s"}' % err, status=400)

        if (net_id is not None or reg_id is not None) and len(course_list):
            try:
                if net_id is not None:
                    instructor = get_person_by_netid(net_id)
                else:
                    instructor = get_person_by_regid(reg_id)

                year = request.GET.get('year')
                quarter = request.GET.get('quarter')
                term = get_term_by_year_and_quarter(year, quarter)

                white_list = []
                for section in get_sections_by_instructor_and_term(
                        instructor, term):
                    white_list.append('-'.join([
                        section.term.canvas_sis_id(),
                        section.curriculum_abbr.upper(),
                        section.course_number,
                        section.section_id.upper()]))

            except Exception as err:
                self._log.error('section search fail: %s' % err)
                return self.json_response('{"error":"%s"}' % err, status=400)

        include_sws_url = can_view_source_data()
        for course in course_list:
            if 'white_list' in locals() and course.course_id not in white_list:
                continue

            json_data = course.json_data(include_sws_url)
            json_rep['courses'].append(json_data)

        return self.json_response(json.dumps(json_rep))
Example #13
0
    def get(self, request, *args, **kwargs):
        json_rep = {'courses': []}

        filt_kwargs = None

        if 'queue_id' in request.GET:
            queue_id = request.GET.get('queue_id', '').strip()
            if re.match(r'^[0-9]+$', str(queue_id)):
                filt_kwargs = {'queue_id': queue_id}
            else:
                err = 'invalid queue_id: {}'.format(queue_id)
                logger.error(err)
                return self.error_response(400, err)
        else:
            provisioned_error = request.GET.get('provisioned_error')
            if provisioned_error:
                filt_kwargs = {
                    'provisioned_error': self._is_true(provisioned_error),
                    'queue_id__isnull': True
                }

        if filt_kwargs:
            try:
                filt_kwargs['priority__gt'] = Course.PRIORITY_NONE
                course_list = list(
                    Course.objects.filter(**filt_kwargs).order_by('course_id'))

                include_sws_url = self.can_view_source_data(request)
                for course in course_list:
                    json_data = course.json_data(include_sws_url)
                    json_rep['courses'].append(json_data)

                return self.json_response(json_rep)
            except Exception as err:
                logger.error('Course search fail: {}'.format(err))
                return self.error_response(400, err)

        net_id = None
        reg_id = None
        try:
            if 'net_id' in request.GET:
                net_id = self.netid_from_request(request.GET)
            elif 'reg_id' in request.GET:
                reg_id = self.regid_from_request(request.GET)
            else:
                self._criteria[2]['required'] = True

            filter_terms = self._valid_course_filter(request)
            filter_prefix = '-'.join(filter_terms)
            course_list = list(
                Course.objects.filter(
                    course_id__startswith=filter_prefix).order_by('course_id'))
        except CourseInvalidException as err:
            return self.error_response(400, err)
        except Exception as err:
            logger.error('Course filter fail: {}'.format(err))
            return self.error_response(400, err)

        if (net_id is not None or reg_id is not None) and len(course_list):
            try:
                if net_id is not None:
                    instructor = get_person_by_netid(net_id)
                else:
                    instructor = get_person_by_regid(reg_id)

                year = request.GET.get('year')
                quarter = request.GET.get('quarter')
                term = get_term_by_year_and_quarter(year, quarter)

                valid = []
                for section in get_sections_by_instructor_and_term(
                        instructor, term):
                    valid.append('-'.join([
                        section.term.canvas_sis_id(),
                        section.curriculum_abbr.upper(), section.course_number,
                        section.section_id.upper()
                    ]))

            except Exception as err:
                logger.error('Section search fail: {}'.format(err))
                return self.error_response(400, err)

        include_sws_url = self.can_view_source_data(request)
        for course in course_list:
            if 'valid' in locals() and course.course_id not in valid:
                continue

            json_data = course.json_data(include_sws_url)
            json_rep['courses'].append(json_data)

        return self.json_response(json_rep)
Example #14
0
 def add_user_by_netid(self, net_id, priority=ImportResource.PRIORITY_HIGH):
     return self.add_user(get_person_by_netid(net_id), priority=priority)
Example #15
0
 def _process(self, user):
     try:
         person = get_person_by_netid(user.net_id)
         self.add_user_data_for_person(person, force=True)
     except UserPolicyException as err:
         self.logger.info("Skip user %s: %s" % (user.reg_id, err))
Example #16
0
 def _process(self, user):
     try:
         person = get_person_by_netid(user.net_id)
         self.add_user_data_for_person(person, force=True)
     except (UserPolicyException, DataFailureException) as err:
         self.logger.info('Skip user {}: {}'.format(user.reg_id, err))