Esempio n. 1
0
 def Tasks(self, request, pk=None):
     try:
         # this line checks to see if the project is owned by the user
         if Project.objects.get(pk = pk) in Project.objects.filter(Creator=request.user.id):
             data = Task.objects.filter(Project=pk)
             serializer = TaskSerializers(data, many=True)
             return Response(serializer.data)
         else:
             # this returns an error if the user does nto own the project
             return bad_request('Users not authenticated for this request', 400)
     except:
             # this returns a 400 error if there is something wrong with the request
             return bad_request('Error bad request',400)
Esempio n. 2
0
 def Children(self, request, pk=None):
     try:
         data = Task.objects.filter(Parent=pk)
         serializer = TaskSerializers(data, many=True)
         return Response(serializer.data)
     except:
             return bad_request('Error bad request',400)
Esempio n. 3
0
    def post(self, request, slug):

        # Only available to staff/admin
        if not (request.user.is_staff or request.user.is_superuser):
            return bad_request(request, exception="Forbidden")

        schedule_id = QueryDict(request.body).get('schedule_id')

        # This is because testing comes in from a different way, django doesn't support ajax that well
        if schedule_id == None:
            schedule_id = request.POST.get('schedule_id')

        attendance_payload = QueryDict(request.body).get('students')

        # This is because testing comes in from a different way, django doesn't support ajax that well
        if attendance_payload == None:
            attendance_payload = request.POST.get('students')

        attendance_json = json.loads(attendance_payload)

        # Update the status
        for student in attendance_json:
            Attendance.objects.filter(schedule_id=schedule_id, student_id=student['id']).update(status=student['status'])

        # Send back the json serialized data of all students, now that the update has gone through
        response = redirect('update_attendance', slug=slug)
        response['Location'] += '?schedule_id=' + schedule_id
        return response
Esempio n. 4
0
 def create(self, validated_data):
     if not hasattr(Role, validated_data['role']):
         raise bad_request(request, Exception, 'Invalid Role', code=400)
     user = super(UserSerializer, self).create(validated_data)
     user.set_password(validated_data['password'])
     user.save()
     return user
