Ejemplo n.º 1
0
    def _ajax_upload(self, request, *args, **kwargs):
        if request.method == "POST":
            upload = request.FILES.get('qqfile', None)
            if not upload:
                return HttpResponseBadRequest("AJAX request not valid")

            filename = upload.name
            backend = self.get_backend()

            # custom filename handler
            filename = (backend.update_filename(request, filename, *args, **kwargs)
                        or filename)
            # save the file
            backend.setup(request, filename, *args, **kwargs)
            success = backend.upload(upload, filename, False, *args, **kwargs)

            # callback
            extra_context = backend.upload_complete(request, filename, uuid=request.POST['qquuid'], *args, **kwargs)

            if success is True:
                file_uploaded.send(sender=self.__class__, backend=backend, request=request, extra_context=extra_context)

            # let Ajax Upload know whether we saved it or not
            ret_json = {'success': success, 'filename': filename}
            if extra_context is not None:
                ret_json.update(extra_context)

            # although "application/json" is the correct content type, IE throws a fit
            return HttpResponse(json.dumps(ret_json, cls=DjangoJSONEncoder), content_type='text/html; charset=utf-8')
        else:
            response = HttpResponseNotAllowed(['POST'])
            response.write("ERROR: Only POST allowed")
            return response
Ejemplo n.º 2
0
def json_method_not_allowed(methods):
    # type: (List[Text]) -> Text
    resp = HttpResponseNotAllowed(methods)
    resp.content = force_bytes(ujson.dumps({"result": "error",
                                            "msg": "Method Not Allowed",
                                            "allowed_methods": methods}))
    return resp
Ejemplo n.º 3
0
    def _ajax_upload(self, request, *args, **kwargs):
        if request.method == "POST":
            if request.is_ajax():
                # the file is stored raw in the request
                upload = request
                is_raw = True
                # AJAX Upload will pass the filename in the querystring if it
                # is the "advanced" ajax upload
                try:
                    if 'qqfile' in request.GET:
                        filename = request.GET['qqfile']
                    elif 'qqfilename' in request.GET:
                        filename = request.GET['qqfilename']
                    else:
                        filename = request.POST['qqfilename']
                except KeyError:
                    return HttpResponseBadRequest("AJAX request not valid")
            # not an ajax upload, so it was the "basic" iframe version with
            # submission via form
            else:
                is_raw = False
                if len(request.FILES) == 1:
                    # FILES is a dictionary in Django but Ajax Upload gives
                    # the uploaded file an ID based on a random number, so it
                    # cannot be guessed here in the code. Rather than editing
                    # Ajax Upload to pass the ID in the querystring, observe
                    # that each upload is a separate request, so FILES should
                    # only have one entry. Thus, we can just grab the first
                    # (and only) value in the dict.
                    upload = request.FILES.values()[0]
                else:
                    raise Http404("Bad Upload")
                filename = upload.name

            backend = self.get_backend()

            # custom filename handler
            filename = (backend.update_filename(request, filename, *args, **kwargs)
                        or filename)
            # save the file
            backend.setup(filename, *args, **kwargs)
            success = backend.upload(upload, filename, is_raw, *args, **kwargs)

            if success:
                file_uploaded.send(sender=self.__class__, backend=backend, request=request)

            # callback
            extra_context = backend.upload_complete(request, filename, *args, **kwargs)

            # let Ajax Upload know whether we saved it or not
            ret_json = {'success': success, 'filename': filename}
            if extra_context is not None:
                ret_json.update(extra_context)

            # although "application/json" is the correct content type, IE throws a fit
            return HttpResponse(json.dumps(ret_json, cls=DjangoJSONEncoder), content_type='text/html; charset=utf-8')
        else:
            response = HttpResponseNotAllowed(['POST'])
            response.write("ERROR: Only POST allowed")
            return response
Ejemplo n.º 4
0
 def __call__(self, request, *args, **kwargs):      
     try:
         return self.dispatch(request, self, *args, **kwargs)
     except HttpMethodNotAllowed:
         response = HttpResponseNotAllowed(self.permitted_methods)
         response.mimetype = self.mimetype
         return response
Ejemplo n.º 5
0
def json_method_not_allowed(methods):
    # type: (List[text_type]) -> text_type
    resp = HttpResponseNotAllowed(methods)
    resp.content = ujson.dumps({"result": "error",
        "msg": "Method Not Allowed",
        "allowed_methods": methods})
    return resp
Ejemplo n.º 6
0
    def __call__(self, request, *args, **kwargs):      
        try:
            return self.dispatch(request, self, *args, **kwargs)
        except HttpMethodNotAllowed:
            response = HttpResponseNotAllowed(self.permitted_methods)
            response.mimetype = self.mimetype
            return response
        except:
            exc_info = sys.exc_info()
            msg_array = traceback.format_exception(exc_info[0], exc_info[1], exc_info[2])
            msg = ""
            for line in msg_array:
              msg += line

            msg = "[" + unicode(exc_info[0]) + "] " + unicode(exc_info[1])
            return HttpResponseServerError(json_encode(get_error_object(msg)), mimetype='application/json; charset=UTF-8')
Ejemplo n.º 7
0
    def _ajax_upload(self, request, *args, **kwargs):
        if request.method == "POST":
            upload = request.FILES.get('qqfile', None)
            if not upload:
                return HttpResponseBadRequest("AJAX request not valid")

            # get chunks
            chunk_index = int(request.POST.get('qqpartindex'))
            total_chunks = int(request.POST.get('qqtotalparts'))


            filename = upload.name

            file_id = request.POST['qquuid']

            backend = self.get_backend()

            # custom filename handler
            filename = (backend.update_filename(request, filename, *args, **kwargs)
                        or filename)

            backend.setup(filename, *args, **kwargs)
            success = backend.upload_chunk(upload, *args, **kwargs)

            # callback - edited
            extra_context = None
            if total_chunks == chunk_index +1:
                extra_context = backend.upload_complete(request, filename, file_id, *args, **kwargs)
                # file_uploaded.send(sender=self.__class__, backend=backend, request=request)

            # let Ajax Upload know whether we saved it or not
            if settings.DEBUG:
                ret_json = {'success': success, 'filename': filename}
            else:
                ret_json = {'success': success}
            
            if extra_context is not None:
                if settings.DEBUG:
                    ret_json.update(extra_context)

            # although "application/json" is the correct content type, IE throws a fit
            return HttpResponse(json.dumps(ret_json, cls=DjangoJSONEncoder), content_type='text/html; charset=utf-8')
        else:
            response = HttpResponseNotAllowed(['POST'])
            response.write("ERROR: Only POST allowed")
            return response
Ejemplo n.º 8
0
 def __call__(self, request, *args, **kwargs):      
     try:
         response = self.dispatch(request, self, *args, **kwargs)
         
         log_request(request, response, 'access')
         
         return response
     except (HttpMethodNotAllowed, Http403):
         log_request(request, None, 'access')
         
         response = HttpResponseNotAllowed(self.permitted_methods)
         response.mimetype = self.mimetype
         return response
     except TracedServerError, e:
         log_request(request, None, 'access')
         
         msg = log_detailed_exception(request, e)
Ejemplo n.º 9
0
def ajax_upload(request):
    if request.method == 'POST':
        for field_name in request.FILES:
            uploaded_file = request.FILES[field_name]

            datedir = time.strftime('%Y/%m/%d/', time.localtime(time.time()))
            dest_dir = conf.TEMP_DIR + datedir

            if not os.path.exists(str(dest_dir)):
                os.makedirs(str(dest_dir))

            salt = str(time.time()) + uploaded_file.name
            if isinstance(salt, unicode):
                salt = salt.encode('utf8')
            filename = hashlib.md5(salt).hexdigest()
            fn_ext = uploaded_file.name.split('.')[-1]

            # save to temp dir
            dest_path = dest_dir + filename + '.' + fn_ext
            dest = open(str(dest_path), 'wb+')
            for chunk in uploaded_file.chunks():
                dest.write(chunk)
            dest.close()

            # copy to media root
            media_path = time.strftime('uploads/media/%Y/%m/%d/', time.localtime(time.time())) + filename + '.' + fn_ext
            if not os.path.exists(settings.MEDIA_ROOT + time.strftime('uploads/media/%Y/%m/%d/', time.localtime(time.time()))):
                os.makedirs(settings.MEDIA_ROOT + time.strftime('uploads/media/%Y/%m/%d/', time.localtime(time.time())))

            import shutil
            shutil.copyfile(dest_path, settings.MEDIA_ROOT + media_path)

        ret_json = {'success': True, 'filename': media_path}        
        return HttpResponse(json.dumps(ret_json), mimetype="text/plain")
    else:
        response = HttpResponseNotAllowed(['POST'])
        response.write("ERROR: Only POST allowed")
        return response
