Example #1
0
def SchedulersView(request):
    res = HttpResponse()
    if request.method == "GET":
        return render(
            request, 'schedulers.html', {
                'scheduler_list': CUser.objects.filter(user_type='scheduler'),
                'invite_user_form': InviteUserForm(),
                'delete_user_form': DeleteUserForm()
            })
    elif request.method == "POST" and 'invite-form' in request.POST:
        form = InviteUserForm(request.POST)
        if form.is_valid():
            form.send_invite('scheduler', request)
            return HttpResponseRedirect('/department/schedulers')
        else:
            return ErrorView(request, 400, "")
    elif reqest.method == "POST" and 'edit-form' in request.POST:
        res.status_code = 400
        res.reason_phrase = "NYI"
    elif request.method == "POST" and 'delete-form' in request.POST:
        form = DeleteUserForm(request.POST)
        if form.is_valid():
            try:
                form.delete_user()
                res.status_code = 200
            except ObjectDoesNotExist:
                res.status_code = 404
                res.reason_phrase = "User not found"
        else:
            return ErrorView(request, 400, "Invalid form entry")
    else:
        return ErrorView(request, 400, "")
    return res
Example #2
0
def HandleDeleteStoryRequest(request):
    # Don't accept non-POST requests
    if (request.method != 'POST'):
        http_bad_response = HttpResponseBadRequest()
        http_bad_response['Content-Type'] = 'text/plain'
        http_bad_response.content = 'Only POST requests are permitted for this resource\n'
        return http_bad_response

    # Create response object
    http_response = HttpResponse()
    http_response['Content-Type'] = 'text/plain'

    # Check if user is logged in
    if request.user.is_authenticated:
        # Decode json data
        requestData = json.loads(request.body)
        # Delete the story object
        story_id = requestData['story_key']
        s1 = Story.objects.get(id=story_id)
        s1.delete()
        http_response.status_code = 201
        http_response.reason_phrase = 'Created'
        http_response.content = 'Story deleted successfully'
        return http_response
    else:
        http_response.status_code = 503
        http_response.reason_phrase = 'Service Unavailable'
        http_response.content = 'User is not authenticated'

    return http_response
Example #3
0
def fingerprint(request, key):
    logger.debug("fingerprint/{} ({})".format(key, request.method))

    permissions = request.user.get_all_permissions()

    if request.method == "GET":
        if "ddosdb.view_fingerprint" not in permissions:
            raise PermissionDenied()

    try:
        fps = _search({'key': key}, {'_id': 0})
        logger.debug(fps)
        if len(fps) > 0:
            # Check if this user is allowed to view this fingerprint...

            return JsonResponse(fps, safe=False)
        else:
            response = HttpResponse()
            response.status_code = 404
            response.reason_phrase = "Fingerprint {} not found".format(key)
            return response

    except ServerSelectionTimeoutError as e:
        logger.error("MongoDB unreachable")
        response = HttpResponse()
        response.status_code = 500
        response.reason_phrase = "Error with MongoDB"
        return response
Example #4
0
def GetStudentPlanData(request):
    res = HttpResponse()
    if request.method == "GET":
        try:
            term = request.GET.get('schedule')
            schedule = Schedule.get_schedule(term_name=term)
            student_plan_data = StudentPlanData.get_student_plan_data(
                schedule=schedule).all()
            data = []
            for v in student_plan_data:
                data.append(v.to_json())
            res.write(json.dumps({'data': data}))
        except KeyError as e:
            res.status_code = 400
            if term == None:
                res.reason_phrase = "Missing schedule in query string"
            else:
                res.status_code = 500
        except ObjectDoesNotExist:
            res.status_code = 400
            if schedule is None:
                res.reason_phrase = "Schedule '%s' does not exist" % (
                    request.GET.get('schedule'), )
            elif student_plan_data is None:
                res.reason_phrase = "No student plan data for schedule '%s'" % (
                    schedule.academic_term, )
            else:
                res.status_code = 500
    else:
        res.status_code = 400
    return res
Example #5
0
 def get_all_or_create_resource(self, request, **kwargs):
     self.method_check(request, allowed=['post', 'get'])
     if request.method == 'POST':
         data = json.loads(request.body)
         user = data.get('user', '')
         content = data.get('content', '')
         success, response = Message.objects.add_message(user=user,
                                                         content=content)
         if not success:
             data = serializers.serialize('json', [response])
             response = HttpResponse(data, mimetype='application/json')
             response.status_code = 400
             response.reason_phrase = "BAD REQUEST"
             return response
         else:
             data = serializers.serialize('json', [response])
             response = HttpResponse(data, mimetype='application/json')
             response.status_code = 201
             response.reason_phrase = "CREATED"
             return response
     elif request.method == 'GET':
         response = Message.objects.all()
         data = serializers.serialize('json', response)
         response = HttpResponse(data, mimetype='application/json')
         response.status_code = 200
         response.reason_phrase = "OK"
         return response
def check_results(request):
    """Check the results of a requested classification. If the classification
    has not been completed yet, all of the updates will be sent in the response
    instead.
    """
    
    # Check if an ID was supplied.
    if ('ID' not in request.GET):
        response = HttpResponse()
        response.status_code = 400 # Bad Request
        response.reason_phrase = ("No ID was passed. The ID used to start "
                                  "the classification job must be sent to "
                                  "check the progress. The ID should be "
                                  "passed in a parameter named 'ID'.")
        return response
        
    # Ensure a file exists with the specified ID.
    id = request.GET['ID']
    if (not File.objects.filter(file_name=id).exists()):
        response = HttpResponse()
        response.status_code = 400 # Bad Request
        response.reason_phrase = ('The passed ID was invalid. If the ID you '
                                  'sent was returned by a validate request, '
                                  'it is possible the ID has expired and the '
                                  'job was deleted.')
        
    # Retrieve the job for the requested file.
    file = File.objects.get(file_name=id)
    job = file.job
    
    # If the job is complete, send the results. Otherwise, send all of the
    # updates for the job.
    has_result = JobResult.objects.filter(job=job).exists()
    return job_results(request, job) if has_result else \
           job_updates(request, job)
Example #7
0
def HandleLoginRequest(request):
    is_post, bad_response = POST_req_checker(request)

    if not is_post:
        return bad_response

    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)

    username = body['Username']
    password = body['Password']

    account_object = authenticate(username=username, password=password)
    response = HttpResponse()

    if account_object is not None:
        token = Token.objects.create(user=account_object)

        response['Content-Type'] = 'application/text'
        response.status_code = 200
        response.reason_phrase = 'Login Successful'
        response.content = token.key
    else:
        response['Content-Type'] = 'application/text'
        response.status_code = 401
        response.reason_phrase = 'Login Failed'

    return response
Example #8
0
def make_shortcode(request):
    """View to shorten url."""
    form = ShortcodeForm(data=request.POST)
    if form.is_valid():
        cd = form.cleaned_data
        shortcode = cd['shortcode']
        entry = form.save(commit=False)
        if url_exists(cd['url']) != True:
            response = HttpResponse(
                'Url not present.<br><a href="/">Try again</a>.')
            response.status_code = 400
            response.reason_phrase = 'Url not present'
            return response
        elif not is_valid(shortcode):
            response = HttpResponse('The provided shortcode is invalid.<br>\
                    <a href="/">Try again</a>.')
            response.status_code = 412
            response.reason_phrase = 'The provided shortcode is invalid'
            return response
        shortcodes = [getattr(c, 'shortcode') for c in Shortcode.objects.all()]
        if shortcode in shortcodes:
            response = HttpResponse('Shortcode already in use.<br>\
                <a href="/">Try again</a>.')
            response.status_code = 409
            response.reason_phrase = 'Shortcode already in use'
            return response
        elif shortcode == '':
            entry.shortcode = make_unique_shortcode(6, shortcodes)
        entry.redirectCount = 0
        entry.save()
        serializer = ShortcodeSerializer(entry, many=False)
        return JsonResponse(serializer.data, status=201)
    return render(request, 'urly/index.html', {'form': form})
Example #9
0
def HandleLoginRequest(request):
    # Don't accept non-POST requests
    if (request.method != 'POST'):
        http_bad_response = HttpResponseBadRequest()
        http_bad_response['Content-Type'] = 'text/plain'
        http_bad_response.content = 'Only POST requests are permitted for this resource\n'
        return http_bad_response

    # Get the login details provided
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)

    # Create http response object
    http_response = HttpResponse()
    http_response['Content-Type'] = 'text/plain'

    # Respond based on whether the user has been authenticated
    if user is not None:
        login(request, user)
        request.session.modified = True
        http_response.status_code = 200
        http_response.reason_phrase = 'OK'
        http_response.content = 'Welcome to The Josh Boult News Agency'
    else:
        http_response.status_code = 401
        http_response.reason_phrase = 'Unauthorized'
        http_response.content = 'Invalid login'

    return http_response