Esempio n. 5
0
    def update(self, request, *args, **kwargs):
        if request.user.id is None:
            raise PermissionDenied(
                {"message": "Can only update class symbol when logged in"})

        partial = kwargs.pop('partial', False)
        instance = self.get_object()

        if 'image' in request.data:
            err_msg = 'Image should not be contained in update request'
            return bad_request(request, Exception(err_msg))

        img = MathSymbol.objects.get(pk=instance.id).image
        instance.image = img

        serializer = self.get_serializer(instance,
                                         data=request.data,
                                         partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if instance.image is None or len(instance.image) == 0:
            instance.image = self.get_latex_svg(instance.latex)
            instance.save()

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response('Ok')
Esempio n. 6
0
 def Filtered_Tasks(self, request, pk=None):
         Local_Filter = Filter.objects.get(pk = pk)
         Command = Local_Filter.Filter()
         Command = eval(Command)
         serializer = TaskSerializers(Command, many=True)
         print(serializer.data)
         try:
             return Response(serializer.data)
         except:
             return bad_request('Error bad request', 400)
Esempio n. 7
0
 def create(self, request):
     fields = {}
     try:
         for field in self.mapped_object_class.required_fields:
             fields[field] = request.POST[field]
         new_ann_type = self.mapped_object_class.insert(**fields)
     except KeyError:
         return bad_request(request, None)
     except RuntimeError:
         return already_exists()
     serializer = self.serializer_class(instance=new_ann_type)
     return Response(serializer.data)
Esempio n. 8
0
    def image(self, request, pk=None):
        if pk is None:
            return bad_request(request,
                               Exception('Primary key can not be null'))

        if 'image' not in request.data:
            err_msg = 'Image needs to be sent with this request'
            return bad_request(request, Exception(err_msg))

        if request.user.id is None:
            raise PermissionDenied(
                {"message": "Can only update class image when logged in"})

        try:
            symbol = MathSymbol.objects.get(pk=pk)
            symbol.image = base64.b64decode(request.data['image'])
            symbol.save()

            return Response('Ok')
        except MathSymbol.DoesNotExist as e:
            return bad_request(request, e)
Esempio n. 9
0
 def update(self, request, pk=None):
     try:
         ann = self.mapped_object_class.get(id=pk)[0]
     except IndexError:
         return does_not_exists()
     try:
         for field in self.mapped_object_class.required_fields:
             setattr(ann, field, request.POST.get(field, getattr(ann, field)))
         ann.update()
     except KeyError:
         return bad_request(request, None)
     except RuntimeError:
         return server_error(request, None)
     serializer = self.serializer_class(instance=ann)
     return Response(serializer.data)
Esempio n. 10
0
    def post(self, request, slug):
        # Only professors and admin can change this
        if not (request.user.is_staff or request.user.is_superuser):
            logger.warning("Attempting to unlock a schedule as a student (user_id={})".format(request.user.id))
            return bad_request(request, exception="Forbidden")

        # Grab POST data
        schedule_id = QueryDict(request.body).get('schedule_id')
        lock_status_payload = QueryDict(request.body).get('lock_status')
        lock_status_json = json.loads(lock_status_payload)

        # Find particular schedule
        schedule = Schedule.objects.filter(id=schedule_id)

        # Update lock status
        if schedule.count() > 0:
            schedule.update(attendance_closed=lock_status_json)

        return HttpResponse(200)
Esempio n. 11
0
 def list(self, request, *args, **kwargs):
     logger.error(
         f"GET on /task/{kwargs.get('task_id')}/reward. {request.user}")
     return exceptions.bad_request(request, exception=None)
def test_bad_request():
    request = RequestFactory().get('/')
    exception = Exception('Something went wrong — Not used')
    response = bad_request(request, exception)
    assert response.status_code == 400
    assert response["content-type"] == 'application/json'
Esempio n. 13
0
 def get(self, request, *args, **kwargs):
     return bad_request(request, exception="Forbidden")
Esempio n. 14
0
    def post(self, request, *args, **kwargs):
        all_users = []
        try:
            csv_file = request.FILES["file"]
            if not csv_file.name.endswith('.csv'):
                logger.error(request, 'File is not CSV type')
                return HttpResponseRedirect('manageusers')
        except Exception as e:
            logger.error("Unable to process file. " + repr(e))
            return HttpResponseRedirect('manageusers')

        file_data = csv_file.read().decode("utf-8")

        lines = file_data.split("\n")
        fields = lines[0].split(",")

        # Determine the field order for the CSV
        for i,field in enumerate(fields):
            if field.lower() in self.first_name_opts:
                self.csv_positions['first_name'] = i
            elif field.lower() in self.last_name_opts:
                self.csv_positions['last_name'] = i
            elif field.lower() in self.email_opts:
                self.csv_positions['email'] = i
            elif field.lower() in self.program_opts:
                self.csv_positions['program'] = i
            elif field.lower() in self.country_opts:
                self.csv_positions['country'] = i
            elif field.lower() in self.specialization_opts:
                self.csv_positions['specialization'] = i
            elif field.lower() in self.semester_opts:
                self.csv_positions['intake_semester'] = i

        # Validate CSV headers
        if self.csv_positions['email'] < 0:
            return bad_request("Cannot find email in CSV", exception="BadCSV")
        elif self.csv_positions['first_name'] < 0:
            return bad_request("Cannot find first name in CSV", exception="BadCSV")
        elif self.csv_positions['last_name'] < 0:
            return bad_request("Cannot find last name in CSV", exception="BadCSV")
        elif self.csv_positions['program'] < 0:
            return bad_request("Cannot find program in CSV", exception="BadCSV")

        # Get override data (if any)
        override_specialization = request.POST.get('overrideSpecialization')
        override_semester_season = request.POST.get('overrideSemesterSeason')
        override_semester_year = request.POST.get('overrideSemesterYear')
        override_country = request.POST.get('overrideCountry')

        for line in lines[1:]:
            user = {
                'first_name': "",
                'last_name': "",
                'program': "",
                'specialization': "",
                'semester_season': "",
                'semester_year': "",
                'email': "",
                'type': "Student",
                'country': ""
            }

            if line == "":
                continue

            fields = line.split(',')

            user['first_name'] = fields[self.csv_positions['first_name']]
            user['last_name'] = fields[self.csv_positions['last_name']]
            user['program'] = fields[self.csv_positions['program']]
            user['email'] = fields[self.csv_positions['email']]

            # Country
            if self.csv_positions['country'] >= 0:
                user['country'] = fields[self.csv_positions['country']]

            if user['country'] == "" and override_country != None:
                user['country'] = override_country

            # Specialization
            if self.csv_positions['specialization'] >= 0:
                user['specialization'] = fields[self.csv_positions['specialization']]

            if user['specialization'] == "" and override_specialization != None:
                user['specialization'] = override_specialization

            # Intake Semester
            if self.csv_positions['intake_semester'] >= 0:
                parts = fields[self.csv_positions['intake_semester']].split(' ')
                year_match = re.match("\d{4}", parts[0], re.M|re.I)
                if (year_match):
                    user['semester_year'] = parts[0]
                    user['semester_season'] = parts[1]
                else:
                    user['semester_year'] = parts[1]
                    user['semester_season'] = parts[1]

            if user['semester_season'] == "" and override_semester_season != None:
                user['semester_season'] = override_semester_season

            if user['semester_year'] == "" and override_semester_year != None:
                user['semester_year'] = override_semester_year

            all_users.append(user)

        logger.info("Processing CSV user file with {} potential users".format(len(all_users)))

        return JsonResponse(all_users, safe=False)
def test_bad_request():
    request = RequestFactory().get('/')
    exception = Exception('Something went wrong — Not used')
    response = bad_request(request, exception)
    assert response.status_code == 400
    assert response["content-type"] == 'application/json'
Esempio n. 16
0
 def get(self, request):
     logger.error("Attempting get request for toggle attendance lock")
     return bad_request(request, exception="Forbidden")