Ejemplo n.º 10
0
def get_token_view(request, *args, **kwargs):
    if request.method == 'GET':
        return HttpResponse()
    return HttpResponseNotAllowed('Only GET request are allowed')
Ejemplo n.º 11
0
 def post(self, request):
     return HttpResponseNotAllowed([])
Ejemplo n.º 12
0
def save_answer(request, task, answered, context, __, EncryptionProvider, set_ephemeral_encryption_cookies):
    if request.method != "POST":
        return HttpResponseNotAllowed(["POST"])

    # does user have write privs?
    if not task.has_write_priv(request.user):
        return HttpResponseForbidden()

    # normal redirect - reload the page
    redirect_to = task.get_absolute_url() + "?previous=nquestion"

    # validate question
    q = task.module.questions.get(id=request.POST.get("question"))

    # validate and parse value
    if request.POST.get("method") == "clear":
        # clear means that the question returns to an unanswered state
        value = None
        cleared = True
    
    elif request.POST.get("method") == "skip":
        # skipped means the question is answered with a null value
        value = None
        cleared = False
    
    elif request.POST.get("method") == "save":
        # load the answer from the HTTP request
        if q.spec["type"] == "file":
            # File uploads come through request.FILES.
            value = request.FILES.get("value")

            # We allow the user to preserve the existing uploaded value
            # for a question by submitting nothing. (The proper way to
            # clear it is to use Skip.) If the user submits nothing,
            # just return immediately.
            if value is None:
                return JsonResponse({ "status": "ok", "redirect": redirect_to })

        else:
            # All other values come in as string fields. Because
            # multiple-choice comes as a multi-value field, we get
            # the value as a list. question_input_parser will handle
            # turning it into a single string for other question types.
            value = request.POST.getlist("value")

        # parse & validate
        try:
            value = answer_validation.question_input_parser.parse(q, value)
            value = answer_validation.validator.validate(q, value)
        except ValueError as e:
            # client side validation should have picked this up
            return JsonResponse({ "status": "error", "message": str(e) })

        # run external functions
        if q.spec['type'] == "external-function":
            # Make a deepcopy of some things so that we don't allow the function
            # to mess with our data.
            try:
                value = module_logic.run_external_function(
                    q, answered,
                    project_name=task.project.title,
                    project_url=task.project.organization.get_url(task.project.get_absolute_url())
                )
            except ValueError as e:
                return JsonResponse({ "status": "error", "message": str(e) })

        cleared = False

    elif request.POST.get("method") == "review":
        # Update the reviewed flag on the answer.
        ta = TaskAnswer.objects.filter(task=task, question=q).first()
        if ta:
            ans = ta.get_current_answer()
            if ans and not ans.cleared and ans.id == int(request.POST["answer"]):
                ans.reviewed = int(request.POST["reviewed"])
                ans.save(update_fields=["reviewed"])
                return JsonResponse({ "status": "ok" })
        return JsonResponse({ "status": "error", "message": "Invalid question." })

    else:
        raise ValueError("invalid 'method' parameter %s" + request.POST.get("method", "<not set>"))

    # save answer - get the TaskAnswer instance first
    question, _ = TaskAnswer.objects.get_or_create(
        task=task,
        question=q,
    )

    # fetch the task that answers this question
    answered_by_tasks = []
    if q.spec["type"] in ("module", "module-set") and not cleared:
        if value == "__new":
            # Create a new task, and we'll redirect to it immediately.
            t = Task.create(
                parent_task_answer=question, # for instrumentation only, doesn't go into Task instance
                editor=request.user,
                project=task.project,
                module=q.answer_type_module,
                title=q.answer_type_module.title)

            answered_by_tasks = [t]
            redirect_to = t.get_absolute_url() + "?previous=parent"

        elif value == None:
            # User is skipping this question.
            answered_by_tasks = []

        else:
            # User selects existing Tasks.
            # Validate that the tasks are of the right type (module) and
            # the user has read access.
            answered_by_tasks = [
                Task.objects.get(id=int(item))
                for item in value.split(',')
                ]
            for t in answered_by_tasks:
                if t.module != q.answer_type_module or not t.has_read_priv(request.user):
                    raise ValueError("invalid task ID")
            if q.spec["type"] == "module" and len(answered_by_tasks) != 1:
                raise ValueError("did not provide exactly one task ID")
        
        value = None
        answered_by_file = None

    elif q.spec["type"] == "file" and not cleared:
        # Don't save the File into the stored_value field in the database.
        # Instead put it in answered_by_file. value may be None if the user
        # is skipping the question.
        answered_by_file = value
        value = None

    else:
        answered_by_file = None

    # Create a new TaskAnswerHistory record, if the answer is actually changing.
    if cleared:
        # Clear the answer.
        question.clear_answer(request.user)
        instrumentation_event_type = "clear"
    else:
        # Save the answer.
        had_answer = question.has_answer()
        if question.save_answer(value, answered_by_tasks, answered_by_file, request.user, "web", encryption_provider=EncryptionProvider()):
            # The answer was changed (not just saved as a new answer).
            if request.POST.get("method") == "skip":
                instrumentation_event_type = "skip"
            elif had_answer:
                instrumentation_event_type = "change"
            else: # is a new answer
                instrumentation_event_type = "answer"
        else:
            instrumentation_event_type = "keep"

    # Add instrumentation event.
    # --------------------------
    # How long was it since the question was initially viewed? That gives us
    # how long it took to answer the question.
    i_task_question_view = InstrumentationEvent.objects\
        .filter(user=request.user, event_type="task-question-show", task=task, question=q)\
        .order_by('event_time')\
        .first()
    i_event_value = (timezone.now() - i_task_question_view.event_time).total_seconds() \
        if i_task_question_view else None
    # Save.
    InstrumentationEvent.objects.create(
        user=request.user,
        event_type="task-question-" + instrumentation_event_type,
        event_value=i_event_value,
        module=task.module,
        question=q,
        project=task.project,
        task=task,
        answer=question,
        extra={
            "answer_value": value,
        }
    )

    # Form a JSON response to the AJAX request and indicate the
    # URL to redirect to, to load the next question.
    response = JsonResponse({ "status": "ok", "redirect": redirect_to })

    # Apply any new ephemeral encryption cookies now that we have
    # an HttpResponse object.
    set_ephemeral_encryption_cookies(response)

    # Return the response.
    return response
Ejemplo n.º 13
0
 def process_request(self, request):
   if request.method not in desktop.conf.HTTP_ALLOWED_METHODS.get():
     return HttpResponseNotAllowed(desktop.conf.HTTP_ALLOWED_METHODS.get())
Ejemplo n.º 14
0
Archivo: tests.py Proyecto: tnir/django
 async def async_generic_view(request):
     if request.method.lower() != method_name:
         return HttpResponseNotAllowed(method_name)
     return HttpResponse(status=200)
Ejemplo n.º 15
0
def get_analyze_state(request):
    allowed_method = ['GET']
    if request.method not in allowed_method:
        return HttpResponseNotAllowed(allowed_method)

    locktime = timezone.now() - LOCKDELTA

    face_loc = {
        'service':
        'face_location',
        'unanalyzed':
        models.Image.objects.filter(
            service_face_location_analyzed=False).count(),
        'analyzing':
        models.Image.objects.filter(
            service_face_location_analyzed=False,
            service_face_location_analyzing_startdate__range=(locktime,
                                                              timezone.now()),
        ).count(),
        'analyzed':
        models.Image.objects.filter(
            service_face_location_analyzed=True).count()
    }

    face_enc = {
        'service':
        'face_encoding',
        'unanalyzed':
        models.Face.objects.filter(
            service_face_encoding_analyzed=False).count(),
        'analyzing':
        models.Face.objects.filter(
            service_face_encoding_analyzed=False,
            service_face_encoding_analyzing_startdate__range=(locktime,
                                                              timezone.now()),
        ).count(),
        'analyzed':
        models.Face.objects.filter(
            service_face_encoding_analyzed=True).count()
    }

    face_sex = {
        'service':
        'sex_detection',
        'unanalyzed':
        models.Face.objects.filter(
            service_sex_detection_analyzed=False).count(),
        'analyzing':
        models.Face.objects.filter(
            service_sex_detection_analyzed=False,
            service_sex_detection_analyzing_startdate__range=(locktime,
                                                              timezone.now()),
        ).count(),
        'analyzed':
        models.Face.objects.filter(
            service_sex_detection_analyzed=True).count()
    }

    face_age = {
        'service':
        'age_prediction',
        'unanalyzed':
        models.Face.objects.filter(
            service_age_prediction_analyzed=False).count(),
        'analyzing':
        models.Face.objects.filter(
            service_age_prediction_analyzed=False,
            service_age_prediction_analyzing_startdate__range=(locktime,
                                                               timezone.now()),
        ).count(),
        'analyzed':
        models.Face.objects.filter(
            service_age_prediction_analyzed=True).count()
    }

    return_list = [
        face_loc,
        face_enc,
        face_sex,
        face_age,
    ]

    return JsonResponse(return_list, safe=False)