Example #10
0
def Options(request):
    res = HttpResponse()
    if request.method == "GET":
        option_type = request.GET.get('type') 
        if option_type is None:
            res.status_code = 400
            res.reason_phrase = "Missing option type"
        else:
            res.content_type = "application/json"
            if option_type == "Course":
                data = json.dumps({"options": [x.to_json() for x in Course.get_all_courses().all()] })
                res.write(data)
                res.status_code = 200
            elif option_type == "Faculty":
                data = json.dumps({"options": [x.to_json() for x in CUser.get_all_faculty().all()] })
                res.write(data)
                res.status_code = 200
            elif option_type == "Room":
                data = json.dumps({"options": [x.to_json() for x in Room.get_all_rooms().all()] })
                res.write(data)
                res.status_code = 200
            elif option_type == "Time":
                res.status_code = 400
                res.reason_phrase = "NYI"
            else:
                res.status_code = 400
                res.reason_phrase = "Missing option type"
    else:
        res.status_code = 400 
    return res
Example #11
0
def login(request):
    # author 必须在这里添加了才有用,在site中添加的连接不上去
    # models.Author.objects.create(username="******", password="******")
    # models.Author.objects.create(username="******", password="******") ok
    if request.method == 'POST':
        name = request.POST.get('username')
        pwd = request.POST.get('password')

        if name:
            try:
                user = models.Author.objects.get(username=name)
                # user = models.Author.objects.filter(username=name, password=pwd)
            except:
                payload = {'sorry': 'unsername not exists !'}
                http_badresponse = HttpResponse(json.dumps(payload))
                http_badresponse['content-type'] = 'text/plain'
                http_badresponse.status_code = 404
                http_badresponse.reason_phrase = ' unsername or password is wrong'
                return http_badresponse

        else:  # get username
            return HttpResponse("please input your username and password")

        if pwd:
            # get pwd

            if user.password == pwd:
                request.session['name'] = user.username
                # 登陆成功
                payload = {'Hell': 'welcome you !'}
                http_response = HttpResponse(json.dumps(payload))
                http_response['content-type'] = 'text/plain'
                http_response.status_code = 200
                http_response.reason_phrase = 'OK'
                return http_response
            else:
                # 登陆失败
                payload = {'sorry': 'unsername or password is wrong !'}
                http_badresponse = HttpResponse(json.dumps(payload))
                http_badresponse['content-type'] = 'text/plain'
                http_badresponse.status_code = 404
                http_badresponse.reason_phrase = ' unsername or password is wrong'
                return http_badresponse
        else:
            return HttpResponse("please input your password and password")

    # post request
    else:
        payload = {'request problem': 'need POST request '}
        http_badresponse = HttpResponse(json.dumps(payload))
        http_badresponse['content-type'] = 'text/plain'
        http_badresponse.status_code = 404
        http_badresponse.reason_phrase = 'need POST request'
        return http_badresponse
Example #12
0
def rate(request):
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'

    if (request.method == 'GET'):
        http_bad_response.content = 'Only POST requests are allowed for this resource\n'
        return http_bad_response

    profID = request.POST.get('teach_ID').upper()
    modID = request.POST.get('mod_ID').upper()
    year = request.POST.get('year')
    sem = request.POST.get('semester')
    rate = request.POST.get('rate')

    numProf = models.Teacher.objects.filter(profID=profID).count()
    numModule = models.Module.objects.filter(module_ID=modID).count()
    is_int = isinstance(rate, int)

    if numProf == 0 or numModule == 0 or is_int:
        the_list = "\n\nInvalid option\n\n"
        payload = {'phrase': the_list}
        http_response = HttpResponse(json.dumps(payload))
        http_response['Content-Type'] = 'application/json'
        http_response.status_code = 401
        http_response.reason_phrase = 'Invalid Details'
        return http_response
    else:
        prof = models.Teacher.objects.get(profID=profID)
        module = models.Module.objects.filter(module_ID=modID)[0]
        numModules = models.Module.objects.filter(module_ID=modID,
                                                  teachers=prof.id,
                                                  year=int(year),
                                                  semester=int(sem)).count()
        if numModules > 0:
            the_list = "\n\nRate successful\n\n"
            payload = {'phrase': the_list}
            http_response = HttpResponse(json.dumps(payload))
            http_response['Content-Type'] = 'application/json'
            http_response.status_code = 200
            http_response.reason_phrase = 'OK'
            rating = models.Rating.objects.create(module=module,
                                                  teacher=prof,
                                                  Rating=rate)
            rating.save()
        else:
            the_list = "\n\nTeacher does not take this module at specified time.\n\n"
            payload = {'phrase': the_list}
            http_response = HttpResponse(json.dumps(payload))
            http_response['Content-Type'] = 'application/json'
            http_response.status_code = 401
            http_response.reason_phrase = 'Invalid Details'
            return http_response
        return http_response
Example #13
0
def RegistrationView(request):
    res = HttpResponse()
    #pass these credentials to the RegisterUserForm
    first_name = request.GET.get('first')
    last_name = request.GET.get('last')
    user_type = request.GET.get('type')

    if request.method == "GET":
        storage = messages.get_messages(request)
        for msg in storage:
            pass
        return render(
            request, 'registration.html', {
                'registration_form':
                RegisterUserForm(
                    first=first_name, last=last_name, type=user_type)
            })
    elif request.method == "POST":
        form = RegisterUserForm(request.POST)
        if form.is_valid():
            try:
                user = form.save()
                #res.status_code = 200
                #return render(request, 'home.html')
                return HttpResponseRedirect("/home")
            except ValidationError as e:
                res.status_code = 400
                res.reason_phrase = "Invalid password entry"
                return HttpResponseRedirect("/register")
            # db error
            except IntegrityError as e:
                if not e[0] == 1062:
                    res.status_code = 500
                    res.reason_phrase = "db error:" + e[0]
                else:
                    res.status_code = 400
                    res.reason_phrase = "Duplicate entry"
                    messages.error(
                        request,
                        "A user with that email already exists. Please login if that's you or contact a department scheduler."
                    )
                    return render(
                        request, 'registration.html', {
                            'registration_form': RegisterUserForm(),
                            'errors': messages.get_messages(request)
                        })
        else:
            res.status_code = 400
            res.reason_phrase = "Invalid form entry"
    else:
        res.status_code = 400
    return res
Example #14
0
def login(request):
    if request.method == 'POST':
        name = request.POST.get('username')
        pwd = request.POST.get('password')

        if name:
            try:
                user = Author.objects.get(username=name)
            except:
                payload = {'sorry': 'invalid username !\n'}
                http_badresponse = HttpResponse(json.dumps(payload))
                http_badresponse['content-type'] = 'text/plain'
                http_badresponse.status_code = 404
                http_badresponse.reason_phrase = 'wrong username \n'
                return http_badresponse

        else:
            return HttpResponse("please enter your username and password\n")

        if pwd:
            # get pwd

            if user.password == pwd:
                request.session['name'] = user.username
                # 登陆成功
                payload = {'Hello': 'welcome!'}
                http_response = HttpResponse(json.dumps(payload))
                http_response['content-type'] = 'text/plain'
                http_response.status_code = 200
                http_response.reason_phrase = 'OK'
                return http_response
            else:
                # 登陆失败
                payload = {'sorry': 'password is wrong !'}
                http_badresponse = HttpResponse(json.dumps(payload))
                http_badresponse['content-type'] = 'text/plain'
                http_badresponse.status_code = 404
                http_badresponse.reason_phrase = ' password is wrong'
                return http_badresponse
        else:
            return HttpResponse("please enter your username and password")

    # post request
    else:
        payload = {'request problem': 'need POST request '}
        http_badresponse = HttpResponse(json.dumps(payload))
        http_badresponse['content-type'] = 'text/plain'
        http_badresponse.status_code = 404
        http_badresponse.reason_phrase = 'need POST request'
        return http_badresponse