Ejemplo n.º 16
0
def dashboard(request):
    if request.method == 'GET':
        return render(request, 'dashboard.html')
    return HttpResponseNotAllowed(permitted_methods=['GET'])
Ejemplo n.º 17
0
def contacts(request, uid):
    print('I dont know what to do, but I know ur ID: ', uid)
    if request.method == 'GET':
        return JsonResponse({'text': 'contacts ' + str(uid)})
    else:
        return HttpResponseNotAllowed(['GET'])
Ejemplo n.º 18
0
def store(request):
    if request.method != 'POST':
        return HttpResponseNotAllowed(
            'This method only supports POST requests')

    if request.META.get('HTTP_AUTHORIZATION', '').startswith('Sentry'):
        auth_vars = parse_auth_header(request.META['HTTP_AUTHORIZATION'])

        signature = auth_vars.get('sentry_signature')
        timestamp = auth_vars.get('sentry_timestamp')

        format = 'json'

        data = request.body

        # Signed data packet
        if signature and timestamp:
            try:
                timestamp = float(timestamp)
            except ValueError:
                return HttpResponseBadRequest('Invalid timestamp')

            if timestamp < time.time() - 3600:  # 1 hour
                return HttpResponseGone('Message has expired')

            sig_hmac = get_signature(data, timestamp)
            if sig_hmac != signature:
                return HttpResponseForbidden('Invalid signature')
        else:
            return HttpResponse('Unauthorized', status_code=401)
    else:
        # Legacy request (deprecated as of 2.0)
        key = request.POST.get('key')

        if not key:
            return HttpResponseForbidden('Invalid credentials')

        if key != settings.KEY:
            warnings.warn(
                'A client is sending the `key` parameter, which will be removed in Sentry 2.0',
                DeprecationWarning)
            return HttpResponseForbidden('Invalid credentials')

        data = request.POST.get('data')
        if not data:
            return HttpResponseBadRequest('Missing data')

        format = request.POST.get('format', 'pickle')

        if format not in ('pickle', 'json'):
            return HttpResponseBadRequest('Invalid format')

    logger = logging.getLogger('sentry.server')

    try:
        try:
            data = base64.b64decode(data).decode('zlib')
        except zlib.error:
            data = base64.b64decode(data)
    except Exception, e:
        # This error should be caught as it suggests that there's a
        # bug somewhere in the client's code.
        logger.exception('Bad data received')
        return HttpResponseForbidden('Bad data decoding request (%s, %s)' %
                                     (e.__class__.__name__, e))
Ejemplo n.º 19
0
def submit_feedback_via_zendesk(request):
    """
    Create a new user-requested Zendesk ticket.

    If Zendesk submission is not enabled, any request will raise `Http404`.
    If any configuration parameter (`ZENDESK_URL`, `ZENDESK_USER`, or
    `ZENDESK_API_KEY`) is missing, any request will raise an `Exception`.
    The request must be a POST request specifying `subject` and `details`.
    If the user is not authenticated, the request must also specify `name` and
    `email`. If the user is authenticated, the `name` and `email` will be
    populated from the user's information. If any required parameter is
    missing, a 400 error will be returned indicating which field is missing and
    providing an error message. If Zendesk returns any error on ticket
    creation, a 500 error will be returned with no body. Once created, the
    ticket will be updated with a private comment containing additional
    information from the browser and server, such as HTTP headers and user
    state. Whether or not the update succeeds, if the user's ticket is
    successfully created, an empty successful response (200) will be returned.
    """
    if not settings.MITX_FEATURES.get('ENABLE_FEEDBACK_SUBMISSION', False):
        raise Http404()
    if request.method != "POST":
        return HttpResponseNotAllowed(["POST"])
    if (not settings.ZENDESK_URL or not settings.ZENDESK_USER
            or not settings.ZENDESK_API_KEY):
        raise Exception("Zendesk enabled but not configured")

    def build_error_response(status_code, field, err_msg):
        return HttpResponse(json.dumps({
            "field": field,
            "error": err_msg
        }),
                            status=status_code)

    additional_info = {}

    required_fields = ["subject", "details"]
    if not request.user.is_authenticated():
        required_fields += ["name", "email"]
    required_field_errs = {
        "subject": "Please provide a subject.",
        "details": "Please provide details.",
        "name": "Please provide your name.",
        "email": "Please provide a valid e-mail.",
    }

    for field in required_fields:
        if field not in request.POST or not request.POST[field]:
            return build_error_response(400, field, required_field_errs[field])

    subject = request.POST["subject"]
    details = request.POST["details"]
    tags = []
    if "tag" in request.POST:
        tags = [request.POST["tag"]]

    if request.user.is_authenticated():
        realname = request.user.profile.name
        email = request.user.email
        additional_info["username"] = request.user.username
    else:
        realname = request.POST["name"]
        email = request.POST["email"]
        try:
            validate_email(email)
        except ValidationError:
            return build_error_response(400, "email",
                                        required_field_errs["email"])

    for header in ["HTTP_REFERER", "HTTP_USER_AGENT"]:
        additional_info[header] = request.META.get(header)

    zendesk_api = _ZendeskApi()

    additional_info_string = ("Additional information:\n\n" + "\n".join(
        "%s: %s" % (key, value)
        for (key, value) in additional_info.items() if value is not None))

    new_ticket = {
        "ticket": {
            "requester": {
                "name": realname,
                "email": email
            },
            "subject": subject,
            "comment": {
                "body": details
            },
            "tags": tags
        }
    }
    try:
        ticket_id = zendesk_api.create_ticket(new_ticket)
    except zendesk.ZendeskError as err:
        log.error("Error creating Zendesk ticket: %s", str(err))
        return HttpResponse(status=500)

    # Additional information is provided as a private update so the information
    # is not visible to the user.
    ticket_update = {
        "ticket": {
            "comment": {
                "public": False,
                "body": additional_info_string
            }
        }
    }
    try:
        zendesk_api.update_ticket(ticket_id, ticket_update)
    except zendesk.ZendeskError as err:
        log.error("Error updating Zendesk ticket: %s", str(err))
        # The update is not strictly necessary, so do not indicate failure to the user
        pass

    return HttpResponse()
Ejemplo n.º 20
0
 def get(self, request, *args, **kwargs):
     return HttpResponseNotAllowed(['post'])
Ejemplo n.º 21
0
 def http_method_not_allowed(self, request, *args, **kwargs):
     logger.warning(
         'Method Not Allowed (%s): %s', request.method, request.path,
         extra={'status_code': 405, 'request': request}
     )
     return HttpResponseNotAllowed(self._allowed_methods())
Ejemplo n.º 22
0
def state_progress(request, state, context, category):
    # If no context is specified, "full" is the default
    if context is None: context = 'full'

    # Only GET commands are allowed
    valid_requests = ['GET']
    if request.META['REQUEST_METHOD'] not in valid_requests:
        return HttpResponseNotAllowed(valid_requests)

    # Check that the URL components were valid. If they aren't, 404
    if context not in VALID_CONTEXTS: raise Http404
    if category is not None and category not in CATEGORIES: raise Http404
    state = get_object_or_404(State, abbreviation__iexact=state)

    if category != None:
        # Get deliverables that fall under this category
        deliverables = state.deliverable_set.filter(category=category)
    else:
        # Get all this state's deliverables
        deliverables = state.deliverable_set.all()

    # Get submissions that address these deliverables
    submissions = Submission.objects.filter(
        satisfies_deliverable__in=deliverables)

    # Get comments that pertain to these submissions
    comments = SubmissionComment.objects.filter(submission__in=submissions)

    # Get the completion percentage for this category
    if category == None:
        if state.category_completion('all') == None:
            percent = None
        else:
            percent = int(round(state.category_completion('all')))
    else:
        if state.category_completion(category) == None:
            percent = None
        else:
            percent = int(round(state.category_completion(category)))

    # Build context for the templates
    additional_context = {
        'comments': comments,
        'submissions': submissions,
        'deliverables': deliverables,
        'deliv_1': deliverables.filter(year=1),
        'deliv_2': deliverables.filter(year=2),
        'deliv_3': deliverables.filter(year=3),
        'deliv_4': deliverables.filter(year=4),
        'state': state,
        'percent': percent
    }
    if category != None: additional_context['category'] = CATEGORIES[category]
    template_context = standard_context(additional_context)

    # Render the appropriate template
    if context == 'full':
        return render_to_response('aasgtrack/progress-full.html',
                                  template_context)
    if context == 'popup':
        return render_to_response('aasgtrack/progress-popup.html',
                                  template_context)
    else:
        # If this happens, double-check this code. Make sure there's an if-statement for each
        #  item in the VALID_CONTEXTS variable. You can only get here if that is botched.
        return HttpResponse('Sorry, there was an error', status=500)
Ejemplo n.º 23
0
def todo(request, id=None):

    # read and read by id, @return json
    if request.method == 'GET':

        if id != None:
            try:
                t = Todo.objects.get(pk=id)
                res = serializers.serialize("json", [t])
                return HttpResponse(res, content_type="application/json")
            except Todo.DoesNotExist:
                response = json.dumps({
                    'errors': ['No Items found'],
                    'success': False
                })
                return HttpResponse(response, content_type="application/json")

        keyword = request.GET.get('keyword', '')

        if keyword != '':
            data = Todo.objects.order_by('-created_at').filter(
                Q(tags__slug__contains=keyword)
                | Q(todo_text__contains=keyword))
        else:
            data = Todo.objects.order_by('-created_at').all()

        tags_data = {}

        for t in data:
            tags = t.tags.all()
            tags_data[t.pk] = []
            for tag in tags:
                tags_data[t.pk].append(tag.slug)

        list = {}
        list['todos'] = json.loads(serializers.serialize("json", data))
        list['tags'] = tags_data
        response = json.dumps(list)
        return HttpResponse(response, content_type="application/json")

    # create, @return json
    elif request.method == 'POST':

        query = request.POST.get('query', '')

        if query != '':
            query = query.split(',')
            pub_date = datetime.datetime.now()

            todo = Todo()
            todo.todo_text = query[0]
            todo.created_at = pub_date
            todo.save()

            del query[0]

            for tag in query:
                if tag.strip() == '':
                    continue
                try:
                    t = Tag.objects.get(slug=tag)
                    todo.tags.add(t)
                except Tag.DoesNotExist:
                    t = Tag()
                    t.slug = tag
                    t.save()
                    todo.tags.add(t)

            response = json.dumps({'query': query, 'success': True})
            return HttpResponse(response, content_type="application/json")
        else:
            return HttpResponseBadRequest('Query missing')

    # delete, @return json
    elif request.method == 'DELETE':
        if id == None:
            return HttpResponseBadRequest('ID missing')
        else:
            try:
                t = Todo.objects.get(pk=id)
                t.delete()
                response = json.dumps({
                    'message': 'Item has been deleted',
                    'success': True
                })
                return HttpResponse(response, content_type="application/json")
            except Todo.DoesNotExist:
                response = json.dumps({
                    'errors': ['No Items found'],
                    'success': False
                })
                return HttpResponse(response, content_type="application/json")

    # update, @return json
    elif request.method == 'PUT':
        if id == None:
            return HttpResponseBadRequest('ID missing')
        else:
            request.PUT = QueryDict(request.body)
            query = request.PUT.get('query', '')
            if query != '':
                query = query.split(',')

                try:
                    todo = Todo.objects.get(pk=id)
                    todo.todo_text = query[0]
                    todo.tags.clear()
                    todo.save()

                    del query[0]

                    for tag in query:
                        if tag.strip() == '':
                            continue
                        try:
                            t = Tag.objects.get(slug=tag)
                            todo.tags.add(t)
                        except Tag.DoesNotExist:
                            t = Tag()
                            t.slug = tag
                            t.save()
                            todo.tags.add(t)

                    response = json.dumps({
                        'message': 'Item has been updated',
                        'success': True
                    })
                    return HttpResponse(response,
                                        content_type="application/json")
                except Todo.DoesNotExist:
                    response = json.dumps({
                        'errors': ['No Items found'],
                        'success': False
                    })
                    return HttpResponse(response,
                                        content_type="application/json")

            else:
                return HttpResponseBadRequest('Query missing')

    # Invalid method, @return json
    else:
        return HttpResponseNotAllowed('Method not allowed')
Ejemplo n.º 24
0
def method_not_allowed(message = ''):
    return HttpResponseNotAllowed(message)
Ejemplo n.º 25
0
 def not_allowed(self, data=''):
     return HttpResponseNotAllowed(data)
Ejemplo n.º 26
0
def add_to_cart(request):
    if request.method == "GET":
        return HttpResponseNotAllowed()

    order = Order.objects.filter(user__pk=request.user.id).filter(
        order_sent=False)
    if order.count() == 0:
        order = Order(user=request.user)
        order.save()
    else:
        order = order[0]

    # Get product data
    try:
        product_class = request.POST["product_class"]
        product_name = request.POST["product_name"]
        product_id = int(request.POST["product_id"])
    except (KeyError, ValueError):
        return HttpResponseBadRequest()

    # Get other request parameters
    quantity = int(request.POST["quantity"])

    # Add to order
    if product_class == "DinnerPlatterName":
        order_dinner_platter = OrderDinnerPlatter(
            order=order,
            dinner_platter=DinnerPlatter.objects.get(
                name=DinnerPlatterName.objects.get(name=product_name),
                size=Size.objects.get(pk=int(request.POST["size"]))),
            quantity=quantity)
        order_dinner_platter.save()
        order.save()
    elif product_class == "Salad":
        order_salad = OrderSalad(
            order=order,
            salad=Salad.objects.get(name=Salad.objects.get(name=product_name)),
            quantity=quantity)
        order_salad.save()
        order.save()
    elif product_class == "Pasta":
        order_pasta = OrderPasta(
            order=order,
            pasta=Pasta.objects.get(name=Pasta.objects.get(name=product_name)),
            quantity=quantity)
        order_pasta.save()
        order.save()
    elif product_class == "Sub":
        order_sub = OrderSub(
            order=order,
            sub=Sub.objects.get(
                name=SubName.objects.get(name=product_name),
                size=Size.objects.get(pk=int(request.POST["size"]))),
            quantity=quantity)
        order_sub.save()
        for addon_id in request.POST.get("subaddons", []).split(","):
            order_sub.sub_addons.add(SubAddon.objects.get(pk=int(addon_id)))
        order_sub.save()

        order.save()
    elif product_class == "PizzaName":
        order_pizza = OrderPizza(
            order=order,
            pizza=Pizza.objects.get(
                name=PizzaName.objects.get(name=product_name),
                size=Size.objects.get(pk=int(request.POST["size"])),
                toppings_count=int(request.POST["toppings_count"])),
            quantity=quantity)
        order_pizza.save()
        for topping_id in request.POST.get("toppings", []).split(","):
            order_pizza.toppings.add(Topping.objects.get(pk=int(topping_id)))
        order_pizza.save()

        order.save()
    else:
        return HttpResponseNotFound()

    return JsonResponse({
        "order_price": order.get_order_price(),
        "order_id": order.id
    })
Ejemplo n.º 27
0
 def dummy_view_handle_http_response_not_allowed(
         _request, _message, _client_public_key):
     return HttpResponseNotAllowed({}, status=405)