Example #15
0
    def error_response(self,
                       content='',
                       mimetype=None,
                       content_type=settings.DEFAULT_CONTENT_TYPE):
        """Error response generator. Returns a Django HttpResponse with status
        401 and the approproate headers set. See Django documentation for details.
        https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpResponse.__init__

        **Kwargs:**

        * *content:* See Django docs. *Default ''*
        * *mimetype:* See Django docs. *Default None*
        * *content_type:* See Django docs. *Default DEFAULT_CONTENT_TYPE*

        """
        response = HttpResponse(content=content,
                                mimetype=mimetype,
                                content_type=content_type)
        if not self.attempted_validation:
            response['WWW-Authenticate'] = 'Bearer realm="%s"' % REALM
            response.status_code = 401
            return response
        else:
            if self.error is not None:
                error = getattr(self.error, "error", "invalid_request")
                error_description = self.error.message
            else:
                error = "invalid_request"
                error_description = "Invalid Request."
            header = [
                'Bearer realm="%s"' % REALM,
                'error="%s"' % error,
                'error_description="%s"' % error_description
            ]
            if isinstance(self.error, InsufficientScope):
                header.append('scope=%s' % ' '.join(self.authorized_scope))
                response.status_code = 403
                response.reason_phrase = 'FORBIDDEN'
            elif isinstance(self.error, InvalidToken):
                response.status_code = 401
                response.reason_phrase = 'UNAUTHORIZED'
            elif isinstance(self.error, InvalidRequest):
                response.status_code = 400
                response.reason_phrase = 'BAD REQUEST'
            else:
                response.status_code = 401
                response.reason_phrase = 'UNAUTHORIZED'
            response['WWW-Authenticate'] = ', '.join(header)
            return response
Example #16
0
    def error_response(self,
            content='',
            mimetype=None,
            content_type=settings.DEFAULT_CONTENT_TYPE):
        """Error response generator. Returns a Django HttpResponse with status
        401 and the approproate headers set. See Django documentation for details.
        https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpResponse.__init__

        **Kwargs:**

        * *content:* See Django docs. *Default ''*
        * *mimetype:* See Django docs. *Default None*
        * *content_type:* See Django docs. *Default DEFAULT_CONTENT_TYPE*

        """
        response = HttpResponse(
            content=content,
            mimetype=mimetype,
            content_type=content_type)
        if not self.attempted_validation:
            response['WWW-Authenticate'] = 'Bearer realm="%s"' % REALM
            response.status_code = 401
            return response
        else:
            if self.error is not None:
                error = getattr(self.error, "error", "invalid_request")
                error_description = self.error.message
            else:
                error = "invalid_request"
                error_description = "Invalid Request."
            header = [
                'Bearer realm="%s"' % REALM,
                'error="%s"' % error,
                'error_description="%s"' % error_description]
            if isinstance(self.error, InsufficientScope):
                header.append('scope=%s' % ' '.join(self.authorized_scope))
                response.status_code = 403
                response.reason_phrase = 'FORBIDDEN'
            elif isinstance(self.error, InvalidToken):
                response.status_code = 401
                response.reason_phrase = 'UNAUTHORIZED'
            elif isinstance(self.error, InvalidRequest):
                response.status_code = 400
                response.reason_phrase = 'BAD REQUEST'
            else:
                response.status_code = 401
                response.reason_phrase = 'UNAUTHORIZED'
            response['WWW-Authenticate'] = ', '.join(header)
            return response
Example #17
0
def GetCourseInfo(request):
    res = HttpResponse()
    if request.method == "GET":
        try:
            term = request.GET.get('schedule')
            schedule = Schedule.get_schedule(term_name=term)
            course_name = request.GET.get('course')
            course = Course.get_course(name=course_name)
            cohort_data = CohortData.get_cohort_data(schedule=schedule,
                                                     course=course).all()
            cohort_total = CohortTotal.get_cohort_total(
                schedule=schedule).all()

            data = {}
            data['course'] = course.to_json()
            tmp = {}
            for c in cohort_data:
                tmp[c.major] = [c.freshman, c.sophomore, c.junior, c.senior]
            data['cohort_data'] = tmp
            tmp = []
            for c in cohort_total:
                tmp[c.major] = [c.freshman, c.sophomore, c.junior, c.senior]
            data['cohort_total'] = tmp
            res.write(json.dumps(data))
        except KeyError as e:
            res.status_code = 400
            if term is None:
                res.reason_phrase = "Missing schedule in query string"
            elif course is None:
                res.reason_phrase = "Missing course in query string"
            else:
                res.status_code = 500
        except ObjectDoesNotExist:
            res.status_code = 400
            if schedule is None:
                res.reason_phrase = "Schedule '%s' does not exist" % (
                    request.GET.get('schedule'), )
            if course is None:
                res.reason_phrase = "Course '%s' does not exist" % (
                    request.GET.get('course'), )
            elif cohort_data is None or cohort_total is None:
                res.reason_phrase = "No cohort data for schedule '%s' and course '%s'" % (
                    schedule.name, course.name)
            else:
                res.status_code = 500
    else:
        res.status_code = 400
    return res
Example #18
0
def RoomsView(request):
    res = HttpResponse()
    if request.method == "GET":
        return render(
            request, 'rooms.html', {
                'room_list': Room.objects.filter(),
                'add_room_form': AddRoomForm(),
                'delete_room_form': DeleteRoomForm(),
                'edit_room_form': EditRoomForm(auto_id='edit_room_%s')
            })
    elif request.method == "POST" and 'add-form' in request.POST:
        form = AddRoomForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                return HttpResponseRedirect("/resources/rooms")
            except ValidationError as e:
                res.status_code = 400
                res.reason_phrase = "Invalid form entry"
            except IntegrityError as e:
                if not e[0] == 1062:
                    res.status_code = 500
                    res.reason_phrase = "db error:" + e[0]
                else:
                    res.status_code = 400
                    res.reason_phrase = "Duplicate entry"
        else:
            res.status_code = 400
            res.reason_phrase = "Invalid form entry"
    elif request.method == "POST" and 'edit-form' in request.POST:
        form = EditRoomForm(request.POST)
        if form.is_valid():
            form.save()
            res.status_code = 200
            return HttpResponseRedirect('/resources/rooms')
        else:
            res.status_code = 400
    elif request.method == "POST" and 'delete-form' in request.POST:
        form = DeleteRoomForm(request.POST)
        if form.is_valid():
            form.deleteRoom()
            res.status_code = 200
            return HttpResponseRedirect('/resources/rooms')
        else:
            res.status_code = 400
    else:
        res.status_code = 400
    return res
def validate(request):
    """Validate that the sent file can be classified. If the file is valid, a
    response will be sent with the content "Valid". If the file is invalid, a
    response will be sent with the content "Invalid". If any error occurs,
    a proper status code will be set for the response.
    """
    
    # If no file was passed, send a failed status code.
    if ('file' not in request.FILES):
        response = HttpResponse()
        response.status_code = 400; # Bad Request
        response.reason_phrase = ("No file was passed. File is expected as a "
                                  "parameter named 'file' in a set of form "
                                  "data.")
        return response
    
    # Read in the file.
    contents = request.FILES['file'].read()
    
    # Check .exe format
    with ExeRawSample(data=contents) as exeSample:
        if (exeSample.validate()):
            return save_sample(request, exeSample, 'exe')
    
    # No valid format was found.
    response = HttpResponse(json.dumps({'Valid': False}))
    return response
Example #20
0
def action(request, token, type, name):
    user = User.get_token(token)
    token = Token.objects.filter(user=user).filter(token=token).get()
    if not token.get_prop('webdav_enabled', False):
        response = HttpResponse()
        response.status_code = 403
        response.reason_phrase = 'This token is not allowed for webdav'
        return response


    try:
        if request.method == 'DELETE':
            return call_delete(request, token, type, name)
        elif request.method == 'GET':
            return call_get(request, token, type, name)
        elif request.method == 'PUT':
            return call_put(request, token, type, name)
        elif request.method == 'PROPFIND':
            return call_propfind(request, token, type)
        elif request.method == 'MOVE':
            return call_move(request, token, type, name)
        else:
            return HttpResponse('webdav endpoint')
    except Exception, e:
        return HttpResponse(str(e))