Ejemplo n.º 28
0
def questions(request, offering_id, **kwargs):
    """
    List of Questions, Tagged questions, and Unanswered questions.
    matching search query or user selection
    """
    #before = timezone.now()
    if request.method != 'GET':
        return HttpResponseNotAllowed(['GET'])
    offering = get_object_or_404(Offering, id=offering_id)
    search_state = SearchState(user_logged_in=request.user.is_authenticated(),
                               offering_id=offering_id,
                               **kwargs)

    qs, meta_data = models.Thread.objects.run_advanced_search(
        request_user=request.user,
        search_state=search_state,
        offering=offering)
    if meta_data['non_existing_tags']:
        search_state = search_state.remove_tags(meta_data['non_existing_tags'])

    paginator = Paginator(qs, search_state.page_size)
    if paginator.num_pages < search_state.page:
        search_state.page = 1
    page = paginator.page(search_state.page)
    page.object_list = list(page.object_list)  # evaluate the queryset

    # INFO: Because for the time being we need question posts and thread authors
    #       down the pipeline, we have to precache them in thread objects
    models.Thread.objects.precache_view_data_hack(threads=page.object_list)

    related_tags = Tag.objects.get_related_to_search(
        threads=page.object_list,
        ignored_tag_names=meta_data.get('ignored_tag_names', []))
    tag_list_type = askbot_settings.TAG_LIST_FORMAT
    if tag_list_type == 'cloud':  #force cloud to sort by name
        related_tags = sorted(related_tags, key=operator.attrgetter('name'))

    contributors = list(
        models.Thread.objects.get_thread_contributors(
            thread_list=page.object_list).only('id', 'username',
                                               'askbot_profile__gravatar'))

    paginator_context = {
        'is_paginated': (paginator.count > search_state.page_size),
        'pages': paginator.num_pages,
        'current_page_number': search_state.page,
        'page_object': page,
        'base_url': search_state.query_string(),
        'page_size': search_state.page_size,
    }

    #get url for the rss feed
    context_feed_url = reverse('latest_questions_feed')
    # We need to pass the rss feed url based
    # on the search state to the template.
    # We use QueryDict to get a querystring
    # from dicts and arrays. Much cleaner
    # than parsing and string formating.
    rss_query_dict = QueryDict("").copy()
    if search_state.query:
        # We have search string in session - pass it to
        # the QueryDict
        rss_query_dict.update({"q": search_state.query})

    if search_state.tags:
        # We have tags in session - pass it to the
        # QueryDict but as a list - we want tags+
        rss_query_dict.setlist('tags', search_state.tags)
        context_feed_url += '?' + rss_query_dict.urlencode()

    reset_method_count = len(
        filter(None, [
            search_state.query, search_state.tags,
            meta_data.get('author_name', None)
        ]))

    if request.is_ajax():
        q_count = paginator.count

        #todo: words
        question_counter = ungettext('%(q_num)s question',
                                     '%(q_num)s questions', q_count)
        question_counter = question_counter % {
            'q_num': humanize.intcomma(q_count),
        }

        if q_count > search_state.page_size:
            paginator_tpl = get_template('main_page/paginator.html')
            paginator_html = paginator_tpl.render(
                RequestContext(
                    request, {
                        'context': paginator_context,
                        'questions_count': q_count,
                        'page_size': search_state.page_size,
                        'search_state': search_state,
                    }))
        else:
            paginator_html = ''

        questions_tpl = get_template('main_page/questions_loop.html')
        questions_html = questions_tpl.render(
            RequestContext(
                request, {
                    'threads': page,
                    'search_state': search_state,
                    'reset_method_count': reset_method_count,
                    'request': request,
                    'offering_id': offering_id,
                }))
        print questions_html
        ajax_data = {
            'query_data': {
                'tags': search_state.tags,
                'sort_order': search_state.sort,
                'ask_query_string': search_state.ask_query_string(),
            },
            'paginator': paginator_html,
            'question_counter': question_counter,
            'faces':
            [],  #[extra_tags.gravatar(contributor, 48) for contributor in contributors],
            'feed_url': context_feed_url,
            'query_string': search_state.query_string(),
            'page_size': search_state.page_size,
            'questions': questions_html.replace('\n', ''),
            'non_existing_tags': meta_data['non_existing_tags'],
        }

        related_tags_tpl = get_template('widgets/related_tags.html')
        related_tags_data = {
            'tags': related_tags,
            'tag_list_type': tag_list_type,
            'query_string': search_state.query_string(),
            'search_state': search_state,
            'language_code': translation.get_language(),
        }
        if tag_list_type == 'cloud':
            related_tags_data['font_size'] = extra_tags.get_tag_font_size(
                related_tags)

        ajax_data['related_tags_html'] = related_tags_tpl.render(
            RequestContext(request, related_tags_data))

        #here we add and then delete some items
        #to allow extra context processor to work
        ajax_data['tags'] = related_tags
        ajax_data['interesting_tag_names'] = None
        ajax_data['threads'] = page
        extra_context = context.get_extra(
            'ASKBOT_QUESTIONS_PAGE_EXTRA_CONTEXT', request, ajax_data)
        del ajax_data['tags']
        del ajax_data['interesting_tag_names']
        del ajax_data['threads']

        ajax_data.update(extra_context)

        return HttpResponse(simplejson.dumps(ajax_data),
                            content_type='application/json')

    else:  # non-AJAX branch

        template_data = {
            'active_tab':
            'questions',
            'author_name':
            meta_data.get('author_name', None),
            'contributors':
            contributors,
            'context':
            paginator_context,
            'is_unanswered':
            False,  #remove this from template
            'interesting_tag_names':
            meta_data.get('interesting_tag_names', None),
            'ignored_tag_names':
            meta_data.get('ignored_tag_names', None),
            'subscribed_tag_names':
            meta_data.get('subscribed_tag_names', None),
            'language_code':
            translation.get_language(),
            'name_of_anonymous_user':
            models.get_name_of_anonymous_user(),
            'page_class':
            'main-page',
            'page_size':
            search_state.page_size,
            'query':
            search_state.query,
            'threads':
            page,
            'questions_count':
            paginator.count,
            'reset_method_count':
            reset_method_count,
            'scope':
            search_state.scope,
            'show_sort_by_relevance':
            conf.should_show_sort_by_relevance(),
            'search_tags':
            search_state.tags,
            'sort':
            search_state.sort,
            'tab_id':
            search_state.sort,
            'tags':
            related_tags,
            'tag_list_type':
            tag_list_type,
            'font_size':
            extra_tags.get_tag_font_size(related_tags),
            'display_tag_filter_strategy_choices':
            conf.get_tag_display_filter_strategy_choices(),
            'email_tag_filter_strategy_choices':
            conf.get_tag_email_filter_strategy_choices(),
            'query_string':
            search_state.query_string(),
            'search_state':
            search_state,
            'feed_url':
            context_feed_url,
            'offering_id':
            offering_id,
        }

        extra_context = context.get_extra(
            'ASKBOT_QUESTIONS_PAGE_EXTRA_CONTEXT', request, template_data)

        template_data.update(extra_context)
        template_data.update(context.get_for_tag_editor())

        #and one more thing:) give admin user heads up about
        #setting the domain name if they have not done that yet
        #todo: move this out to a separate middleware
        if request.user.is_authenticated() and request.user.is_administrator():
            if domain_is_bad():
                url = askbot_settings.get_setting_url(
                    ('QA_SITE_SETTINGS', 'APP_URL'))
                msg = _(
                    'Please go to Settings -> %s '
                    'and set the base url for your site to function properly'
                ) % url
                request.user.message_set.create(message=msg)
        print "dusan"
        return render(request, 'main_page.html', template_data)
Ejemplo n.º 29
0
def edit_study(request, owner, title):
    if request.method != 'POST': return HttpResponseNotAllowed()
    if request.user.username != owner: return HttpResponseForbidden()

    body = request.data
    study_title = body['title']
    study_start_date = parse_date(body['start_date'])
    study_end_date = parse_date(
        body['end_date']
    ) if 'end_date' in body and body['end_date'] is not None else None
    study_contact_institution = body[
        'contact_institution'] if 'contact_institution' in body else None
    study_country = body['country'] if 'country' in body else None
    study_site_name = body['site_name'] if 'site_name' in body else None
    study_latitude = float(
        body['latitude']
    ) if 'latitude' in body and body['latitude'] is not None else None
    study_longitude = float(
        body['longitude']
    ) if 'longitude' in body and body['longitude'] is not None else None
    study_altitude = int(
        body['altitude']
    ) if 'altitude' in body and body['altitude'] is not None else None
    study_altitude_units = body[
        'altitude_units'] if 'altitude_units' in body else None
    study_experimental_design_description = body[
        'experimental_design_description'] if 'experimental_design_description' in body else None
    study_experimental_design_type = body[
        'experimental_design_type'] if 'experimental_design_type' in body else None
    study_observation_unit_description = body[
        'observation_unit_description'] if 'observation_unit_description' in body else None
    study_growth_facility_description = body[
        'growth_facility_description'] if 'growth_facility_description' in body else None
    study_growth_facility_type = body[
        'growth_facility_type'] if 'growth_facility_type' in body else None
    study_cultural_practices = body[
        'cultural_practices'] if 'cultural_practices' in body else None
    study_environment_parameters = body[
        'environment_parameters'] if 'environment_parameters' in body else None
    study_experimental_factors = body[
        'experimental_factors'] if 'experimental_factors' in body else None

    try:
        project = Investigation.objects.get(owner=request.user, title=title)
        study = Study.objects.get(investigation=project, title=study_title)
        environment_parameters = list(
            EnvironmentParameter.objects.filter(study=study))
    except:
        return HttpResponseNotFound()

    study.description = body['description']
    study.start_date = study_start_date
    study.end_date = study_end_date
    study.contact_institution = study_contact_institution
    study.country = study_country
    study.site_name = study_site_name
    study.latitude = study_latitude
    study.longitude = study_longitude
    study.altitude = study_altitude
    study.altitude_units = study_altitude_units
    study.experimental_design_description = study_experimental_design_description
    study.experimental_design_type = study_experimental_design_type
    # study.experimental_design_map = body['experimental_design_map']
    # study.observation_unit_level_hierarchy = body['observation_unit_level_hierarchy']
    study.observation_unit_description = study_observation_unit_description
    study.growth_facility_description = study_growth_facility_description
    study.growth_facility_type = study_growth_facility_type
    study.cultural_practices = study_cultural_practices
    study.save()

    for existing in environment_parameters:
        existing.delete()

    for name, value in study_environment_parameters.items():
        EnvironmentParameter.objects.create(name=name,
                                            value=value,
                                            study=study)

    return JsonResponse(q.project_to_dict(project))
Ejemplo n.º 30
0
 def routed(request, *args, **kwargs):
     method = request.method.lower()
     if method not in methods:
         return HttpResponseNotAllowed(permitted)
     return methods[method](request, *args, **kwargs)
Ejemplo n.º 31
0
 def wrap(request, *args, **kwargs):
     nonlocal methods
     methods = [m.upper() for m in methods]
     if request.method not in methods:
         return HttpResponseNotAllowed(methods)
     return view_func(request, *args, **kwargs)
Ejemplo n.º 32
0
def dynamic_ip_update_view(request):
    """
    
    TODO: explain dynamic IP update options and logic
    
    if hostname is missing, the ips of all A and AAAA records of the zone are changed
    otherwise only the specific record with the name=hostname and provided that the
    correct ip (v4, v6) has been provided for the type of the record (A, AAAA)
    
    If no ipv4 or ipv6 address is provided, then the client IP address is used
    to update A records (if the client IP is IPv4) or AAAA records (if client IP is IPv6).
    
    curl -k \
        -F "api_key=UBSE1RJ0J175MRAMJC31JFUH" \
        -F "hostname=ns1.centos.example.org" \
        -F "ipv4=10.1.2.3" \
        -F "ipv6=3ffe:1900:4545:3:200:f8ff:fe21:67cf" \
        https://centos.example.org/powerdns/zone/update/

    """
    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])
    form = DynamicIPUpdateForm(request.POST)
    
    if not form.is_valid():
        return HttpResponseBadRequest(repr(form.errors))
    
    # Determine protocol or REMOTE_ADDR
    remote_ipv4 = None
    remote_ipv6 = None
    try:
        validate_ipv4_address(request.META['REMOTE_ADDR'])
    except ValidationError:
        try:
            validate_ipv6_address(request.META['REMOTE_ADDR'])
        except ValidationError:
            return HttpResponseBadRequest('Cannot determine protocol of remote IP address')
        else:
            remote_ipv6 = request.META['REMOTE_ADDR']
    else:
        remote_ipv4 = request.META['REMOTE_ADDR']
    
    # Gather required information
    
    # API key
    
    api_key = form.cleaned_data['api_key']
    
    # Hostname
    
    hostname = form.cleaned_data['hostname']
    
    # If the hostname is missing, the IP addresses of all A and AAAA records
    # of the zone are updated.
    update_all_hosts_in_zone = False
    if not hostname:
        update_all_hosts_in_zone = True
    
    # IP addresses
    
    ipv4 = form.cleaned_data['ipv4']
    ipv6 = form.cleaned_data['ipv6']

    # If IP information is missing, the remote client's IP address will be used.
    if not ipv4 and not ipv6:
        if remote_ipv4:
            ipv4 = remote_ipv4
        if remote_ipv6:
            ipv6 = remote_ipv6
    
    # All required data is good. Process the request.
    
    DynamicZone = get_model('powerdns_manager', 'DynamicZone')
    Record = get_model('powerdns_manager', 'Record')
    
    # Get the relevant dynamic zone instance
    dyn_zone = DynamicZone.objects.get(api_key__exact=api_key)
    
    # Get A and AAAA records
    dyn_rrs = Record.objects.filter(domain=dyn_zone.domain, type__in=('A', 'AAAA'))
    if not dyn_rrs:
        return HttpResponseNotFound('A or AAAA resource records not found')
    
    # Check existence of hostname
    if hostname:
        hostname_exists = False
        for rr in dyn_rrs:
            if rr.name == hostname:
                hostname_exists = True
                break
        if not hostname_exists:
            return HttpResponseNotFound('error:Hostname not found: %s' % hostname)
    
    # Update the IPs
    
    rr_has_changed = False
    
    if update_all_hosts_in_zone:    # No hostname supplied
        for rr in dyn_rrs:
            
            # Try to update A records
            if rr.type == 'A' and ipv4:
                rr.content = ipv4
                rr_has_changed = True
            
            # Try to update AAAA records
            elif rr.type == 'AAAA' and ipv6:
                rr.content = ipv6
                rr_has_changed = True
            
            rr.save()
        
    else:    # A hostname is supplied
        for rr in dyn_rrs:
            if rr.name == hostname:
                
                # Try to update A records
                if rr.type == 'A' and ipv4:
                    rr.content = ipv4
                    rr_has_changed = True
            
                # Try to update AAAA records
                elif rr.type == 'AAAA' and ipv6:
                    rr.content = ipv6
                    rr_has_changed = True
                
                rr.save()
    
    if rr_has_changed:
        return HttpResponse('Success')
    else:
        return HttpResponseNotFound('error:No suitable resource record found')
Ejemplo n.º 33
0
def try_capture(request, username, id_flag):
    # comprobamos método HTTP, sino POST 405
    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])

    # comprobamos si cookie está en headers, sino 400
    if not 'sessioncookie' in request.headers:
        return JsonResponse(custom_error_response.BAD_REQUEST, status=400)

    session_cookie = request.headers.get('sessioncookie')

    # comprobamos si user existe, sino 404
    try:
        user = Usuario.objects.get(nombre__exact=username)
    except Usuario.DoesNotExist:
        return JsonResponse(custom_error_response.NOT_FOUND, status=404)

    # obtenemos todas las sesiones del usuario
    session_list = Sesion.objects.filter(id_usuario__exact=user)

    # comprobamos si cookie está es válida, sino 401
    valid_session = False
    for session in session_list:
        if session.valor_cookie == session_cookie:
            valid_session = True
            break

    if not valid_session:
        return JsonResponse(custom_error_response.BAD_COOKIE, status=401)

    # comprobamos si la bandera existe, sino 404
    try:
        flag = Bandera.objects.get(pk=id_flag)
    except Bandera.DoesNotExist:
        return JsonResponse(custom_error_response.NOT_FOUND, status=404)

    # obtengo todos los intentos de captura sobre esa bandera
    intento_captura_list = IntentoCaptura.objects.filter(id_bandera=flag)

    # cuento cuantos usuarios de mi clan han realizado un intento de captura en los últimos 10 min
    users_capturing_list = []
    for intento_captura in intento_captura_list:
        # si este mismo usuario ya ha iniciado una captura sobre esta bandera se devuelve un conflicto (409)
        # OJO!: (si no se aplica el borrado de intentos esto no funciona bien)
        if intento_captura.id_usuario == user:
            return JsonResponse(custom_error_response.ALREADY_EXISTS,
                                status=409)
        # antiguedad_intento_captura = timezone.now() - intento_captura.fecha
        # if intento_captura.id_usuario.id_clan == user.id_clan and antiguedad_intento_captura < datetime.timedelta(minutes=1): # 10 o 5? (1 de prueba)
        if intento_captura.id_usuario.id_clan == user.id_clan:
            users_capturing_list.append(intento_captura.id_usuario)

    if len(users_capturing_list) >= 1:
        # si hay 1 o más usuarios de tu mismo clan (además de ti mismo) la bandera se captura
        flag.capturando = False
        flag.id_clan = user.id_clan

        # borramos todos los intentos de captura asociados a esa bandera (puede que no haga falta, poer el hecho de filtrar por tiempo)
        for intento_captura in intento_captura_list:
            intento_captura.delete()

        # sumamos 1 a las banderas capturadas de todos los usuarios del clan ganador
        for user_obj in users_capturing_list:
            user_obj.banderas_capturadas += 1
            user_obj.save()

        # sumamos 1 a las banderas capturadas de este propio usuario
        user.banderas_capturadas += 1
        user.save()
    else:
        # sino creamos un nuevo intento de captura
        flag.capturando = True
        new_intento = IntentoCaptura(id_usuario=user, id_bandera=flag)
        new_intento.save()

    # guardamos la bandera, porque su estado de captura se ha modificado (a true o a false)
    flag.save()

    # envio una respuesta 200 indicando que la captura ha comenzado
    # (aunque sea el usuario que finaliza la captura)
    return JsonResponse(custom_error_response.CAPTURE_STARTED, status=200)