Example #21
0
def user_view_userphoto_field(request, userid, action):
    data = {}
    u = models.User.objects.get(uidnumber=userid)
    if action == 'value':
        if request.method == 'POST':
            # here we have only one file
            # TODO: accepts any file, should be changed to only accept jpeg
            if 'userphoto' in request.FILES:
                from django.conf import settings
                import os
                # get file, write it to disk
                f = request.FILES['userphoto']
                data['name'] = f.name
                data['size'] = f.size
                data['content_type'] = f.content_type
                if settings.DEBUG:
                    if hasattr(settings, 'MAX_UPLOAD_SIZE'):
                        if f.size > settings.MAX_UPLOAD_SIZE:
                            r = HttpResponse()
                            r.status_code = 413
                            r.reason_phrase = 'REQUEST_ENTITY_TOO_LARGE'
                            return r
                # generate file name
                fname = os.path.join(str(u.uidnumber), f.name)
                fdest = os.path.join(settings.USER_PHOTO_PATH, fname)
                destdir = os.path.dirname(fdest)
                try:
                    os.makedirs(destdir)
                except OSError as e:
                    pass
                # 2 paths depending on file size
                fdesc = open(fdest, 'wb')
                if f.multiple_chunks():
                    for chunk in f.chunks():
                        fdesc.write(chunk)
                else:
                    d = f.read()
                    fdesc.write(d)

                fdesc.close()
                u.photo_path = f.name
                u.save(request_user=request.user)

                import json
                c = models.Command()
                c.user = request.user
                c.verb = "UpdatePhoto"
                c.data = json.dumps({'uid': u.login})
                c.in_cron = True
                c.post()

    if u.photo_path is None:
        data['url'] = None
    else:
        data['url'] = reverse('user-view-photo',
                              args=(
                                  u.uidnumber,
                                  u.photo_path,
                              ))
    return data
Example #22
0
def HandleView(request):
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'

    if request.method != 'GET':
        http_bad_response.content = 'Only GET request is allowed'
        return http_bad_response

    new_list = []
    prof_list = []
    for prof_id in Professor.objects.all().values('professor_id'):
        prof_id_get = prof_id.get('professor_id')
        prof_list.append(prof_id_get)

    for professor in prof_list:
        rating_prof = Rating.objects.filter(
            which_professor__professor_id=professor).aggregate(Avg('rating'))
        raw_rating = rating_prof.get('rating__avg')
        rounded = int(
            Decimal(raw_rating).quantize(Decimal('1'), rounding=ROUND_HALF_UP))

        ratingobjects = {'code': professor, 'rating': rounded}
        new_list.append(ratingobjects)

    payload = {'rating_list': new_list}

    http_response = HttpResponse(json.dumps(payload))
    http_response['Content-Type'] = 'application/json'
    http_response.status_code = 200
    http_response.reason_phrase = 'OK'

    return http_response
Example #23
0
  def uploadFiletoFolder(request, foldercode):
    if request.method != 'POST':
      return HttpResponseNotAllowed(['post'], content='Only POST request method is allowed')

    if len(list(request.FILES.items())) == 0:
      return HttpResponseNotFound('Missing file selection in request')
    errorcount = 0
    response = HttpResponse()
    folder, extensions = FileManager.getFolderInfo(request, foldercode)
    for filename, content in request.FILES.items():
      try:
        # Validate file name
        clean_filename = re.split(r'/|:|\\', filename)[-1]
        if not extensions or not clean_filename.lower().endswith(extensions):
          response.write('%s: %s\n' % (clean_filename, _("Filename extension must be among %(ext)s") % {"ext": ", ".join(extensions)}))
          errorcount += 1
          continue

        # Write to a file
        with open(os.path.join(folder, clean_filename), 'wb') as thetarget:
          for chunk in content.chunks():
            thetarget.write(chunk)

        response.write(force_text('%s: %s\n' % (clean_filename, _('OK'))))
      except Exception as e:
        logger.error("Failed file upload: %s" % e)
        response.write('%s: %s\n' % (clean_filename, _("Upload failed") ))
        errorcount += 1
    response.write(force_text('%s' % capfirst(_('finished'))))
    if errorcount:
      response.status_code = 400
      response.reason_phrase = '%s files failed to upload correctly' % errorcount
    return response
Example #24
0
def call_delete(request, token, type, name):
    user = User.get_token(token)

    images = Image.objects.filter(user=user).filter(state='ok').all()
    image = None
    for i in images:
        if name == urllib.quote_plus(i.name):
            image = i

    if image == None:
        response = HttpResponse()
        response.status_code = 404
        response.reason_phrase = "Not found"
        return response

    task = Task()
    task.type = 'image'
    task.action = 'delete'
    task.state = 'not active'
    task.image = image
    task.addAfterImage()

    response = HttpResponse()
    response.status_code = 200
    return response
Example #25
0
def proxy_tunnel(request, *args, **kwargs):
	path = request.get_full_path()
	request_body = request.body
	save_to_file(request_body)

	if settings.TARGET_PORT == 443:
		connector = httplib.HTTPSConnection
	else:
		connector = httplib.HTTPConnection

	connection = connector(settings.TARGET_HOST, settings.TARGET_PORT)

	# TODO gormezden gelmek cozum degil ama belki sorun da yoktur
	headers = {k:(lambda v: v.decode("utf-8", "ignore") if type(v)==str else v )(val) for k,val in request.META.items()}
	connection.request(request.method, path, body=request_body, headers=headers)

	target_resp = connection.getresponse()

	response = HttpResponse()	
	response.status_code = target_resp.status
	response.reason_phrase = target_resp.reason
		
	for header_name, value in target_resp.getheaders():
		response[header_name] = value
	
	resp_body = target_resp.read()
	response.write(resp_body)

	save_access(request_meta=str(request.META), response=resp_body, ip=request.get_host())
	
	return response
Example #26
0
    def report(self, request, user, resource_name):
        resource = self.get_resource(request, user, resource_name)

        try:
            dom = etree.fromstring(request.read())
        except:
            raise davvy.exceptions.BadRequest()

        # print etree.tostring(dom, pretty_print=True)

        doc = etree.Element('{DAV:}multistatus')

        if dom.tag == '{urn:ietf:params:xml:ns:carddav}addressbook-multiget':
            hrefs = dom.iterfind('{DAV:}href')
            for href in hrefs:
                resource = self.get_resource(
                    request, user, href.text[len(request.path):])
                if not resource.collection:
                    doc.append(
                        self._multiget_response(request, resource, href.text))

        elif dom.tag in ('{urn:ietf:params:xml:ns:carddav}addressbook-query', '{DAV:}sync-collection'):
            for child in resource.resource_set.all():
                doc.append(self._multiget_response(
                    request, child, request.path.rstrip('/') + '/' + child.name))
        else:
            raise davvy.exceptions.BadRequest()

        # print etree.tostring(doc, pretty_print=True)

        response = HttpResponse(
            etree.tostring(doc, pretty_print=True), content_type='text/xml; charset=utf-8')
        response.status_code = 207
        response.reason_phrase = 'Multi-Status'
        return response