Ejemplo n.º 34
0
 def get(self, request, *args, **kwargs):
     if "GET" in self.Meta.methods:
         return self.handle_request(request)
     return HttpResponseNotAllowed(self.Meta.methods.keys())
Ejemplo n.º 35
0
    def _ajax_upload(self, request):
        if request.method == "POST":
            # determine which model and field this upload relates to
            try:
                model = request.POST['model']
                self.model = model
                field = request.POST['field']
            except KeyError:
                return HttpResponseBadRequest("AJAX request not valid")
            else:
                # is the field one of the fields allowed?
                if field not in ('picture',):
                    return HttpResponseBadRequest("AJAX request not valid")

            if request.is_ajax():
                # /!\ try this with Chrome / this is HTML5
                # the file is stored raw in the request
                is_raw = True
                upload = request
                try:
                    filename = request.POST['file']
                except KeyError:
                    return HttpResponseBadRequest("AJAX request not valid")
            # not an ajax upload, so it was the "basic" iframe version with
            # submission via form
            else:
                is_raw = False
                if len(request.FILES) == 1:
                    # FILES is a dictionary in Django but Ajax Upload gives
                    # the uploaded file an ID based on a random number, so it
                    # cannot be guessed here in the code. Rather than editing
                    # Ajax Upload to pass the ID in the querystring, observe
                    # that each upload is a separate request, so FILES should
                    # only have one entry. Thus, we can just grab the first
                    # (and only) value in the dict.
                    upload = request.FILES.values()[0]
                    filename = upload.name
                else:
                    raise Http404("Bad Upload")

            # we have a filename, now determine where to put it
            # first, we need to figure out what model this refers to
            #logger.debug(model + '/' + field)
            try:
                _model = getattr(models, model)
                upload_to = _model._meta.get_field(field).upload_to
            except Exception as e:
                logger.error(e)
                return HttpResponseBadRequest("Bad Request")

            # do we need to resize the image?
            width = request.POST['width'] if request.POST.has_key('width') else None
            height = request.POST['height'] if request.POST.has_key('height') else None
            if width and height:
                self.storage.set_size(width, height)

            # save the file
            self.storage.setup(filename, upload_to)
            success = self.storage.upload(upload, is_raw)
            ret_json = {'success': success, 'filename': self.storage.filename}
            return HttpResponse(json.dumps(ret_json, cls=DjangoJSONEncoder), content_type=self.content_type)
        else:
            response = HttpResponseNotAllowed(['POST'])
            response.write("Only POST allowed")
            return response
Ejemplo n.º 36
0
def flag(request):
    # Si recibimos una peticion que no es GET, devolvemos un 405
    if request.method != 'GET':
        return HttpResponseNotAllowed(['GET'])

    # if not 'latitude' in request.GET or not 'longitude' in request.GET or not 'radius' in request.GET:
    #     return JsonResponse(custom_error_response.BAD_REQUEST, status=400)

    user_latitude = request.GET.get('latitude', None)
    user_longitude = request.GET.get('longitude', None)
    search_radius = request.GET.get('radius', None)

    try:
        if user_latitude is None or user_longitude is None or search_radius is None:
            raise ValueError
        user_latitude = float(user_latitude)
        user_longitude = float(user_longitude)
        search_radius = float(search_radius)
        # https://www.movable-type.co.uk/scripts/latlong.html
        # 0.2 = 16.26 km (ese es el radio máximo permitido)
        if search_radius > 0.200000:
            raise ValueError
    except ValueError:
        return JsonResponse(custom_error_response.BAD_REQUEST, status=400)

    all_flags_list = Bandera.objects.all()
    flags_in_area_list = []

    for flag in all_flags_list:
        distance_to_location = math.sqrt((flag.latitud - user_latitude)**2 +
                                         (flag.longitud - user_longitude)**2)
        # print(distance_to_location, "<=", search_radius, distance_to_location <= search_radius)
        # if distance_to_location < search_radius:
        if distance_to_location <= search_radius:
            flags_in_area_list.append(flag)

    response = []
    for flag in flags_in_area_list:
        flag_response = {
            "id": flag.id,
            "name": flag.nombre,
            "description": flag.descripcion,
            "latitude": flag.latitud,
            "longitude": flag.longitud,
            "capturing": flag.capturando
        }

        if flag.id_clan is not None:
            flag_response["clan"] = {
                "id": flag.id_clan.id,
                "name": flag.id_clan.nombre,
                "color": flag.id_clan.color
            }

            if flag.id_clan.url_icon is not None:
                flag_response["clan"]["url_icon"] = flag.id_clan.url_icon

            if flag.id_clan.abreviatura is not None:
                flag_response["clan"]["acronym"] = flag.id_clan.abreviatura

        response.append(flag_response)

    return JsonResponse(response, safe=False, status=200)
Ejemplo n.º 37
0
def file_upload(request):
    if request.method != "POST":
        return HttpResponseNotAllowed(["POST"])

    upload_id = request.POST.get("upload_id")
    upload_key = request.POST.get("upload_key")
    fu = request.FILES["file"]

    try:
        upload = FileUpload.objects.get(id=upload_id, upload_key=upload_key)
    except:
        return HttpResponseForbidden("Not allowed to upload the file.")

    upload_path = os.path.join(upload.target_dir, upload.name)

    if os.path.isfile(upload_path):
        upload.state = UPLOAD_STATES["FAILED"]
        upload.save()
        # remove file
        return HttpResponseServerError("File already exists.")

    # TODO: check size
    # TODO: check target_dir? create it?
    # don't re-upload FINISHED or STARTED

    tmp_dir = tempfile.mkdtemp()
    tmp_file_name = os.path.join(tmp_dir, upload.name)
    tmp_file = open(tmp_file_name, "wb")
    sum = hashlib.sha256()

    # transaction, commit save()
    upload.state = UPLOAD_STATES["STARTED"]
    upload.save()

    for chunk in fu.chunks():
        tmp_file.write(chunk)
        sum.update(chunk)
    tmp_file.close()

    checksum = sum.hexdigest().lower()

    if checksum != upload.checksum.lower():
        upload.state = UPLOAD_STATES["FAILED"]
        upload.save()
        # remove file
        return HttpResponseServerError("Checksum mismatch.")

    if not os.path.isdir(upload.target_dir):
        os.makedirs(upload.target_dir)

    shutil.move(tmp_file_name, upload.target_dir)
    shutil.rmtree(tmp_dir)

    upload.state = UPLOAD_STATES["FINISHED"]
    upload.dt_finished = datetime.datetime.now()
    upload.save()

    # upload.save can modify state if there is a race
    if upload.state == UPLOAD_STATES['FAILED']:
        return HttpResponseServerError("Checksum mismatch.")

    return HttpResponse("Upload finished.")