Example #27
0
def get_wfs_csv(request):
    qdict = request.GET
    typename = qdict['lyrname']
    category_field = qdict['category']
    quantity_field = qdict['quantity']

    lyr = Layer.objects.get(typename=typename)
    featno = get_featno(lyr.id)
    if featno > settings.MAX_CSV_RECORDS:
        response = HttpResponse('{0} has too many records; csv download'
                                ' is not available for very large '
                                'datasets'.format(lyr.title))
        response.status_code = 413
        response.reason_phrase = 'REQUEST ENTITY TOO LARGE'
        return response

    params = urllib.urlencode({
        'service': 'WFS',
        'version': '1.1.0',
        'request': 'GetFeature',
        'typename': typename,
        'propertyName': category_field + ',' + quantity_field,
        'outputFormat': 'csv',
        'maxFeatures': str(settings.MAX_CSV_RECORDS)
    })

    wfs_baseurl = lyr.link_set.get(link_type='OGC:WFS').url
    wfs_request = urllib.urlopen(wfs_baseurl + '?%s' % params)
    content = wfs_request.read()
    response = HttpResponse(content, content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="myfile.csv"'
    return response
Example #28
0
def view(request):
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'

    if (request.method != 'GET'):
        http_bad_response.content = 'Only GET requests are valid\n'
        return http_bad_response

    profList = models.Teacher.objects.all()
    the_list = []
    for professor in profList:
        rateSum = 0
        avgRate = 0
        ratingList = models.Rating.objects.filter(teacher=professor.id)
        numRatings = models.Rating.objects.filter(teacher=professor.id).count()
        for profRate in ratingList:
            rateSum = rateSum + profRate.Rating
        if rateSum > 0:
            avgRate = math.trunc((rateSum / numRatings) + 0.5)
        else:
            avgRate = 0
        name = professor.profName[0] + "." + professor.profLastName
        item = {'Rating': avgRate, 'name': name}
        the_list.append(item)
    payload = {'phrase': the_list}
    http_response = HttpResponse(json.dumps(payload))
    http_response['Content-Type'] = 'application/json'
    http_response.status_code = 200
    http_response.reason_phrase = 'OK'
    return http_response
def postPuzzle(request):
    bodyUnicode = request.body.decode('utf-8')  #decodes bytes into string
    bodyData = json.loads(bodyUnicode)  #decodes string into dictionary

    newPuzzle = Puzzle.objects.create(title=bodyData['title'],
                                      creationDate=timezone.now(),
                                      length=bodyData['length'])
    for word in bodyData['words']:
        Word.objects.create(puzzle=newPuzzle, word=word)

    try:
        #Try to generate puzzle 3 times before concluding that it must be impossible
        for i in range(3):
            newMatrix = generateWordSearchHard(bodyData['words'],
                                               bodyData['length'])
            if newMatrix:
                break
            elif i == 2:
                raise ValueError
    except ValueError:
        res = HttpResponse()
        res.status_code = 400
        res.reason_phrase = 'NOT CREATED. Try shorter words or a larger puzzle size.'
        Puzzle.objects.get(pk=newPuzzle.id).delete()
        return res

    for row in newMatrix:
        r = Row.objects.create(puzzle=newPuzzle)
        for letter in row:
            Cell.objects.create(row=r, value=letter)

    return JsonResponse({"id": newPuzzle.id}, safe=False)
Example #30
0
def View(request):
    retList = []

    # Get list of professors
    prof_list = Professor.objects.all()
    for p in prof_list:
        rating = 0
        length = len(p.rating_set.all())

        if (length > 0):
            for rate in p.rating_set.all():
                rating += rate.rating

            rating = Decimal(rating / length).quantize(Decimal('1'),
                                                       rounding=ROUND_HALF_UP)
            rating = int(rating)

        name = p.fname + ' ' + p.lname
        item = {'Name': name, 'Rating': rating}
        retList.append(item)

    # Create payload
    payload = {'professors': retList}

    # Create HttpResponse
    http_response = HttpResponse(json.dumps(payload))
    http_response['Content-Type'] = 'application/json'
    http_response.reason_phrase = 'OK'
    return http_response
Example #31
0
def List(request):
    # get list of modules from the database
    module_list = moduleInstance.objects.all()
    the_list = []
    for m in module_list:
        # Get list of professors
        prof_list = []
        for p in m.professor.all():
            name = p.fname + ' ' + p.lname
            prof_list.append(name)

        item = {
            'Code': m.module.moduleCode,
            'Module Name': m.module.name,
            'Year': m.year,
            'Semester': m.semester,
            'Taught By': prof_list
        }
        the_list.append(item)

    # Create Payload
    payload = {'module_list': the_list}

    # Create HttpResponse
    http_response = HttpResponse(json.dumps(payload))
    http_response['Content-Type'] = 'application/json'
    http_response.reason_phrase = 'OK'
    return http_response
Example #32
0
    def get(self, request, *args, **kwargs):

        response = HttpResponse()

        response.status_code = 403
        response.reason_phrase = 'Unauthorized'
        return response
Example #33
0
def list(request):
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'

    if (request.method != 'GET'):
        http_bad_response.content = 'Only GET requests are valid\n'
        return http_bad_response

    module_list = models.Module.objects.all().values('module_ID', 'name',
                                                     'semester', 'year',
                                                     'teachers')
    the_list = []
    for r in module_list:
        profName = models.Teacher.objects.get(id=r['teachers'])
        string = str(profName.profID) + ", " + str(
            profName.profName)[0] + "." + str(profName.profLastName)
        item = {
            'ID': r['module_ID'],
            'name': r['name'],
            'sem': r['semester'],
            'year': r['year'],
            'tc': string
        }
        the_list.append(item)
    payload = {'phrase': the_list}
    http_response = HttpResponse(json.dumps(payload))
    http_response['Content-Type'] = 'application/json'
    http_response.status_code = 200
    http_response.reason_phrase = 'OK'
    return http_response
Example #34
0
def queueQuestion(request):			
	try:
		#All POST data is apparently escaped by Django
		#Sanitizing and checking additional criteria		
		post_data = request.POST
		question_text = sanitizeInput(post_data['question_text'], 'question')
		sender = sanitizeInput(post_data['sender'], 'email').lower()		
		question_type = sanitizeInput( post_data['question_type'], 'question_type')

		#An empty 'sent'_to will generate a custom url for use
		if len(post_data['sent_to']) >= 6:
			sent_to = sanitizeInput(post_data['sent_to'], 'email').lower()
		else:
			sent_to = "Generate"	

		if question_type == "Multiple" or question_type == "Secret":
			answers = getAnswers(post_data)						
			
			#Typecast the answer radio button value to verify it's a normal number
			try:
				selected_answer = int( post_data['selected_answer'] )
			except:
				selected_answer = False
		else:
			selected_answer = "Open"
			answers = "Open"		
		
		if (sender is not False and sent_to is not False and 
			answers is not False and question_text is not False and
			selected_answer is not False and question_type is not False):
			#Input has been sanitized and checked and can be inserted into the DB			
			create_new_paper(sender=sender, ip=get_client_ip(request), question=question_text,
							 sent_to=sent_to, answers=answers, selected_answer=selected_answer,
							 question_type=question_type)
			
		else:			
			#Build and throw an error, some input is incorrect
			#This should be caught with Javascript but including checks on back-end as well.
			#Can't trust users
			incorrectFields = []
			if sender == False:
				incorrectFields.append("Your E-mail")
			if sent_to == False:
				incorrectFields.append("Recipients E-mail")
			if question_text == False:
				incorrectFields.append("Question")
			if answers == False:
				incorrectFields.append("Answers")

			#Return http response with error code 400 and text with incorrect fields.
			response = HttpResponse()
			response.status_code = 400

			response.reason_phrase = "Error in field(s): " + ' | '.join(incorrectFields)
			return response
	

	except Exception:		
		return (HttpResponseRedirect('/ask') )
Example #35
0
def HandleViewRequest(request):
    is_get, bad_response = GET_req_checker(request)

    if not is_get:
        return bad_response

    if not Token.objects.get(key=request.headers['Authorization']):
        response = HttpResponse()
        response['Content-Type'] = 'application/text'
        response.status_code = 401
        response.reason_phrase = 'Not Logged in'
        return response

    return_list = []

    for i in Professor.objects.all():

        total = 0
        counter_final = 0

        try:
            for j in Rating.objects.filter(professor_code=i):
                total += j.rating
                counter_final += 1
        except ObjectDoesNotExist:
            continue

        if counter_final == 0:
            continue

        item = {
            "name": i.name,
            "code": i.professor_code,
            "rating": total / counter_final
        }

        return_list.append(item)

    payload = {"professors": return_list}

    response = HttpResponse(json.dumps(payload))
    response['Content-Type'] = 'application/json'
    response.status_code = 200
    response.reason_phrase = 'OK'

    return response
def classify(request):
    """Classify the requested file. The request should not include the file
    to classify; instead, the file should have already been uploaded when it
    was validated and the request should include the ID that the validation
    service responded with.
    """
    
    # Check if an ID was supplied.
    if ('ID' not in request.POST):
        response = HttpResponse()
        response.status_code = 400 # Bad Request
        response.reason_phrase = ('No ID was passed. The ID of the file to '
                                  'classify should have been returned by the '
                                  'validation service. You must send this ID '
                                  'with the parameter name \'ID\' when '
                                  'requesting classification')
        return response
        
    # Ensure a file exists with the specified ID.
    id = request.POST['ID']
    if (not File.objects.filter(file_name=id).exists()):
        response = HttpResponse()
        response.status_code = 400 # Bad Request
        response.reason_phrase = ('The passed ID was invalid. If the ID you '
                                  'sent was returned by a validate request, '
                                  'it is possible the ID has expired and the '
                                  'file was deleted.')
    
    # Create a job for the classification.
    job = Job()
    job.save()
    
    file = File.objects.get(file_name=id)
    file.job = job
    file.save()
    
    # Perform the job asynchronously in a new thread.
    Thread(target=perform_job, args=(file,)).start()
        
    # Indicate the classification job has started.
    response = HttpResponse(('The requested classification job has been '
                             'started. You can retrieve the progress of the '
                             'job by sending the file ID to the '
                             'classify/result service.'))
    response.status_code = 202 # Accepted
    return response    
Example #37
0
def basic_authentication_response(app_name):
    response = HttpResponse()
    response.status_code = 401
    response.reason_phrase = "Unauthorized"
    response['WWW-Authenticate'] = 'Basic realm="{}"'.format(app_name)
    with open(BASE_DIR + '/templates/portal/401.html', 'r') as fd:
        response.write(fd.read())
    return response
Example #38
0
def call_get(request, token, type, name):
    user = User.get_token(token)

    images = Image.objects.filter(user=user).filter(state='ok').all()
    image = None
    for i in images:
        if name == urllib.quote_plus(i.name):
            image = i

    if image == None:
        response = HttpResponse()
        response.status_code = 404
        response.reason_phrase = "Not found"
        return response

    conn = libvirt.open('qemu:///system')
    storage = conn.storagePoolLookupByName(image.storage.name)
    if storage.info()[0] != libvirt.VIR_STORAGE_POOL_RUNNING:
        response = HttpResponse()
        response.status_code = 500
        response.reason_phrase = 'Storage unavailable'
        return response

    storage.refresh(0)
    volume = storage.storageVolLookupByName(image.libvirt_name)
    stream = conn.newStream(0)

    try:
        def downloader(size):
            bytes = 0
            while bytes < size:
                chunk = stream.recv(1024*1024)
                if len(chunk) == 0:
                    break
                yield chunk
                bytes += len(chunk)


        volume.download(stream, 0, volume.info()[1], 0)
        response = StreamingHttpResponse(downloader(volume.info()[1]), content_type="text/plain")
        conn.close()
        return response
    except Exception, e:
        response = HttpResponse()
        response.status_code = 500
        return response
Example #39
0
def call_put(request, token, type, name):
    user = User.get_token(token)
    user.check_storage(len(request.body))

    filename = os.path.join(settings.UPLOAD_DIR, 'oc_upload_%s' % user.id)
    if os.path.exists(filename):
        response = HttpResponse()
        response.status_code = 403
        response.reason_phrase = "You have upload active"
        return response

    if len(request.body) > settings.MAX_UPLOAD_CHUNK_SIZE:
        response = HttpResponse()
        response.status_code = 403
        response.reason_phrase = "File too large (max. size %d)" % settings.MAX_UPLOAD_CHUNK_SIZE
        return response

    f = open(filename, 'w')
    f.write(request.body)
    f.close()

    image = Image.create(user, name, "", 1, type, 'virtio', 'private', 'raw')
    image.save()

    task = Task()
    task.type = 'image'
    task.action = 'create'
    task.state = 'not active'
    task.image = image
    task.storage = image.storage
    task.addAfterStorage()

    task = Task()
    task.type = 'image'
    task.action = 'upload_data'
    task.state = 'not active'
    task.image = image
    task.set_all_props({'offset': 0,
                        'size': len(request.body),
                        'filename': filename})
    task.addAfterImage()

    return HttpResponse()
Example #40
0
def annotated(request):
    path = os.path.dirname(os.path.abspath(__file__))
    
    # store the posted file as a global html file, if any
    if 'html' in request.FILES:
        content = request.FILES['html'].read()
        html = request.FILES['html'].name
        f = open(path + html, 'w+')
        f.write(content)
        f.close()
        response = HttpResponse(content_type='text/html')
        response.write(content)
        return response

    # if userid, then set path to user's project folder
    if not 'userid' in request.GET:
        return render(request, 'entity/annotated.html')    
    
    userid = request.GET['userid']

    # check the userid is alphanumeric for security
    if not re.match('^[\w]+$', userid):
        response = HttpResponse()
        response.status_code = 500
        response.reason_phrase = 'Userid must be alphanumeric.'
        return response

    # define the user's project path
    path = path + "/projects/" + userid + "/"

    # check if this is a request to load the file
    if 'proj' in request.GET and request.GET['proj'] != "":
        html = request.GET['proj'] + ".html"

        if html == ".html":
            return render(request, 'entity/annotated.html')  
        elif os.path.isfile(path + html):
            response = HttpResponse(content_type='text/html')
            with open(path + html, 'r') as f:
                content = f.read()
                response.write(content)
                return response
        else:
            return HttpResponse("Request not found: " + html)

    # else, check if this is a request to save the file
    elif 'proj' in request.POST and request.POST['proj'] != "":
        html = request.POST['proj'] + ".html"
        html_content = request.POST['annotated']

        with open(path + html, 'w+') as f:
            f.write(html_content)
        return HttpResponse("Request posted: " + html)

    return render(request, 'entity/annotated.html')    
Example #41
0
    def build_error_response(self):
        """
        Send an error response to a client.

        For an example see class docstring.
        """
        resp = HttpResponse(content_type='application/json',
                            content=json.dumps(self.output_doc))
        resp.status_code = 400
        resp.reason_phrase = 'bad request'
        return resp
Example #42
0
 def to_json(request, *args, **kwargs):
     """
     Creates the actual HttpResponse with json content.
     """
     data = f(request, *args, **kwargs)
     response = HttpResponse(json.dumps(data, sort_keys=True, indent=4),
                             content_type="application/json")
     if not data:
         response.status_code = 404
         response.reason_phrase = 'Not found'
     return response
Example #43
0
def check_username(request):
    if request.method == 'POST':
        response = HttpResponse()
        if User.objects.filter(username=request.POST['username']).count():
            response.content = "Username is already taken"
            response.reason_phrase = "Username must not already be taken"
            response.status_code = 498
            #return username is not unique
        else:
            response.content = "Username is acceptable"
            response.status_code = 200
            #return username is unique
        return response
Example #44
0
 def process_response(self, request, response):
     if random() >= 0.5 and DRF_CHAOS_ENABLED:
         time.sleep(randint(0, 3))
         response = HttpResponse()
         status_code = choice(REASON_PHRASES.keys())
         response.status_code = status_code
         response.reason_phrase = REASON_PHRASES.get(
             status_code,
             'UNKNOWN STATUS CODE'
         )
         response.content = "drf-chaos: {}".format(
             response.reason_phrase
         )
     return response
Example #45
0
def get(request_method, url, headers):
    """
    Send a get or head request to DataCite.

    Args:
        request_method (str): This should be 'GET' or 'HEAD'
        url (str): The URL to call
        headers (dict): A dictionary of headers to use

    Return:
        a HTTPResponse

    """
    LOGGING.info('get(%s,%s,%s)', request_method, url, headers)
    _set_timeout()
    opener = get_opener()
    auth_string = (base64.encodestring(DATACITE_USER_NAME + ':'
                                       + DATACITE_PASSWORD)).rstrip()
    headers.update({'Authorization':'Basic ' + auth_string})
    req = urllib2.Request(url, data=None, headers=headers)
    if request_method == "HEAD":
        req.get_method = lambda: 'HEAD'
    try:
        response = opener.open(req)
    except (urllib2.HTTPError) as ex:
        msg = ex.readlines()
        if ex.code in [404, 410]:
            LOGGING.info('HTTPError error getting %s. %s', url, msg)
        else:
            LOGGING.warn('HTTPError error getting %s. %s', url, msg)
        return get_response(msg, ex.code)
    except (socket.timeout, urllib2.URLError) as ex:
        LOGGING.warn('Timeout or URLError error getting %s. %s', url, ex.reason)
        return get_response(ex.reason, 500)
    except (SSLError) as ex:
        LOGGING.warn('SSLError error getting %s. %s', url, ex)
        return get_response(ex, 500)
    finally:
        _close(opener)
    if response.headers.has_key('Content-Type'):
        ret_response = HttpResponse(content_type=
                                    response.headers.get('Content-Type'))
    else:
        ret_response = HttpResponse()
    ret_response.status_code = response.code
    ret_response.reason_phrase = response.msg
    # pylint: disable=maybe-no-member
    ret_response.writelines(response.readlines())
    return ret_response
Example #46
0
 def wrap(request, **kwargs):
     token = request.REQUEST.get("token", None)
     response = HttpResponse()
     if token:
         # 检查token值是否过期
         if re.match("^" + TOKEN_PREFIX + "[0-9\-a-zA-Z]+$", token):
             mc = get_mc()
             val = mc.get(str(token))
             if val:
                 # 对网页进行处理(后期要根据token值进行权限控制)
                 # request.REQUEST["username"] = val
                 return func(request, val, **kwargs)
                 # return func(request, **kwargs)
             else:
                 response.status_code = 401
                 response.reason_phrase = "token timeout"
         else:
             response.status_code = 401
             response.reason_phrase = "invalid token"
     else:
         # 说明没有传递token值过来
         response.status_code = 401
         response.reason_phrase = "unauthorized"
     return response
Example #47
0
def automatic_ping(request, **kwargs):
    """ Handles browser queries, and updates browser status when required. """
    location = request.GET.get("location")
    if location:
        if hasattr(request, "browser") and request.browser:
            bcache.set("last-known-location-%s" % request.browser.bid_public, location, 3600)
            bcache.set("last-known-location-timestamp-%s" % request.browser.bid_public, time.time(), 3600)
            bcache.set("last-known-location-from-%s" % request.browser.bid_public, request.remote_ip, 3600)
        activity = request.GET.get("activity")
        hidden = request.GET.get("hidden")
        error = request.GET.get("error")
        client_t = request.GET.get("t")
        client_c = request.GET.get("c")
        client_r = request.GET.get("r")
        client_u = request.GET.get("u")
        if error:
            custom_log(request, "Ping: an error occured: %s - %s" % (location, error), level="error")
        custom_log(request, "Ping from %s - %s - %s - %s - %s - %s - %s" % (location, activity, hidden, client_t, client_c, client_r, client_u))
    ret = {}
    sign_out = False
    if not request.browser:
        # TODO: check whether browser thinks it's still signed in.
        pass
    elif request.browser.forced_sign_out and not request.GET.get("forced_sign_out"):
        # User is not authenticated. If the browser thinks otherwise, fix that.
        ret["not_signed_in"] = True
        ret["redirect_location"] = reverse("login_frontend.views.indexview")+"?forced_sign_out=true"
        sign_out = True

    if kwargs.get("img"):
        #response = HttpResponse(open(settings.PROJECT_ROOT+"/static/img/clear.gif").read(), content_type="image/gif")
        response = HttpResponse()
        response.status_code = 204
        response.reason_phrase = "No Content"
    else:
        response = HttpResponse(json.dumps(ret), content_type="application/json")
        if kwargs.get("external") and request.GET.get("location"):
            try:
                parsed = urlparse.urlparse(request.GET.get("location"))
                if parsed.hostname.endswith(".futurice.com"):
                    response["Access-Control-Allow-Origin"] = "https://"+parsed.hostname
            except:
                pass
    if sign_out:
        pubtkt_logout(request, response)
    return response
Example #48
0
    def report(self, request, user, resource_name):
        resource = self.get_resource(request, user, resource_name)

        try:
            dom = etree.fromstring(request.read())
        except:
            raise davvy.exceptions.BadRequest()

        # print etree.tostring(dom, pretty_print=True)

        doc = etree.Element('{DAV:}multistatus')

        if dom.tag == '{urn:ietf:params:xml:ns:caldav}calendar-query':
            doc.append(
                self._multiget_response(request, resource, request.path))
            for child in resource.resource_set.all():
                doc.append(self._multiget_response(
                    request, child, request.path.rstrip('/') + '/' + child.name))
        elif dom.tag == '{DAV:}sync-collection':
            doc.append(self._multiget_response(
                request, resource, request.path, 'sync-response'))
            for child in resource.resource_set.all():
                doc.append(self._multiget_response(
                    request, child, request.path.rstrip('/') + '/' + child.name, 'sync-response')
                )

            doc.append(davvy.xml_node(
                '{DAV:}sync-token', prop_dav_calendar_getctag(self, request, resource))
            )
        elif dom.tag == '{urn:ietf:params:xml:ns:caldav}calendar-multiget':
            hrefs = dom.iterfind('{DAV:}href')
            for href in hrefs:
                child = self.get_resource(
                    request, user, self.get_href(href.text, resource_name))
                doc.append(self._multiget_response(request, child, href.text))
        else:
            raise davvy.exceptions.BadRequest()

        # print etree.tostring(doc, pretty_print=True)

        response = HttpResponse(
            etree.tostring(doc, pretty_print=True), content_type='text/xml; charset=utf-8')
        response.status_code = 207
        response.reason_phrase = 'Multi-Status'
        return response
Example #49
0
def call_move(request, token, type, name):
    user = User.get_token(token)

    images = Image.objects.filter(user=user).filter(state='ok').all()
    image = None
    for i in images:
        if name == urllib.quote_plus(i.name):
            image = i

    if image == None:
        response = HttpResponse()
        response.status_code = 404
        response.reason_phrase = "Not found"
        return response

    image.name = os.path.basename(request.META['HTTP_DESTINATION'])
    image.save()
    return HttpResponse()
Example #50
0
def browse(request, token, type):
    user = User.get_token(token)
    token = Token.objects.filter(user=user).filter(token=token).get()
    if not token.get_prop('webdav_enabled', False):
        response = HttpResponse()
        response.status_code = 403
        response.reason_phrase = 'This token is not allowed for webdav'
        return response

    try:
        if request.method == 'OPTIONS':
            return call_options(request, token, type)
        elif request.method == 'PROPFIND':
            return call_propfind(request, token, type)
        else:
            return HttpResponse('webdav endpoint')
    except Exception, e:
        return HttpResponse(str(e))
Example #51
0
  def uploadFiletoFolder(request, foldercode):
    if request.method != 'POST':
      return HttpResponseNotAllowed(['post'], content='Only POST request method is allowed')

    if len(list(request.FILES.items())) == 0:
      return HttpResponseNotFound('Missing file selection in request')
    errorcount = 0
    response = HttpResponse()
    folder, extensions = FileManager.getFolderInfo(request, foldercode)

    # Try to create the upload if doesn't exist yet
    if not os.path.isdir(settings.DATABASES[request.database]['FILEUPLOADFOLDER']):
      try:
        os.makedirs(settings.DATABASES[request.database]['FILEUPLOADFOLDER'])
      except:
        errorcount += 1
        response.write("Upload folder doesn't exist")

    if not errorcount:
      # Directory exists and we can upload files into it
      for filename, content in request.FILES.items():
        try:
          # Validate file name
          clean_filename = re.split(r'/|:|\\', filename)[-1]
          if not extensions or not clean_filename.lower().endswith(extensions):
            response.write('%s: %s\n' % (clean_filename, _("Filename extension must be among %(ext)s") % {"ext": ", ".join(extensions)}))
            errorcount += 1
            continue

          # Write to a file
          with open(os.path.join(folder, clean_filename), 'wb') as thetarget:
            for chunk in content.chunks():
              thetarget.write(chunk)

          response.write(force_text('%s: %s\n' % (clean_filename, _('OK'))))
        except Exception as e:
          logger.error("Failed file upload: %s" % e)
          response.write('%s: %s\n' % (clean_filename, _("Upload failed") ))
          errorcount += 1
      response.write(force_text('%s' % capfirst(_('finished'))))
    if errorcount:
      response.status_code = 400
      response.reason_phrase = '%s files failed to upload correctly' % errorcount
    return response
Example #52
0
    def proppatch(self, request, user, resource_name):
        resource = self.get_resource(request, user, resource_name)

        try:
            dom = etree.fromstring(request.read())
        except:
            raise davvy.exceptions.BadRequest()

        # print etree.tostring(dom, pretty_print=True)

        requested_props = []

        for setremove_item in dom:
            props = setremove_item.find('{DAV:}prop')
            if props is None:
                props = []
            # top-down must be respected
            for prop in props:
                if setremove_item.tag == '{DAV:}set':
                    try:
                        resource.set_prop(self, request, prop.tag, prop)
                        requested_props.append((prop.tag, '200 OK'))
                    except davvy.exceptions.DavException as e:
                        requested_props.append((prop.tag, e.status))
                elif setremove_item.tag == '{DAV:}remove':
                    try:
                        resource.del_prop(self, request, prop.tag)
                        requested_props.append((prop.tag, '200 OK'))
                    except davvy.exceptions.DavException as e:
                        requested_props.append((prop.tag, e.status))

        doc = etree.Element('{DAV:}multistatus')

        multistatus_response = self._proppatch_response(
            request, request.path, resource, requested_props)
        doc.append(multistatus_response)

        # print etree.tostring(doc, pretty_print=True)

        response = HttpResponse(
            etree.tostring(doc, pretty_print=True), content_type='text/xml; charset=utf-8')
        response.status_code = 207
        response.reason_phrase = 'Multi-Status'
        return response
Example #53
0
def _delete(url):
    """
    Send a delete request to DataCite.

    Args:
        url (str): The URL to call

    Return:
        a HTTPResponse

    """
    _set_timeout()
    opener = get_opener()
    auth_string = (base64.encodestring(DATACITE_USER_NAME + ':'
                                       + DATACITE_PASSWORD)).rstrip()
    headers = {'Authorization':'Basic ' + auth_string}
    req = urllib2.Request(url, data=None, headers=headers)
    req.get_method = lambda: 'DELETE'
    try:
        response = opener.open(req)
    except (urllib2.HTTPError) as ex:
        msg = ex.readlines()
        LOGGING.warn('HTTPError error getting %s. %s', url, msg)
        return get_response(msg, ex.code)
    except (socket.timeout, urllib2.URLError) as ex:
        LOGGING.warn('Timeout or URLError error getting %s. %s', url, ex.reason)
        return get_response(ex.reason, 500)
    except (SSLError) as ex:
        LOGGING.warn('SSLError error getting %s. %s', url, ex)
        return get_response(ex, 500)
    finally:
        _close(opener)
    if response.headers.has_key('Content-Type'):
        ret_response = HttpResponse(content_type=
                                    response.headers.get('Content-Type'))
    else:
        ret_response = HttpResponse()
    ret_response.status_code = response.code
    ret_response.reason_phrase = response.msg
    # pylint: disable=maybe-no-member
    ret_response.writelines(response.readlines())
    return ret_response
Example #54
0
    def dispatch(self, request, username, *args, **kwargs):
        user = None
        # REMOTE_USER should be always honored
        if 'REMOTE_USER' in request.META:
            user = User.objects.get(username=request.META['REMOTE_USER'])
        elif 'HTTP_AUTHORIZATION' in request.META:
            auth = request.META['HTTP_AUTHORIZATION'].split()
            if len(auth) == 2:
                if auth[0].lower() == "basic":
                    uname, passwd = base64.b64decode(auth[1]).split(':')
                    user = authenticate(username=uname, password=passwd)

        def _check_group_sharing(user, sharing_user):
            try:
                sharing_user = User.objects.get(username=username)
                return sharing_user.groups.all() & user.groups.all()
            except ObjectDoesNotExist:
                return None

        if (user and user.is_active) and (
                user.username == username or _check_group_sharing(user, username)):
            login(request, user)
            request.user = user
            try:
                response = super(WebDAV, self).dispatch(
                    request, username, *args, **kwargs
                )
                dav_base = ['1']
                dav_base += getattr(settings, 'DAVVY_EXTENSIONS', [])
                response['Dav'] = ','.join(dav_base + self.dav_extensions)
            except davvy.exceptions.DavException as e:
                code, phrase = e.status.split(' ', 1)
                response = HttpResponse(phrase, content_type='text/plain')
                response.status_code = int(code)
                response.reason_phrase = phrase
        else:
            response = HttpResponse('Unathorized', content_type='text/plain')
            response.status_code = 401
            response['WWW-Authenticate'] = 'Basic realm="davvy"'

        return response
Example #55
0
def number_playground_submission(request):
    if request.method == 'POST':
        form = NumberPlaygroundForm(request.POST)
        if form.is_valid():
            action = form.cleaned_data['action']
            if action == 'qstring_to_float':
                try:
                    number_from_qstring = qiki.Number(form.cleaned_data['qstring'])
                    floater = str(float(number_from_qstring))
                except Exception as e:
                    return invalid_response(str(e))
                else:
                    return valid_response('floater', floater)
            elif action == 'float_to_qstring':
                try:
                    floating_point_typed = float(form.cleaned_data['floater'])
                except Exception as e:
                    float_error = str(e)
                    try:
                        integer_typed = int(form.cleaned_data['floater'], 0)
                    except Exception as e:
                        int_error = str(e)
                        # TODO: support q-string by trying qiki.Number(floater) ?
                        return invalid_response("Either %s, or %s" % (float_error, int_error))
                    else:
                        qstring = qiki.Number(integer_typed).qstring()
                        return valid_response('qstring', qstring)
                else:
                    qstring = qiki.Number(floating_point_typed, qigits=7).qstring()
                    # XXX:  Why qigits=7 here?  The negative round-off bug?  To examine it??
                    return valid_response('qstring', qstring)
            else:
                r = HttpResponse()
                r.status_code = 404
                r.reason_phrase = "Action '%s' not supported" % action
                return r
        else:
            return HttpResponse('whoa %s' % repr(form.errors))
    else:
        return HttpResponse('Oops, this is a POST-only URL.')
Example #56
0
    def build_error_response(self):
        '''Send an error response to a client.

        Example:
        400 bad request
        ...

        [
            {
                'field': 'name',
                'message': 'Report name cannot be empty.',
            },
            {
                'message': 'Order must be under $300.',
            },
        ]
        '''
        resp = HttpResponse(content_type='application/json',
                            content=json.dumps(self.errors))
        resp.status_code = 400
        resp.reason_phrase = 'bad request'
        return resp
Example #57
0
    def mkcalendar(self, request, user, resource_name):

        resource = self.get_resource(
            request, user, resource_name, create=True, collection=True, strict=True
        )

        cl = int(request.META.get('CONTENT_LENGTH', '0'))
        if cl > 0:
            try:
                dom = etree.fromstring(request.read())
            except:
                raise davvy.exceptions.BadRequest()

            # logger.debug(etree.tostring(dom, pretty_print=True))

            for prop in dom.find('{DAV:}set').find('{DAV:}prop'):
                try:
                    resource.set_prop(self, request, prop.tag, prop)
                except davvy.exceptions.Forbidden:
                    pass

            doc = etree.Element(
                '{urn:ietf:params:xml:ns:caldav}mkcalendar-response')
            doc_propstat = etree.Element('{DAV:}propstat')
            doc_propstat_status = etree.Element('{DAV:}status')
            doc_propstat_status.text = request.META[
                'SERVER_PROTOCOL'] + ' 200 OK'
            doc_propstat.append(doc_propstat_status)
            doc.append(doc_propstat)

            response = HttpResponse(
                etree.tostring(doc, pretty_print=True), content_type='text/xml; charset=utf-8')
        else:
            response = HttpResponse()
        response.status_code = 201
        response.reason_phrase = 'Created'
        response['Cache-Control'] = 'no-cache'
        return response
Example #58
0
def webdav_proxy_view(request):
    remote_url = settings.VF_HOST

    headers = {
        'Cookie': request.META.get('HTTP_COOKIE'),
        'Authorization': request.META.get('HTTP_AUTHORIZATION'),
        'Depth': request.META.get('HTTP_DEPTH')
    }

    path, encoded_path, real_username = rewrite_webdav_path(request, request.path)

    request_body = request.body
    if len(request_body) > 0:
        data = request_body
    else:
        data = None

    r = requests.request(request.method, remote_url + path, data=data, headers=headers)


    response = HttpResponse()
    response.status_code = r.status_code
    response.reason_phrase = r.reason
    #response.content = r.content

    if request.method == 'PROPFIND':
        returned_content = r.content.replace(real_username, encoded_path)
    else:
        returned_content = r.content

    for header in r.headers.keys():
        if header.lower() not in ['keep-alive', 'connection', 'content-encoding', 'vary', 'content-length']:
            print(header, '->', r.headers[header])
            response[header] = r.headers[header]

    response.write(returned_content)

    return response
Example #59
0
        def _decorator(request, *args, **kwargs):
            allowed = False
            logger.info('request is secure? {}'.format(request.is_secure()))
            if settings.ALLOW_ANONYMOUS_POST:
                logger.debug('allowing anonymous post')
                allowed = True
            elif hasattr(request, 'user') and request.user.is_authenticated():
                allowed = True
            elif 'HTTP_AUTHORIZATION' in request.META:
                logger.debug('checking for http authorization header')
                if settings.REQUIRE_SECURE_AUTH and not request.is_secure():
                    return insecure_connection_response()
                http_auth = request.META['HTTP_AUTHORIZATION']
                authmeth, auth = http_auth.split(' ', 1)
                if authmeth.lower() == 'basic':
                    username, password = decode_basic_auth(auth)
                    user = authenticate(username=username, password=password)
                    if user is not None and user.is_active:
                        logger.info(
                            'Authentication succeeded for {}'.format(username))
                        login(request, user)
                        allowed = True
                    else:
                        logger.info(
                            'Failed auth for {}'.format(username))
                        return HttpResponseForbidden()
            if allowed:
                return func(request, *args, **kwargs)

            if settings.REQUIRE_SECURE_AUTH and not request.is_secure():
                logger.debug('not requesting auth over an insecure channel')
                return insecure_connection_response()
            else:
                res = HttpResponse()
                res.status_code = 401
                res.reason_phrase = 'Unauthorized'
                res['WWW-Authenticate'] = 'Basic realm="{}"'.format(realm)
                return res
Example #60
0
def create_new_paper(**kwargs):	
	if email_has_more_than_five_questions_open(kwargs['sent_to']):
		#Do not create a new paper and return http response with error code 400		
		response = HttpResponse()
		response.status_code = 400
		response.reason_phrase = "Too many questions open for this e-mail"
		return response
	else:	#Insert Data into DB		
		#See if a DB record from the sender already exists.
		the_sender = checkExistingEmail(kwargs['sender'])			
		the_sender.ip = kwargs['ip']		
		the_sender.save()

		new_paper = Paper(sender=the_sender, sent_to=kwargs['sent_to'])
		new_paper.code = uuid.uuid4()
		new_paper.save()
		new_question = Question(sender=the_sender, paper=new_paper, question_text=kwargs['question'],
								question_type=kwargs['question_type'])		
		new_question.save()
		new_answers = create_answers_objects(the_sender, new_paper, new_question, 
											kwargs['answers'], kwargs['selected_answer'])		
				
		test = Answer.objects.bulk_create(new_answers)
		test.save()