Ejemplo n.º 38
0
def pid(request, noid, type):
    """REST API access to PURLs and ARKs.

    On GET, returns information about the PURL or ARK requested by id and type.

    Accessing an ARK or PURL will return all information associated with that
    pid.  In order to allow accessing and updating the unqualified (for an ARK)
    or default (for a PURL) target, the pid url must NOT include a trailing slash.
    Attempting to access a PURL pid as an ARK or vice versa will result in a 404.
    Example urls::

        http://pid.emory.edu/ark/8g3sq          - info for ARK and all targets
        http://pid.emory.edu/purl/127zr         - info for PURL and target

    On PUT, update a PURL or ARK.  Update values should be in the request body
    as JSON.  The following values are supported:

        * **domain** - domain, in URI resource format, e.g.
          http://pid.emory.edu/domains/1/
        * **name** - label or title
        * **external_system_id** - external system name
        * **external_system_key** - key or identifier in the specified external
          system
        * **policy** - policy by name (to specify a different policy from the
          default domain policy)

    Updating target information (resolve URI, active, proxy) is not currently
    supported via PUT on the Ark or Purl that the target belongs to; you must PUT
    the new data to the target itself-- see :meth:`target`.

    """
    methods = ["GET", "PUT"]

    if request.method == "DELETE":
        # *explicitly* disallow delete, since it will never be supported for pids
        response = HttpResponseNotAllowed(methods)
        response.content = """ARKs and PURLs cannot be deleted.
If no longer in use, you may mark the target(s) as inactive, which will prevent
them from being resolved."""
        return response

    # find the requested pid for view or update
    if request.method in methods:
        pid = get_object_or_404(Pid, pid__exact=noid, type=type.title())

    if request.method == "PUT":
        if not request.user.is_authenticated():
            # 401 unauthorized - not logged in or invalid credentials
            return HttpResponseUnauthorized(BASIC_AUTH_REALM)
        elif not request.user.has_perm("pid.change_pid"):
            # 403 Forbidden - logged in but insufficient permissions
            return HttpResponseForbidden()

        # content should be posted in request body as JSON
        content_type = "application/json"
        try:
            if request.META["CONTENT_TYPE"] != content_type:
                raise BadRequest(
                    "Unsupported content type '%s'; please use a supported format: %s"
                    % (request.META["CONTENT_TYPE"], content_type)
                )

            # parse the request body as JSON
            data = json.loads(request.body)

            # TODO: figure out how to take advantage of overlap in create_pid logic

            # update any pid properties that are specified
            if "domain" in data:
                # domain should be passed in as resource URI
                pid.domain = _domain_from_uri(data["domain"])
            if "name" in data:
                pid.name = data["name"]
            if "external_system_id" in data:
                # if external system id is set and not empty, find and update
                if data["external_system_id"]:
                    try:
                        pid.ext_system = ExtSystem.objects.get(name=data["external_system_id"])
                    except ObjectDoesNotExist:
                        raise BadRequest("External System '%s' not found" % data["external_system_id"])
                # otherwise, clear external system
                else:
                    pid.ext_system = None
            if "external_system_key" in data:
                pid.ext_system_key = data["external_system_key"]
            if "policy" in data:
                # if policy is set and not empty, find and update
                if data["policy"]:
                    try:
                        pid.policy = Policy.objects.get(title=data["policy"])
                    except ObjectDoesNotExist:
                        raise BadRequest("Policy '%s' not found" % request.POST["policy"])
                # otherwise, clear policy
                else:
                    pid.policy = None

            # NOTE: currently does not supporting target URI or info
            # It might be nice to allow updating one target specified by qualifier,
            # or perhaps only primary/default target, (roughly parallel to pid creation)
            # HOWEVER, that complicates things:
            # - should specifying active=True/False at this level apply to one
            #   target or ALL targets?
            # - if the requested target does not exist, do we create it?

            # set current user as editor
            pid.editor = request.user
            pid.save()
            _log_rest_action(request, pid, CHANGE, "Updated pid:%s via rest api" % unicode(pid))

        except BadRequest as err:
            # return a response with status code 400, Bad Request
            return HttpResponseBadRequest("Error: %s" % err)

        # successful PUT can return 200 Ok or 204 No Content
        # in this case, on success, return the updated pid with status 200
        # -- fall through to common GET/PUT display logic

    # common logic for GET and successful PUT: return pid info as JSON
    if request.method == "GET" or request.method == "PUT":
        json_data = json_serializer.encode(pid_data(pid, request))
        return HttpResponse(json_data, content_type="application/json")

    # if request method is not GET or PUT, return 405 method not allowed
    return HttpResponseNotAllowed(methods)
Ejemplo n.º 39
0
def token(request):
    if request.method == 'GET':
        return HttpResponse(status=204)
    else:
        return HttpResponseNotAllowed(['GET'])
Ejemplo n.º 40
0
def sign_up(request):
    if request.method == 'POST':
        try:
            req_data = json.loads(request.body.decode())
            username = req_data['username']
            email = req_data['email']
            password = req_data['password']
            selected_foods = req_data['selectedFoods']
            service_option_list = req_data['serviceOptionList']
        except (KeyError, JSONDecodeError):
            return HttpResponse(status=400)
        # This checks duplicated user
        if User.objects.filter(email=email).exists() or \
           User.objects.filter(username=username).exists():
            return HttpResponse(status=409)

        # By user's selected foods, initialize pref_vec
        pref_vec = PreferenceVector()
        attr_list = get_preference_attributes(pref_vec)
        max_cos = 0
        min_cos = 5.0
        for attr in attr_list:
            weight = 0.0
            for food in selected_foods:
                weight += (cos_sim_word(attr, food))
                if cos_sim_word(attr, food) > max_cos:
                    max_cos = cos_sim_word(attr, food)
                if cos_sim_word(attr, food) < min_cos:
                    min_cos = cos_sim_word(attr, food)
            weight /= len(selected_foods)
            #print(weight)
            weight = 2.5 + 10 * weight
            if weight > max_weight:
                weight = max_weight
            if weight < min_weight:
                weight = min_weight
            pref_vec[attr] = weight
        set_service_pref(pref_vec, service_option_list)
        pref_vec.save()
        """
        print('max', max_cos)
        print('min', min_cos)
        """
        food_category = FoodCategory()
        food_category.save()

        search_location = Location()
        search_location.save()

        user = User.objects.create_user(
            username=username, email=email, password=password)
        user.save()

        profile = Profile(user=user,
                          preference_vector=pref_vec,
                          food_category=food_category,
                          search_location=search_location)
        profile.save()

        author = Author(user=user,
                        nickname=username)

        author.save()

        return HttpResponse(status=201)
    else:
        return HttpResponseNotAllowed(['POST'])
Ejemplo n.º 41
0
def service_proxy(request):
    # To get around XMLHTTPRequest cross-domain issues. Commonly used as OpenLayers.ProxyHost

    # These are the only domains that can be requested through this proxy
    allowedHosts = [
        'localhost', 'localhost:8080', 'localhost:8000', 'services.usgin.org',
        'services.usgin.org:8080', '50.19.88.63', '50.19.88.63:8080'
    ]

    # These are the only allowed request methods
    allowedRequests = ['POST', 'GET', 'OPTIONS']

    # These are the allowed CORS headers
    allowedHeaders = ['content-type', 'x-requested-with']

    # Check that the request Method is valid
    method = request.META['REQUEST_METHOD']
    if method in ["POST", "GET"]:
        # Find the URL that is being requested through this proxy
        url = request.GET.get('url', "http://www.openlayers.org")
    elif method in ["OPTIONS"]:
        # If it is an OPTIONS request, just respond appropriately
        response = HttpResponse("OK", status=200, mimetype="text/plain")
        return proxy_response_cors_headers(response, allowedRequests,
                                           allowedHeaders)
    else:
        return HttpResponseNotAllowed(allowedRequests)

    try:
        # Make sure the requested Host is allowed
        host = url.split("/")[2]
        if allowedHosts and not host in allowedHosts:
            return HttpResponse("502: Bad Gateway. Cannot provide " + url,
                                status=502)

        elif url.startswith("http://") or url.startswith("https://"):
            if method == "POST":
                headers = {
                    'CONTENT-LENGTH': request.META['CONTENT_LENGTH'],
                    'CONTENT-TYPE': request.META.get('CONTENT_TYPE',
                                                     'text/plain')
                }
                body = request.raw_post_data
                r = urllib2.Request(url, body, headers)
                y = urllib2.urlopen(r)
            else:
                y = urllib2.urlopen(url)

            # print content type header
            response = HttpResponse(y.read())
            i = y.info()
            if i.has_key("Content-Type"):
                response['Content-Type'] = i["Content-Type"]
            else:
                response['Content-Type'] = "text/plain"

            y.close()

            return proxy_response_cors_headers(response, allowedRequests,
                                               allowedHeaders)
        else:
            return HttpResponse("Illegal request.")

    except Exception, E:
        return HttpResponse("Some unexpected error occurred. Error text was:" +
                            E,
                            status=500)
Ejemplo n.º 42
0
def json_method_not_allowed(methods: List[Text]) -> HttpResponseNotAllowed:
    resp = HttpResponseNotAllowed(methods)
    resp.content = ujson.dumps({"result": "error",
                                "msg": "Method Not Allowed",
                                "allowed_methods": methods}).encode()
    return resp
Ejemplo n.º 43
0
 def __init__(self, permitted_methods):
     HttpResponseNotAllowed.__init__(self, permitted_methods)