Пример #1
0
def do_logout(request):
    if request.method == 'GET':
        logout(request)
        return render_to_response("login.html",{'mediaRoot': '/resources/', 'errorMsg':''})
    else:
        response = HttpResponseBadRequest()
        response.write("This URI is only available for GET requests.")
Пример #2
0
def single_email_failed_response():
    
    response = HttpResponseBadRequest()
    response.write('<p>The mail was not sent to all the recipients.' +
                   ' Please check your request and try again.</p>')
    response.write('<p>If the problem persists, please contact' +
                   ' the WebOps Team.</p>')
    return response
Пример #3
0
def do_login(request):
    if request.method == 'GET':
        if not request.user.is_authenticated():
            return render_to_response("login.html",{'mediaRoot': '/resources/', 'errorMsg':''})
        else:
            return render_to_response("EditDeploy.html",{'mediaRoot': '/resources/', 'username': request.user.username})
    elif request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return render_to_response("EditDeploy.html",{'mediaRoot': '/resources/', 'username': user.username})
            else:
                return render_to_response("login.html",{'mediaRoot': '/resources/', 'errorMsg':'Please enter a correct username and password. Note that both fields are case-sensitive.'})
        else:
            return render_to_response("login.html",{'mediaRoot': '/resources/', 'errorMsg':'Please enter a correct username and password. Note that both fields are case-sensitive.'})
    else:
        response = HttpResponseBadRequest()
        response.write("This URI is only available for GET or POST requests.")
Пример #4
0
def frames_downloading(request, storage_record_id):
    try:
        frame_request = json.dumps({"exp_id": storage_record_id})
        storage_logger.debug(
            u'Получение изображений: Запрос списка изображений {}'.format(
                frame_request))
        frames = requests.post(STORAGE_FRAMES_INFO_HOST,
                               frame_request,
                               timeout=settings.TIMEOUT_DEFAULT)
        if frames.status_code == 200:
            frames_info = json.loads(frames.content)
            storage_logger.debug(
                u'Получение изображений: Список изображений: {}'.format(
                    frames_info))
            frames_list = [FrameRecord(frame) for frame in frames_info]
        else:
            storage_logger.error(
                u'Получение изображений: Не удается получить список изображений. Ошибка: {}'
                .format(frames.status_code))
            messages.error(
                request,
                u'Не удается получить список изображений. Ошибка: {}'.format(
                    frames.status_code))
            return HttpResponseBadRequest(
                u'Ошибкa {} при получении списка изображений'.format(
                    frames.status_code),
                content_type='text/plain')
    except Timeout as e:
        storage_logger.error(
            u'Получение изображений: Не удается получить список изображений. Ошибка: {}'
            .format(e.message))
        messages.error(
            request,
            u'Не удается получить список изображений. Сервер хранилища не отвечает. Попробуйте позже.'
        )
        return HttpResponseBadRequest(
            u"Не удалось получить список изображений. Истекло время ожидания ответа",
            content_type='text/plain')
    except BaseException as e:
        storage_logger.error(
            u'Получение изображений: Не удается получить список изображений. Ошибка: {}'
            .format(e))
        messages.error(
            request,
            u'Не удается получить список изображений. Сервер хранилища не отвечает. Попробуйте позже.'
        )
        return HttpResponseBadRequest(
            u'Не удалось получить список изображений. Сервер хранилища не отвечает.',
            content_type='text/plain')

    for frame in frames_list:
        file_name = frame.id + '.png'
        if not os.path.exists(os.path.join(MEDIA_ROOT, file_name)):
            try:
                storage_logger.debug(
                    u'Получение изображений: Запрос на получение изображения номер {}'
                    .format(frame.id))
                frame_response = requests.get(STORAGE_FRAMES_PNG.format(
                    exp_id=storage_record_id, frame_id=frame.id),
                                              timeout=settings.TIMEOUT_DEFAULT,
                                              stream=True)
                if frame_response.status_code == 200:
                    temp_file = tempfile.TemporaryFile()
                    for block in frame_response.iter_content(1024 * 8):
                        if not block:
                            break
                        temp_file.write(block)
                    default_storage.save(os.path.join(MEDIA_ROOT, file_name),
                                         temp_file)
                else:
                    storage_logger.error(
                        u'Не удается получить изображениe {}. Ошибка: {}'.
                        format(frame.num, frame_response.status_code))
                    return HttpResponseBadRequest(
                        u'Ошибкa {} при получении изображения'.format(
                            frame_response.status_code),
                        content_type='text/plain')
            except Timeout as e:
                storage_logger.error(
                    u'Получение изображений: Не удается получить изображения. Ошибка: {}'
                    .format(e.message))
                return HttpResponseBadRequest(
                    u'Не удалось получить изображение номер {}. Истекло время ожидания ответа'
                    .format(frame.num),
                    content_type='text/plain')
            except BaseException as e:
                storage_logger.error(
                    u'Получение изображений: Не удается получить изображения. Ошибка: {}'
                    .format(e.message))
                return HttpResponseBadRequest(
                    u'Не удалось получить изображение номер {}. Сервер хранилища не отвечает.'
                    .format(frame.num),
                    content_type='text/plain')

    return HttpResponse(u'Изображения получены успешно',
                        content_type='text/plain')
Пример #5
0
def graph_table(request):
    """Generate graph table page

    :param request:
    :return:
    """

    hostnames = [h.strip() for h in request.GET.getlist('hostname', []) if h]
    object_ids = [o.strip() for o in request.GET.getlist('object_id', []) if o]

    if len(hostnames) == 0 and len(object_ids) == 0:
        return HttpResponseBadRequest('No hostname or object_id provided')

    # For convenience we will cache the servers in a dictionary.
    servers = {s['hostname']: s for s in
               Query({'hostname': Any(*hostnames)}, None)}
    servers.update({s['hostname']: s for s in
                    Query({'object_id': Any(*object_ids)}, None)})

    if len(servers) != len(hostnames) + len(object_ids):
        messages.error(
            request,
            'One or more objects with hostname: {} or object_ids: {} does not '
            'exist'.format(','.join(hostnames), ','.join(object_ids)))

    # Find the collections which are related with all of the hostnames.
    # If there are two collections with same match, use only the one which
    # is not an overview.
    collections = []
    for collection in Collection.objects.order_by('overview', 'sort_order'):
        if any(collection.name == c.name for c in collections):
            continue
        for hostname in servers.keys():
            if GRAPHITE_ATTRIBUTE_ID not in servers[hostname]:
                break   # The server hasn't got this attribute at all.
            value = servers[hostname][GRAPHITE_ATTRIBUTE_ID]
            assert isinstance(value, MultiAttr)
            if not any(collection.name == v for v in value):
                break   # The server hasn't got this attribute value.
            else:
                collections.append(collection)

    # Prepare the graph descriptions
    descriptions = []
    for collection in collections:
        for template in collection.template_set.all():
            descriptions += (
                [(template.name, template.description)] * len(servers.keys())
            )

    # Prepare the graph tables for all hosts
    graph_tables = []
    for hostname in servers.keys():
        graph_table = []
        if request.GET.get('action') == 'Submit':
            custom_params = request.GET.urlencode()
            for collection in collections:
                column = collection.graph_column(
                    servers[hostname], custom_params
                )
                graph_table += [(k, [('Custom', v)]) for k, v in column]
        else:
            for collection in collections:
                graph_table += collection.graph_table(servers[hostname])
        graph_tables.append(graph_table)

    if len(servers) > 1:
        # Add hostname to the titles
        for order, hostname in enumerate(servers.keys()):
            graph_tables[order] = [(k + ' on ' + hostname, v) for k, v in
                                   graph_tables[order]]

        # Combine them
        graph_table = []
        for combined_tables in zip(*graph_tables):
            graph_table += list(combined_tables)

    return TemplateResponse(request, 'graphite/graph_table.html', {
        'hostnames': servers.keys(),
        'descriptions': descriptions,
        'graph_table': graph_table,
        'link': request.get_full_path(),
        'from': request.GET.get('from', '-24h'),
        'until': request.GET.get('until', 'now'),
    })
Пример #6
0
def OperationPlans(request):
    # Check permissions
    if request.method != "GET" or not request.is_ajax():
        return HttpResponseBadRequest('Only ajax get requests allowed')
    if not request.user.has_perm("view_demand_report"):
        return HttpResponseForbidden('<h1>%s</h1>' % _('Permission denied'))

    # Collect list of selected sales orders
    so_list = request.GET.getlist('demand')

    # Collect operationplans associated with the sales order(s)
    id_list = []
    for dm in Demand.objects.all().using(
            request.database).filter(pk__in=so_list).only('plan'):
        for op in dm.plan['pegging']:
            id_list.append(op['opplan'])

    # Collect details on the operationplans
    result = []
    for o in PurchaseOrder.objects.all().using(request.database).filter(
            id__in=id_list, status='proposed'):
        result.append({
            'id': o.id,
            'type': "PO",
            'item': o.item.name,
            'location': o.location.name,
            'origin': o.supplier.name,
            'startdate': str(o.startdate.date()),
            'enddate': str(o.enddate.date()),
            'quantity': float(o.quantity),
            'value': float(o.quantity * o.item.price),
            'criticality': float(o.criticality)
        })
    for o in DistributionOrder.objects.all().using(request.database).filter(
            id__in=id_list, status='proposed'):
        result.append({
            'id': o.id,
            'type': "DO",
            'item': o.item.name,
            'location': o.location.name,
            'origin': o.origin.name,
            'startdate': str(o.startdate),
            'enddate': str(o.enddate),
            'quantity': float(o.quantity),
            'value': float(o.quantity * o.item.price),
            'criticality': float(o.criticality)
        })
    for o in ManufacturingOrder.objects.all().using(request.database).filter(
            id__in=id_list, status='proposed'):
        result.append({
            'id': o.id,
            'type': "MO",
            'item': '',
            'location': o.operation.location.name,
            'origin': o.operation.name,
            'startdate': str(o.startdate.date()),
            'enddate': str(o.enddate.date()),
            'quantity': float(o.quantity),
            'value': '',
            'criticality': float(o.criticality)
        })

    return HttpResponse(content=json.dumps(result),
                        content_type='application/json; charset=%s' %
                        settings.DEFAULT_CHARSET)
Пример #7
0
def update_tables(request, domain, data_type_id, test_patch=None):
    """
    receives a JSON-update patch like following
    {
        "_id":"0920fe1c6d4c846e17ee33e2177b36d6",
        "tag":"growth",
        "view_link":"/a/gsid/fixtures/view_lookup_tables/?table_id:0920fe1c6d4c846e17ee33e2177b36d6",
        "is_global":false,
        "fields":{"genderr":{"update":"gender"},"grade":{}}
    }
    """
    if test_patch is None:
        test_patch = {}
    if data_type_id:
        try:
            data_type = FixtureDataType.get(data_type_id)
        except ResourceNotFound:
            raise Http404()

        assert(data_type.doc_type == FixtureDataType._doc_type)
        assert(data_type.domain == domain)

        if request.method == 'GET':
            return json_response(strip_json(data_type))

        elif request.method == 'DELETE':
            with CouchTransaction() as transaction:
                data_type.recursive_delete(transaction)
            return json_response({})
        elif not request.method == 'PUT':
            return HttpResponseBadRequest()

    if request.method == 'POST' or request.method == "PUT":
        fields_update = test_patch or _to_kwargs(request)
        fields_patches = fields_update["fields"]
        data_tag = fields_update["tag"]
        is_global = fields_update["is_global"]

        # validate tag and fields
        validation_errors = []
        if is_identifier_invalid(data_tag):
            validation_errors.append(data_tag)
        for field_name, options in fields_update['fields'].items():
            method = options.keys()
            if 'update' in method:
                field_name = options['update']
            if is_identifier_invalid(field_name) and 'remove' not in method:
                validation_errors.append(field_name)
        validation_errors = map(lambda e: _("\"%s\" cannot include special characters or "
                                            "begin with \"xml\" or a number.") % e, validation_errors)
        if validation_errors:
            return json_response({
                'validation_errors': validation_errors,
                'error_msg': _(
                    "Could not update table because field names were not "
                    "correctly formatted"),
            })

        with CouchTransaction() as transaction:
            if data_type_id:
                data_type = update_types(fields_patches, domain, data_type_id, data_tag, is_global, transaction)
                update_items(fields_patches, domain, data_type_id, transaction)
            else:
                if FixtureDataType.fixture_tag_exists(domain, data_tag):
                    return HttpResponseBadRequest("DuplicateFixture")
                else:
                    data_type = create_types(fields_patches, domain, data_tag, is_global, transaction)
        return json_response(strip_json(data_type))
Пример #8
0
def main(request, party=None):
    viewmode = settings.VIEWMODE_
    open_new_tab = settings.OPEN_NEW_TAB_
    hide_contest = settings.HIDE_CONTEST_
    share_to_category = None

    if request.user.is_authenticated:
        if request.GET.get('as_coder') and request.user.has_perm('as_coder'):
            coder = Coder.objects.get(user__username=request.GET['as_coder'])
        else:
            coder = request.user.coder
        viewmode = coder.settings.get("view_mode", viewmode)
        hide_contest = coder.settings.get("hide_contest", hide_contest)
        open_new_tab = coder.settings.get("open_new_tab", open_new_tab)
        share_to_category = coder.settings.get("share_to_category",
                                               share_to_category)
    else:
        coder = None
    viewmode = request.GET.get("view", viewmode)
    hide_contest = request.GET.get("hide_contest", hide_contest)

    hide_contest = int(str(hide_contest).lower() in settings.YES_)

    time_format = get_timeformat(request)

    action = request.GET.get("action")
    if action is not None:
        if action == "party-contest-toggle" and request.user.is_authenticated:
            party = get_object_or_404(Party.objects.for_user(request.user),
                                      slug=request.GET.get("party"),
                                      author=coder)
            contest = get_object_or_404(Contest, pk=request.GET.get("pk"))
            rating, created = Rating.objects.get_or_create(contest=contest,
                                                           party=party)
            if not created:
                rating.delete()
            return HttpResponse("ok")
        if action == "hide-contest-toggle":
            contest = get_object_or_404(Contest, pk=request.GET.get("pk"))
            filt, created = Filter.objects.get_or_create(coder=coder,
                                                         contest=contest,
                                                         to_show=False)
            if not created:
                filt.delete()
                return HttpResponse("deleted")
            return HttpResponse("created")
        return HttpResponseBadRequest("fail")

    has_tz = request.user.is_authenticated or "timezone" in request.session
    tzname = get_timezone(request)
    if tzname is None:
        return HttpResponse("accepted" if has_tz else "reload")

    if coder:
        ignore_filters = coder.ordered_filter_set.filter(
            categories__contains=['calendar'])
        ignore_filters = ignore_filters.filter(name__isnull=False).exclude(
            name='')
        ignore_filters = list(ignore_filters.values('id', 'name'))
    else:
        ignore_filters = []

    if not coder or coder.settings.get('calendar_filter_long', True):
        ignore_filters = ignore_filters + [{
            'id': 0,
            'name': 'Disabled fitler'
        }]

    context = {
        "ignore_filters": ignore_filters,
        "contests": get_view_contests(request, coder),
    }

    if isinstance(party, Party):
        context["party"] = {
            "id":
            party.id,
            "toggle_contest":
            1,
            "has_permission_toggle":
            int(party.has_permission_toggle_contests(coder)),
            "contest_ids":
            party.rating_set.values_list('contest__id', flat=True),
        }

    now = timezone.now()
    banners = Banner.objects.filter(end_time__gt=now)
    if not settings.DEBUG:
        banners = banners.filter(enable=True)

    offset = get_timezone_offset(tzname)

    context.update({
        "offset": offset,
        "now": now,
        "viewmode": viewmode,
        "hide_contest": hide_contest,
        "share_to_category": share_to_category,
        "timezone": tzname,
        "time_format": time_format,
        "open_new_tab": open_new_tab,
        "add_to_calendar": get_add_to_calendar(request),
        "banners": banners,
    })

    return render(request, "main.html", context)
Пример #9
0
def upload(request):
    course_prefix = request.POST.get("course_prefix")
    course_suffix = request.POST.get("course_suffix")
    exam_id = request.POST.get("exam_id",'')
    common_page_data = get_common_page_data(request, course_prefix, course_suffix)

    data = {'common_page_data': common_page_data}

    if request.method == 'POST':
        request.session['video_privacy'] = request.POST.get("video_privacy")

    
        # Need partial instance with course for form slug validation
        new_video = Video(course=common_page_data['course'])
        form = S3UploadForm(request.POST, request.FILES, course=common_page_data['course'], instance=new_video)
        if form.is_valid():
            new_video.index = new_video.section.getNextIndex()
            new_video.mode = 'draft'
            new_video.handle = course_prefix + "--" + course_suffix

            if exam_id:
                try:
                    exam = Exam.objects.get(id=exam_id)
                except Exam.DoesNotExist:
                    return HttpResponseBadRequest("The exam you wanted to link to this video was not found!")
                new_video.exam = exam
            
                exam.live_datetime = new_video.live_datetime
                exam.save()
                if exam.image:
                    exam.image.live_datetime = new_video.live_datetime
                    exam.image.save()

        
        
            # Bit of jiggery pokery to so that the id is set when the upload_path function is called.
            # Now storing file with id appended to the file path so that thumbnail and associated manifest files
            # are easily associated with the video by putting them all in the same directory.
            new_video.file = None
            new_video.save()
            new_video.file = form.cleaned_data['file']
            new_video.save()

            kelvinator.tasks.duration.delay(new_video)

            new_video.create_ready_instance()

            # kick off remote jobs
            kelvinator.tasks.kelvinate.delay(new_video.file.name)
            # kelvinator.tasks.resize.delay(new_video.file.name, "large")
            # kelvinator.tasks.resize.delay(new_video.file.name, "small")
            
            if is_storage_local():
                return redirect('courses.videos.views.list', course_prefix, course_suffix)

            if new_video.url:
                return redirect('courses.videos.views.list', course_prefix, course_suffix)

            authUrl = GetOAuth2Url(request, new_video)
            #eventually should store an access token, so they don't have to give permission everytime
            return redirect(authUrl)
        #    return redirect("http://" + request.META['HTTP_HOST'])


    else:
        form = S3UploadForm(course=common_page_data['course'])
    data['form'] = form

    return render_to_response('videos/s3upload.html',
                              data,
                              context_instance=RequestContext(request))
Пример #10
0
def create_plan(request):
    plan_id = request.POST["plan_id"]
    if plan_id not in ("P5", "P75"):
        return HttpResponseBadRequest()

    sub = Subscription.objects.for_user(request.user)

    # Cancel the previous plan
    if sub.subscription_id:
        braintree.Subscription.cancel(sub.subscription_id)
        sub.subscription_id = ""
        sub.plan_id = ""
        sub.save()

    # Create Braintree customer record
    if not sub.customer_id:
        result = braintree.Customer.create({"email": request.user.email})
        if not result.is_success:
            return log_and_bail(request, result)

        sub.customer_id = result.customer.id
        sub.save()

    # Create Braintree payment method
    if "payment_method_nonce" in request.POST:
        result = braintree.PaymentMethod.create({
            "customer_id":
            sub.customer_id,
            "payment_method_nonce":
            request.POST["payment_method_nonce"]
        })

        if not result.is_success:
            return log_and_bail(request, result)

        sub.payment_method_token = result.payment_method.token
        sub.save()

    # Create Braintree subscription
    result = braintree.Subscription.create({
        "payment_method_token": sub.payment_method_token,
        "plan_id": plan_id,
    })

    if not result.is_success:
        return log_and_bail(request, result)

    sub.subscription_id = result.subscription.id
    sub.plan_id = plan_id
    sub.save()

    # Update user's profile
    profile = request.user.profile
    if plan_id == "P5":
        profile.ping_log_limit = 1000
        profile.team_access_allowed = True
        profile.save()
    elif plan_id == "P75":
        profile.ping_log_limit = 1000
        profile.team_access_allowed = True
        profile.save()

    request.session["first_charge"] = True
    return redirect("hc-pricing")
Пример #11
0
 def invalid_action():
     if REGISTRATION_CONFIRM_INVALID_REDIRECT_PATH:
         return HttpResponseRedirect(REGISTRATION_CONFIRM_INVALID_REDIRECT_PATH)
     else:
         return HttpResponseBadRequest('invalid token!')
Пример #12
0
def ensure_user_information(strategy, auth_entry, backend=None, user=None, social=None, current_partial=None,
                            allow_inactive_user=False, details=None, *args, **kwargs):
    """
    Ensure that we have the necessary information about a user (either an
    existing account or registration data) to proceed with the pipeline.
    """

    # We're deliberately verbose here to make it clear what the intended
    # dispatch behavior is for the various pipeline entry points, given the
    # current state of the pipeline. Keep in mind the pipeline is re-entrant
    # and values will change on repeated invocations (for example, the first
    # time through the login flow the user will be None so we dispatch to the
    # login form; the second time it will have a value so we continue to the
    # next pipeline step directly).
    #
    # It is important that we always execute the entire pipeline. Even if
    # behavior appears correct without executing a step, it means important
    # invariants have been violated and future misbehavior is likely.
    def dispatch_to_login():
        """Redirects to the login page."""
        return redirect(AUTH_DISPATCH_URLS[AUTH_ENTRY_LOGIN])

    def dispatch_to_register():
        """Redirects to the registration page."""
        return redirect(AUTH_DISPATCH_URLS[AUTH_ENTRY_REGISTER])

    def should_force_account_creation():
        """ For some third party providers, we auto-create user accounts """
        current_provider = provider.Registry.get_from_pipeline({'backend': current_partial.backend, 'kwargs': kwargs})
        return (current_provider and
                (current_provider.skip_email_verification or current_provider.send_to_registration_first))

    if not user:
        if user_exists(details or {}):
            # User has not already authenticated and the details sent over from
            # identity provider belong to an existing user.
            return dispatch_to_login()

        if is_api(auth_entry):
            return HttpResponseBadRequest()
        elif auth_entry == AUTH_ENTRY_LOGIN:
            # User has authenticated with the third party provider but we don't know which edX
            # account corresponds to them yet, if any.
            if should_force_account_creation():
                return dispatch_to_register()
            return dispatch_to_login()
        elif auth_entry == AUTH_ENTRY_REGISTER:
            # User has authenticated with the third party provider and now wants to finish
            # creating their edX account.
            return dispatch_to_register()
        elif auth_entry == AUTH_ENTRY_ACCOUNT_SETTINGS:
            raise AuthEntryError(backend, 'auth_entry is wrong. Settings requires a user.')
        elif auth_entry in AUTH_ENTRY_CUSTOM:
            # Pass the username, email, etc. via query params to the custom entry page:
            return redirect_to_custom_form(strategy.request, auth_entry, details or {}, kwargs)
        else:
            raise AuthEntryError(backend, 'auth_entry invalid')

    if not user.is_active:
        # The user account has not been verified yet.
        if allow_inactive_user:
            # This parameter is used by the auth_exchange app, which always allows users to
            # login, whether or not their account is validated.
            pass
        elif social is None:
            # The user has just registered a new account as part of this pipeline. Their account
            # is inactive but we allow the login to continue, because if we pause again to force
            # the user to activate their account via email, the pipeline may get lost (e.g.
            # email takes too long to arrive, user opens the activation email on a different
            # device, etc.). This is consistent with first party auth and ensures that the
            # pipeline completes fully, which is critical.
            pass
        else:
            # This is an existing account, linked to a third party provider but not activated.
            # Double-check these criteria:
            assert user is not None
            assert social is not None
            # We now also allow them to login again, because if they had entered their email
            # incorrectly then there would be no way for them to recover the account, nor
            # register anew via SSO. See SOL-1324 in JIRA.
            # However, we will log a warning for this case:
            logger.warning(
                'User "%s" is using third_party_auth to login but has not yet activated their account. ',
                user.username
            )
Пример #13
0
 def __init__(self):
   HttpResponseBadRequest.__init__(self)
   self.write('<p>Bad Request. Please check your query and try again.</p>')
Пример #14
0
def publish_channel(request, channelid):
    status, response = ccserver_publish_channel(request.user, channelid)
    if status == "failure":
        return HttpResponseBadRequest(response)
    return HttpResponse(response)
Пример #15
0
def deploy_channel(request, channelid):
    status, response = activate_channel(request.user, channelid)
    if status == "failure":
        return HttpResponseBadRequest(response)
    return HttpResponse(response)
Пример #16
0
    def post(self, request, *args, **kwargs):
        limit_reached = misc.is_user_limit_reached()

        username = request.POST["username"].strip()
        password = request.POST["password"].strip()

        if request.POST.get("ajax", "") == "1":
            ret = {"result": 0}

            if request.POST.get("method", "") == "register" and \
               config.get_configuration('FREE_REGISTRATION') and \
               not limit_reached:
                email = request.POST["email"].strip()
                fullname = request.POST["fullname"].strip()
                ret["result"] = self._do_checks_for_empty(request)

                if ret["result"] == 0:  # if there was no errors
                    ret["result"] = self._do_check_valid(request)

                    if ret["result"] == 0:
                        ret["result"] = 1

                        user = None
                        try:
                            user = auth.models.User.objects.create_user(
                                username=username,
                                email=email,
                                password=password)
                        except IntegrityError:
                            ret["result"] = 10
                        except:
                            ret["result"] = 10
                            user = None

                        # this is not a good place to fire signal, but i need password for now
                        # should create function createUser for future use

                        if user:
                            user.first_name = fullname

                            booktype.apps.account.signals.account_created.send(
                                sender=user,
                                password=request.POST['password'],
                                post_params=request.POST)

                            try:
                                user.save()

                                # groups

                                for group_name in json.loads(
                                        request.POST.get('groups')):
                                    if group_name.strip() != '':
                                        try:
                                            group = BookiGroup.objects.get(
                                                url_name=group_name)
                                            group.members.add(user)
                                        except:
                                            pass

                                user2 = auth.authenticate(username=username,
                                                          password=password)
                                auth.login(request, user2)
                            except:
                                ret['result'] = 666

            if request.POST.get('method', '') == 'signin':
                user = auth.authenticate(username=username, password=password)

                if user and user.is_active:
                    auth.login(request, user)
                    ret['result'] = 1
                elif user and not user.is_active:
                    ret['result'] = 4
                else:
                    try:
                        auth.models.User.objects.get(username=username)
                        # User does exist. Must be wrong password then
                        ret['result'] = 3
                    except auth.models.User.DoesNotExist:
                        # User does not exist
                        ret['result'] = 2

            if ret['result'] == 1:
                invite_data = request.session.pop('invite_data', False)
                if invite_data:
                    assign_invitation(user, invite_data)

            return HttpResponse(json.dumps(ret), content_type="text/json")
        return HttpResponseBadRequest()
Пример #17
0
def likes_friendship(request, kind=''):
    try:
        req_username = request.GET.get('reqUser', False)
        req_user = ''
        if req_username:
            req_user = ExtUser.objects.get(username=req_username)

        token = request.META['HTTP_TOKEN']
        user = Token.objects.get(pk=token).user

        if kind == 'create':
            user.create_friendship(req_user)
            return HttpResponse('Like created.')

        elif kind == 'delete':
            if user.delete_friendship(req_user) is True:
                return HttpResponse('Like deleted.')

        elif kind == 'getMutually':
            likes1, likes2 = user.get_friends()
            likes = list(chain(likes1, likes2))
            all_likes = []

            for like in likes:
                if like.friend != user:
                    all_likes.append({
                        'username':
                        like.friend.username,
                        'photo':
                        'http://' + request.get_host() +
                        like.friend.profile.photo.url,
                        'age':
                        str(like.friend.birthday),
                        'location':
                        like.friend.location,
                        'date':
                        str(like.created.date())
                    })
                else:
                    all_likes.append({
                        'username':
                        like.creator.username,
                        'photo':
                        'http://' + request.get_host() +
                        like.creator.profile.photo.url,
                        'age':
                        str(like.creator.birthday),
                        'location':
                        like.creator.location,
                        'date':
                        str(like.created.date())
                    })

            return JsonResponse({'ownLikes': all_likes})

        elif kind == 'getSentLikes':
            likes1, likes2 = user.get_sent_requests_for_friendship()

            sent_likes = list(chain(likes1, likes2))
            likes = []

            for sent in sent_likes:
                if sent.friend != user:
                    likes.append({
                        'username':
                        sent.friend.username,
                        'photo':
                        'http://' + request.get_host() +
                        sent.friend.profile.photo.url,
                        'age':
                        str(sent.friend.birthday),
                        'location':
                        sent.friend.location,
                        'date':
                        str(sent.created.date())
                    })
                else:
                    likes.append({
                        'username':
                        sent.creator.username,
                        'photo':
                        'http://' + request.get_host() +
                        sent.creator.profile.photo.url,
                        'age':
                        str(sent.creator.birthday),
                        'location':
                        sent.creator.location,
                        'date':
                        str(sent.created.date())
                    })

            return JsonResponse({'ownLikes': likes})

        elif kind == 'getOwnLikes':
            own_likes = user.get_requests_for_friendships()
            likes = []
            for like in own_likes:
                likes.append({
                    'username':
                    like.creator.username,
                    'photo':
                    'http://' + request.get_host() +
                    like.creator.profile.photo.url,
                    'age':
                    str(like.creator.birthday),
                    'location':
                    like.creator.location,
                    'date':
                    str(like.created.date())
                })
            return JsonResponse({'ownLikes': likes})
    except Token.DoesNotExist:
        return HttpResponseBadRequest('Token does not exist.')

    except Exception as e:
        return HttpResponseBadRequest('Something went wrong.')
Пример #18
0
def vcs_service_hook(request, service):
    """Shared code between VCS service hooks.

    Currently used for bitbucket_hook, github_hook and gitlab_hook, but should
    be usable for other VCS services (Google Code, custom coded sites, etc.)
    too.
    """
    # We support only post methods
    if not settings.ENABLE_HOOKS:
        return HttpResponseNotAllowed(())

    # Check if we got payload
    try:
        data = parse_hook_payload(request)
    except (ValueError, KeyError):
        return HttpResponseBadRequest('Could not parse JSON payload!')

    if not data:
        return HttpResponseBadRequest('Invalid data in json payload!')

    # Get service helper
    hook_helper = HOOK_HANDLERS[service]

    # Send the request data to the service handler.
    try:
        service_data = hook_helper(data, request)
    except Exception as error:
        LOGGER.error('failed to parse service %s data', service)
        report_error(error, request)
        return HttpResponseBadRequest('Invalid data in json payload!')

    # This happens on ping request upon installation
    if service_data is None:
        return hook_response('Hook working')

    # Log data
    service_long_name = service_data['service_long_name']
    repos = service_data['repos']
    repo_url = service_data['repo_url']
    branch = service_data['branch']
    full_name = service_data['full_name']

    # Generate filter
    spfilter = Q(repo__in=repos) | Q(repo__iendswith=full_name)

    # We need to match also URLs which include username and password
    for repo in repos:
        if repo.startswith('http://'):
            spfilter = spfilter | (Q(repo__startswith='http://')
                                   & Q(repo__endswith='@{0}'.format(repo[7:])))
        elif repo.startswith('https://'):
            spfilter = spfilter | (Q(repo__startswith='https://')
                                   & Q(repo__endswith='@{0}'.format(repo[8:])))

    all_components = Component.objects.filter(spfilter)

    if branch is not None:
        all_components = all_components.filter(branch=branch)

    components = all_components.filter(project__enable_hooks=True)

    LOGGER.info(
        'received %s notification on repository %s, branch %s, '
        '%d matching components, %d to process',
        service_long_name,
        repo_url,
        branch,
        all_components.count(),
        components.count(),
    )

    # Trigger updates
    updates = 0
    for obj in components:
        updates += 1
        LOGGER.info('%s notification will update %s', service_long_name, obj)
        Change.objects.create(
            component=obj,
            action=Change.ACTION_HOOK,
            details=service_data,
        )
        perform_update.delay('Component', obj.pk)

    if updates == 0:
        return hook_response('No matching repositories found!', 'failure')

    return hook_response('Update triggered: {}'.format(', '.join(
        [obj.full_slug for obj in components])))
Пример #19
0
 def __init__(self, message):
     DjangoHttpResponseBadRequest.__init__(self,
                                           message_to_json(message),
                                           content_type='application/json')
Пример #20
0
 def _decorator(request, *args, **kwargs):
     # Deny access if the entrance exam feature is disabled
     if not core_toggles.ENTRANCE_EXAMS.is_enabled():
         return HttpResponseBadRequest()
     return view_func(request, *args, **kwargs)
Пример #21
0
    def get(self, request, patient_id=None, format=None):

        badRequest = False
        notFound = False
        patient = None

        if patient_id:
            try:
                patient = Patient.objects.get(id=patient_id)
            except:
                patient = None
        else:
            # look for optional arguments for searching
            kwargs = {}
            name = request.GET.get('name', '')
            if not name == '':
                try:
                    patient = Patient.objects.filter(
                        Q(paternal_last__icontains=name)
                        | Q(maternal_last__icontains=name)
                        | Q(first__icontains=name) | Q(middle__icontains=name))
                except:
                    patient = None
            else:
                paternal_last = request.GET.get('paternal_last', '')
                if not paternal_last == '':
                    kwargs["paternal_last__icontains"] = paternal_last
                maternal_last = request.GET.get('maternal_last', '')
                if not maternal_last == '':
                    kwargs["maternal_last__icontains"] = maternal_last
                first = request.GET.get('first', '')
                if not first == '':
                    kwargs["first__icontains"] = first
                dob = request.GET.get('dob', '')
                if not dob == '':
                    x = dob.split("/")
                    if len(x) == 3:
                        try:
                            kwargs["dob"] = datetime.strptime(dob, "%m/%d/%Y")
                        except:
                            badRequest = True
                    else:
                        badRequest = True

                gender = request.GET.get('gender', '')
                if not gender == '':
                    if gender == "Male":
                        kwargs["gender"] = "m"
                    elif gender == "Female":
                        kwargs["gender"] = "f"
                    else:
                        badRequest = True

                if not badRequest:
                    try:
                        patient = Patient.objects.filter(**kwargs)
                    except:
                        patient = None

        if not patient and not badRequest:
            notFound = True
        elif patient:
            if patient_id:
                ret = self.serialize(patient)
            else:
                ret = []
                for x in patient:
                    ret.append(x.id)
        if badRequest:
            return HttpResponseBadRequest()
        elif notFound:
            return HttpResponseNotFound()
        else:
            return Response(ret)
Пример #22
0
                if sid:
                    try:
                        act_state = ActivityState.objects.get(
                            state_id=str(urllib.unquote(sid)))
                    except Exception, e:
                        return HttpResponseBadRequest(e.message)
                    return_json.append({"stateId": str(sid)}.items() +
                                       state_data.items())
            return HttpResponse(json.dumps(return_json),
                                content_type="application/json",
                                status=200)
        else:
            return HttpResponse(state.json_state,
                                content_type=state.content_type,
                                status=200)
    return HttpResponseBadRequest(
        "Activity ID, State ID and Agent are all required")


@login_required(login_url=LOGIN_URL)
def my_activity_profiles(request):
    act_id = request.GET.get("act_id", None)
    if act_id:
        profs = ActivityProfile.objects.filter(
            activityId=urllib.unquote(act_id))
        p_list = []
        for prof in profs:
            p_list.append({
                "profileId": prof.profileId,
                "updated": str(prof.updated)
            })
        return HttpResponse(json.dumps(p_list),
Пример #23
0
    def post(self, request):
        """ Allow users to post images i.e upload images to cloud storage.

        POST request parameters:
            [REQUIRED]
            image: containing a file object for the image to be uploaded
                or
            base64: containig the base64 equivalent of the image to be uploaded

            [OPTIONAL]
            eventId: containg the event id of the event where the image will be
                    rendered
            isTrusted: whether the image came from a trusted source or not


        Arguments:
            request {[type]} -- [ Contains the django request object]
        Returns:
            [HttpResponseBadRequest] -- [If  neither image or base64 parameter 
                                        is provided]
            [JsonResponse] -- [Containing the uuid of image]     
        """
        print("Request Recieved", time.time())
        # Generate uuid for the file. Never trust user.
        image = Image(name=str(uuid4()))
        print()
        if request.FILES.get('image', False):
            uploaded_file = request.FILES['image']
            file_system = FileSystemStorage()
            # save
            file_system.save(image.name, uploaded_file)
            image.uuid = image.name + '.' + uploaded_file.name.split('.')[-1]

        elif request.POST.get('base64', False):
            data_uri = request.POST['base64']
            # name = str(uuid4())
            # NOTE: decodestring is deprecated
            img = base64.decodestring(str.encode(data_uri.split(",")[1]))

            with open(image.name, "wb") as image_file:
                image_file.write(img)
            image.uuid = image.name + '.jpg'
        else:
            return HttpResponseBadRequest(
                "Bad request: base64 or image field should be given")
        print("File Saved", time.time())

        image.create_thumbnail(storage=STORAGE)
        # Upload files to Cloud storage
        image.put(storage=STORAGE)

        # Update Event if id is given,
        if request.POST.get("eventId", False):
            event_id = request.POST.get("eventId", False)
            is_trusted = request.POST.get('isValid', '') == 'true'
            image.is_trusted = is_trusted
            image.save(event_id, DB)
            # DB.child('incidents').child(event_id).child("images").push(image_data)
            print("Image Added")
        # Return file id for future reference
        print("Returning From Request", time.time())
        return JsonResponse({'name': image.uuid})
Пример #24
0
def checklists_handler(request,
                       tag=None,
                       package_id=None,
                       branch=None,
                       version_guid=None,
                       block=None,
                       checklist_index=None):
    """
    The restful handler for checklists.

    GET
        html: return html page for all checklists
        json: return json representing all checklists. checklist_index is not supported for GET at this time.
    POST or PUT
        json: updates the checked state for items within a particular checklist. checklist_index is required.
    """
    location = BlockUsageLocator(package_id=package_id,
                                 branch=branch,
                                 version_guid=version_guid,
                                 block_id=block)
    if not has_course_access(request.user, location):
        raise PermissionDenied()

    old_location = loc_mapper().translate_locator_to_location(location)

    modulestore = get_modulestore(old_location)
    course_module = modulestore.get_item(old_location)

    json_request = 'application/json' in request.META.get(
        'HTTP_ACCEPT', 'application/json')
    if request.method == 'GET':
        # If course was created before checklists were introduced, copy them over
        # from the template.
        if not course_module.checklists:
            course_module.checklists = CourseDescriptor.checklists.default
            modulestore.update_item(course_module, request.user.id)

        expanded_checklists = expand_all_action_urls(course_module)
        if json_request:
            return JsonResponse(expanded_checklists)
        else:
            handler_url = location.url_reverse('checklists/', '')
            return render_to_response(
                'checklists.html',
                {
                    'handler_url': handler_url,
                    # context_course is used by analytics
                    'context_course': course_module,
                    'checklists': expanded_checklists
                })
    elif json_request:
        # Can now assume POST or PUT because GET handled above.
        if checklist_index is not None and 0 <= int(checklist_index) < len(
                course_module.checklists):
            index = int(checklist_index)
            persisted_checklist = course_module.checklists[index]
            modified_checklist = json.loads(request.body)
            # Only thing the user can modify is the "checked" state.
            # We don't want to persist what comes back from the client because it will
            # include the expanded action URLs (which are non-portable).
            for item_index, item in enumerate(modified_checklist.get('items')):
                persisted_checklist['items'][item_index]['is_checked'] = item[
                    'is_checked']
            # seeming noop which triggers kvs to record that the metadata is
            # not default
            course_module.checklists = course_module.checklists
            course_module.save()
            modulestore.update_item(course_module, request.user.id)
            expanded_checklist = expand_checklist_action_url(
                course_module, persisted_checklist)
            return JsonResponse(expanded_checklist)
        else:
            return HttpResponseBadRequest(
                ("Could not save checklist state because the checklist index "
                 "was out of range or unspecified."),
                content_type="text/plain")
    else:
        return HttpResponseNotFound()
Пример #25
0
def delete_user(request):
    if request.user.is_authenticated():
        if request.method == 'DELETE':
            request.user.delete()
            return HttpResponse('OK')
    return HttpResponseBadRequest('Bad credentials')
Пример #26
0
def post_comment_ajax(request, using=None):
    """
	Post a comment, via an Ajax call.
	"""
    if not request.is_ajax():
        return HttpResponseBadRequest("Expecting Ajax call")

    # This is copied from django.contrib.comments.
    # Basically that view does too much, and doesn't offer a hook to change the rendering.
    # The request object is not passed to next_redirect for example.
    #
    # This is a separate view to integrate both features. Previously this used django-ajaxcomments
    # which is unfortunately not thread-safe (it it changes the comment view per request).

    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name(
            ) or request.user.username
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    if ctype is None or object_pk is None:
        return CommentPostBadRequest(
            "Missing content_type or object_pk field.")
    try:
        object_pk = long(object_pk)
        model = models.get_model(*ctype.split(".", 1))
        target = model._default_manager.using(using).get(pk=object_pk)
    except ValueError:
        return CommentPostBadRequest("Invalid object_pk value: {0}".format(
            escape(object_pk)))
    except TypeError:
        return CommentPostBadRequest("Invalid content_type value: {0}".format(
            escape(ctype)))
    except AttributeError:
        return CommentPostBadRequest(
            "The given content-type {0} does not resolve to a valid model.".
            format(escape(ctype)))
    except ObjectDoesNotExist:
        return CommentPostBadRequest(
            "No object matching content-type {0} and object PK {1} exists.".
            format(escape(ctype), escape(object_pk)))
    except (ValueError, ValidationError) as e:
        return CommentPostBadRequest(
            "Attempting go get content-type {0!r} and object PK {1!r} exists raised {2}"
            .format(escape(ctype), escape(object_pk), e.__class__.__name__))

    # Do we want to preview the comment?
    preview = "preview" in data

    # Construct the comment form
    form = comments.get_form()(target, data=data)

    # Check security information
    if form.security_errors():
        return CommentPostBadRequest(
            "The comment form failed security verification: {0}".format)

    # If there are errors or if we requested a preview show the comment
    if preview:
        comment = form.get_comment_object() if not form.errors else None
        return _ajax_result(request,
                            form,
                            "preview",
                            comment,
                            object_id=object_pk)
    if form.errors:
        return _ajax_result(request, form, "post", object_id=object_pk)

    # Otherwise create the comment
    comment = form.get_comment_object()
    comment.ip_address = request.META.get("REMOTE_ADDR", None)
    if request.user.is_authenticated():
        comment.user = request.user

    # Signal that the comment is about to be saved
    responses = signals.comment_will_be_posted.send(sender=comment.__class__,
                                                    comment=comment,
                                                    request=request)

    for (receiver, response) in responses:
        if response is False:
            return CommentPostBadRequest(
                "comment_will_be_posted receiver {0} killed the comment".
                format(receiver.__name__))

    # Save the comment and signal that it was saved
    comment.save()
    signals.comment_was_posted.send(sender=comment.__class__,
                                    comment=comment,
                                    request=request)

    if isinstance(comment.content_object, Post):
        post = comment.content_object
        if comment.user.id is not post.user.id:
            notify.send(comment.user,
                        recipient=post.user,
                        verb=u'has commented on your post',
                        action_object=comment,
                        description=u'',
                        target=post)

    return _ajax_result(request, form, "post", comment, object_id=object_pk)
Пример #27
0
def upload_image(request, imageset_id):
    imageset = get_object_or_404(ImageSet, id=imageset_id)
    if request.method == 'POST' \
            and imageset.has_perm('edit_set', request.user) \
            and not imageset.image_lock:
        if request.FILES is None:
            return HttpResponseBadRequest('Must have files attached!')
        json_files = []
        for f in request.FILES.getlist('files[]'):
            error = {
                'duplicates': 0,
                'damaged': False,
                'directories': False,
                'exists': False,
                'unsupported': False,
                'zip': False,
            }
            magic_number = f.read(4)
            f.seek(0)  # reset file cursor to the beginning of the file
            if magic_number == b'PK\x03\x04':  # ZIP file magic number
                error['zip'] = True
                zipname = ''.join(random.choice(string.ascii_uppercase +
                                                string.ascii_lowercase +
                                                string.digits)
                                  for _ in range(6)) + '.zip'
                if not os.path.exists(os.path.join(imageset.root_path(), 'tmp')):
                    os.makedirs(os.path.join(imageset.root_path(), 'tmp'))
                with open(os.path.join(imageset.root_path(), 'tmp', zipname), 'wb') as out:
                    for chunk in f.chunks():
                        out.write(chunk)
                # unpack zip-file
                zip_ref = zipfile.ZipFile(os.path.join(imageset.root_path(), 'tmp', zipname), 'r')
                zip_ref.extractall(os.path.join(imageset.root_path(), 'tmp'))
                zip_ref.close()
                # delete zip-file
                os.remove(os.path.join(imageset.root_path(), 'tmp', zipname))
                filenames = [f for f in os.listdir(os.path.join(imageset.root_path(), 'tmp'))]
                filenames.sort()
                duplicat_count = 0
                for filename in filenames:
                    file_path = os.path.join(imageset.root_path(), 'tmp', filename)
                    try:
                        if imghdr.what(file_path) in settings.IMAGE_EXTENSION:
                            # creates a checksum for image
                            fchecksum = hashlib.sha512()
                            with open(file_path, 'rb') as fil:
                                while True:
                                    buf = fil.read(10000)
                                    if not buf:
                                        break
                                    fchecksum.update(buf)
                            fchecksum = fchecksum.digest()
                            # Tests for duplicats in imageset
                            if Image.objects.filter(checksum=fchecksum,
                                                    image_set=imageset).count() == 0:
                                (shortname, extension) = os.path.splitext(filename)
                                img_fname = (''.join(shortname) + '_' +
                                             ''.join(
                                                 random.choice(
                                                     string.ascii_uppercase + string.ascii_lowercase + string.digits)
                                                 for _ in range(6)) + extension)
                                try:
                                    with PIL_Image.open(file_path) as image:
                                        width, height = image.size
                                    file_new_path = os.path.join(imageset.root_path(), img_fname)
                                    shutil.move(file_path, file_new_path)
                                    shutil.chown(file_new_path, group=settings.UPLOAD_FS_GROUP)
                                    new_image = Image(name=filename,
                                                      image_set=imageset,
                                                      filename=img_fname,
                                                      checksum=fchecksum,
                                                      width=width,
                                                      height=height
                                                      )
                                    new_image.save()
                                except (OSError, IOError):
                                    error['damaged'] = True
                                    os.remove(file_path)
                            else:
                                os.remove(file_path)
                                duplicat_count = duplicat_count + 1
                        else:
                            error['unsupported'] = True
                    except IsADirectoryError:
                        error['directories'] = True
                if duplicat_count > 0:
                    error['duplicates'] = duplicat_count
            else:
                # creates a checksum for image
                fchecksum = hashlib.sha512()
                for chunk in f.chunks():
                    fchecksum.update(chunk)
                fchecksum = fchecksum.digest()
                # tests for duplicats in  imageset
                if Image.objects.filter(checksum=fchecksum, image_set=imageset)\
                        .count() == 0:
                    fname = f.name.split('.')
                    fname = ('_'.join(fname[:-1]) + '_' +
                             ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)
                                     for _ in range(6)) + '.' + fname[-1])
                    image = Image(
                        name=f.name,
                        image_set=imageset,
                        filename=fname,
                        checksum=fchecksum)
                    with open(image.path(), 'wb') as out:
                        for chunk in f.chunks():
                            out.write(chunk)
                    shutil.chown(image.path(), group=settings.UPLOAD_FS_GROUP)
                    if imghdr.what(image.path()) in settings.IMAGE_EXTENSION:
                        try:
                            with PIL_Image.open(image.path()) as image_file:
                                width, height = image_file.size
                            image.height = height
                            image.width = width
                            image.save()
                        except (OSError, IOError):
                            error['damaged'] = True
                            os.remove(image.path())
                    else:
                        error['unsupported'] = True
                        os.remove(image.path())
                else:
                    error['exists'] = True
            errormessage = ''
            if error['zip']:
                errors = list()
                if error['directories']:
                    errors.append('directories')
                if error['unsupported']:
                    errors.append('unsupported files')
                if error['duplicates'] > 0:
                    errors.append(str(error['duplicates']) + ' duplicates')
                if error['damaged']:
                    errors.append('damaged files')
                if len(errors) > 0:
                    # Build beautiful error message
                    errormessage += ', '.join(errors) + ' in the archive have been skipped!'
                    p = errormessage.rfind(',')
                    if p != -1:
                        errormessage = errormessage[:p].capitalize() + ' and' + errormessage[p + 1:]
                    else:
                        errormessage = errormessage.capitalize()
            else:
                if error['unsupported']:
                    errormessage = 'This file type is unsupported!'
                elif error['damaged']:
                    errormessage = 'This file seems to be damaged!'
                elif error['exists']:
                    errormessage = 'This image already exists in the imageset!'
            if errormessage == '':
                json_files.append({'name': f.name,
                                   'size': f.size,
                                   # 'url': reverse('images_imageview', args=(image.id, )),
                                   # 'thumbnailUrl': reverse('images_imageview', args=(image.id, )),
                                   # 'deleteUrl': reverse('images_imagedeleteview', args=(image.id, )),
                                   # 'deleteType': "DELETE",
                                   })
            else:
                json_files.append({'name': f.name,
                                   'size': f.size,
                                   'error': errormessage,
                                   })

        return JsonResponse({'files': json_files})
Пример #28
0
def requirement_new_link(request,
                         requirement_id,
                         location_id='',
                         destination=''):
    permission_results = return_user_permission_level(request, None,
                                                      'requirement_link')

    if permission_results['requirement_link'] < 2:
        return HttpResponseRedirect(reverse('permission_denied'))

    if request.method == "POST":
        print("Requirement ID: " + requirement_id + "\nLocation ID: " +
              location_id + "\nTask or Project: " + destination)
        #Check to make sure that there exists a location id and project_or_task value
        if location_id == '' or destination == '':
            #Well - this is not good for POST
            print("Please check the URL")
            return HttpResponseBadRequest(
                "Please note, both location_id and project_or_task will need to be filled out."
            )

        print("Trying to save")
        requirement_link_save = requirement_link(
            requirement=requirement.objects.get(requirement_id=requirement_id),
            change_user=request.user,
        )

        if destination == "project":
            project_instance = project.objects.get(project_id=location_id)
            requirement_link_save.project_id = project_instance
        elif destination == "task":
            task_instance = task.objects.get(tasks_id=location_id)
            requirement_link_save.task_id = task_instance
        elif destination == "organisation":
            organisation_instance = organisation.objects.get(
                organisation_id=location_id)
            requirement_link_save.organisation_id = organisation_instance
        else:
            return HttpResponseBadRequest(
                "You can only choose: project, task, or organisation")

        requirement_link_save.save()

        #Return blank page\
        # Load template
        t = loader.get_template('NearBeach/blank.html')

        # context
        c = {}

        return HttpResponse(t.render(c, request))
    """
    The linked requirement will only link to requirement the user has access to. Nothing else.
    """
    cursor = connection.cursor()

    cursor.execute(
        """
        SELECT DISTINCT 
          project.project_id
        , project.project_name



        from 
          project left join project_task
            on project.project_id = project_task.project_id
            and project_task.is_deleted = 'FALSE'
        , project_group
        , user_group


        where 1 = 1
        and project.project_status IN ('New','Open')
        and project.project_status IN ('New','Open')
        and project.project_id = project_group.project_id_id
        and project_group.group_id_id = user_group.group_id
        and user_group.username_id = %s
        """, [request.user.id])
    project_results = namedtuplefetchall(cursor)

    cursor.execute(
        """
        select DISTINCT 
         task.tasks_id
        , task.task_short_description

        from 
          task 
        , tasks_group
        , user_group
        , organisation


        where 1 = 1
        and task.task_status in ('New','Open')
        and task.tasks_id = tasks_group.tasks_id_id
        and tasks_group.group_id_id = user_group.group_id
        and user_group.username_id = %s
        and task.organisation_id_id=organisation.organisation_id    
        """, [request.user.id])
    task_results = namedtuplefetchall(cursor)

    #Load template
    t = loader.get_template(
        'NearBeach/requirement_information/requirement_new_link.html')

    # context
    c = {
        'requirement_id': requirement_id,
        'project_results': project_results,
        'task_results': task_results,
    }

    return HttpResponse(t.render(c, request))
Пример #29
0
def donate(request):
    """Add a single donation item to the cart and proceed to payment.

    Warning: this call will clear all the items in the user's cart
    before adding the new item!

    Arguments:
        request (Request): The Django request object.  This should contain
            a JSON-serialized dictionary with "amount" (string, required),
            and "course_id" (slash-separated course ID string, optional).

    Returns:
        HttpResponse: 200 on success with JSON-encoded dictionary that has keys
            "payment_url" (string) and "payment_params" (dictionary).  The client
            should POST the payment params to the payment URL.
        HttpResponse: 400 invalid amount or course ID.
        HttpResponse: 404 donations are disabled.
        HttpResponse: 405 invalid request method.

    Example usage:

        POST /shoppingcart/donation/
        with params {'amount': '12.34', course_id': 'edX/DemoX/Demo_Course'}
        will respond with the signed purchase params
        that the client can send to the payment processor.

    """
    amount = request.POST.get('amount')
    course_id = request.POST.get('course_id')

    # Check that required parameters are present and valid
    if amount is None:
        msg = u"Request is missing required param 'amount'"
        log.error(msg)
        return HttpResponseBadRequest(msg)
    try:
        amount = (
            decimal.Decimal(amount)
        ).quantize(
            decimal.Decimal('.01'),
            rounding=decimal.ROUND_DOWN
        )
    except decimal.InvalidOperation:
        return HttpResponseBadRequest("Could not parse 'amount' as a decimal")

    # Any amount is okay as long as it's greater than 0
    # Since we've already quantized the amount to 0.01
    # and rounded down, we can check if it's less than 0.01
    if amount < decimal.Decimal('0.01'):
        return HttpResponseBadRequest("Amount must be greater than 0")

    if course_id is not None:
        try:
            course_id = CourseLocator.from_string(course_id)
        except InvalidKeyError:
            msg = u"Request included an invalid course key: {course_key}".format(course_key=course_id)
            log.error(msg)
            return HttpResponseBadRequest(msg)

    # Add the donation to the user's cart
    cart = Order.get_cart_for_user(request.user)
    cart.clear()

    try:
        # Course ID may be None if this is a donation to the entire organization
        Donation.add_to_order(cart, amount, course_id=course_id)
    except InvalidCartItem as ex:
        log.exception((
            u"Could not create donation item for "
            u"amount '{amount}' and course ID '{course_id}'"
        ).format(amount=amount, course_id=course_id))
        return HttpResponseBadRequest(unicode(ex))

    # Start the purchase.
    # This will "lock" the purchase so the user can't change
    # the amount after we send the information to the payment processor.
    # If the user tries to make another donation, it will be added
    # to a new cart.
    cart.start_purchase()

    # Construct the response params (JSON-encoded)
    callback_url = request.build_absolute_uri(
        reverse("shoppingcart.views.postpay_callback")
    )

    response_params = json.dumps({
        # The HTTP end-point for the payment processor.
        "payment_url": get_purchase_endpoint(),

        # Parameters the client should send to the payment processor
        "payment_params": get_signed_purchase_params(
            cart,
            callback_url=callback_url,
            extra_data=([unicode(course_id)] if course_id else None)
        ),
    })

    return HttpResponse(response_params, content_type="text/json")
Пример #30
0
 def process_exception(self, request, exception):
     log.debug(f"{request}: {exception}")
     if isinstance(exception, ValueError):
         return HttpResponseBadRequest(content_type='application/json',
                                       content=json.dumps(
                                           {"error": str(exception)}))
Пример #31
0
def update(request):
    plan_id = request.POST["plan_id"]
    nonce = request.POST["nonce"]

    sub = Subscription.objects.for_user(request.user)
    # If plan_id has not changed then just update the payment method:
    if plan_id == sub.plan_id:
        if not sub.subscription_id:
            error = sub.setup(plan_id, nonce)
        else:
            error = sub.update_payment_method(nonce)

        if error:
            return log_and_bail(request, error)

        request.session["payment_method_status"] = "success"
        return redirect("hc-billing")

    if plan_id not in ("", "P20", "P80", "Y192", "Y768", "S5", "S48"):
        return HttpResponseBadRequest()

    # Cancel the previous plan and reset limits:
    sub.cancel()

    profile = request.user.profile
    profile.ping_log_limit = 100
    profile.check_limit = 20
    profile.team_limit = 2
    profile.sms_limit = 5
    profile.call_limit = 0
    profile.save()

    if plan_id == "":
        request.session["set_plan_status"] = "success"
        return redirect("hc-billing")

    error = sub.setup(plan_id, nonce)
    if error:
        return log_and_bail(request, error)

    # Update user's profile
    profile = request.user.profile
    if plan_id in ("S5", "S48"):
        profile.check_limit = 20
        profile.team_limit = 2
        profile.ping_log_limit = 1000
        profile.sms_limit = 5
        profile.sms_sent = 0
        profile.call_limit = 5
        profile.calls_sent = 0
        profile.save()
    elif plan_id in ("P20", "Y192"):
        profile.check_limit = 100
        profile.team_limit = 9
        profile.ping_log_limit = 1000
        profile.sms_limit = 50
        profile.sms_sent = 0
        profile.call_limit = 20
        profile.calls_sent = 0
        profile.save()
    elif plan_id in ("P80", "Y768"):
        profile.check_limit = 1000
        profile.team_limit = 500
        profile.ping_log_limit = 1000
        profile.sms_limit = 500
        profile.sms_sent = 0
        profile.call_limit = 100
        profile.calls_sent = 0
        profile.save()

    request.session["set_plan_status"] = "success"
    return redirect("hc-billing")
Пример #32
0
    def post(self, request, course_id):
        """Takes the form submission from the page and parses it.

        Args:
            request (`Request`): The Django Request object.
            course_id (unicode): The slash-separated course key.

        Returns:
            Status code 400 when the requested mode is unsupported. When the honor mode
            is selected, redirects to the dashboard. When the verified mode is selected,
            returns error messages if the indicated contribution amount is invalid or
            below the minimum, otherwise redirects to the verification flow.

        """
        course_key = CourseKey.from_string(course_id)
        user = request.user

        # This is a bit redundant with logic in student.views.change_enrollment,
        # but I don't really have the time to refactor it more nicely and test.
        course = modulestore().get_course(course_key)
        if not user.has_perm(ENROLL_IN_COURSE, course):
            error_msg = _("Enrollment is closed")
            return self.get(request, course_id, error=error_msg)

        requested_mode = self._get_requested_mode(request.POST)

        allowed_modes = CourseMode.modes_for_course_dict(course_key)
        if requested_mode not in allowed_modes:
            return HttpResponseBadRequest(_("Enrollment mode not supported"))

        if requested_mode == 'audit':
            # If the learner has arrived at this screen via the traditional enrollment workflow,
            # then they should already be enrolled in an audit mode for the course, assuming one has
            # been configured.  However, alternative enrollment workflows have been introduced into the
            # system, such as third-party discovery.  These workflows result in learners arriving
            # directly at this screen, and they will not necessarily be pre-enrolled in the audit mode.
            CourseEnrollment.enroll(request.user, course_key, CourseMode.AUDIT)
            # If the course has started redirect to course home instead
            if course.has_started():
                return redirect(
                    reverse('openedx.course_experience.course_home',
                            kwargs={'course_id': course_key}))
            return redirect(reverse('dashboard'))

        if requested_mode == 'honor':
            CourseEnrollment.enroll(user, course_key, mode=requested_mode)
            # If the course has started redirect to course home instead
            if course.has_started():
                return redirect(
                    reverse('openedx.course_experience.course_home',
                            kwargs={'course_id': course_key}))
            return redirect(reverse('dashboard'))

        mode_info = allowed_modes[requested_mode]

        if requested_mode == 'verified':
            amount = request.POST.get("contribution") or \
                request.POST.get("contribution-other-amt") or 0

            try:
                # Validate the amount passed in and force it into two digits
                amount_value = decimal.Decimal(amount).quantize(
                    decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)
            except decimal.InvalidOperation:
                error_msg = _("Invalid amount selected.")
                return self.get(request, course_id, error=error_msg)

            # Check for minimum pricing
            if amount_value < mode_info.min_price:
                error_msg = _(
                    "No selected price or selected price is too low.")
                return self.get(request, course_id, error=error_msg)

            donation_for_course = request.session.get("donation_for_course",
                                                      {})
            donation_for_course[six.text_type(course_key)] = amount_value
            request.session["donation_for_course"] = donation_for_course

            return redirect(
                reverse('verify_student_start_flow',
                        kwargs={'course_id': six.text_type(course_key)}))
Пример #33
0
def multiple_emails_failed_response(failed_recipients):

    response = HttpResponseBadRequest()
    response.write('<p>The mail was not sent to all the recipients.' +
                   ' Please check your request and try again.</p>')
    response.write('<br/><p>The following recipients did not receive' +
                   ' the mail:</p>')
    response.write('<ul>')
    for email in failed_recipients:
        response.write('<li>'+email+'</li>')
    response.write('</ul>')
    return response
Пример #34
0
    def _upload_file(self, request):
        """
        Upload file to the server.
        """
        if request.method == "POST":
            folder = request.GET.get('folder', '')

            if len(request.FILES) == 0:
                return HttpResponseBadRequest(
                    'Invalid request! No files included.')
            if len(request.FILES) > 1:
                return HttpResponseBadRequest(
                    'Invalid request! Multiple files included.')

            filedata = list(request.FILES.values())[0]

            fb_uploadurl_re = re.compile(
                r'^.*(%s)' %
                reverse("filebrowser:fb_upload", current_app=self.name))
            folder = fb_uploadurl_re.sub('', folder)

            path = os.path.join(self.directory, folder)
            # we convert the filename before uploading in order
            # to check for existing files/folders
            file_name = convert_filename(filedata.name)
            filedata.name = file_name
            file_path = os.path.join(path, file_name)
            file_already_exists = self.storage.exists(file_path)
            # Check for name collision with a directory
            if file_already_exists and self.storage.isdir(file_path):
                ret_json = {'success': False, 'filename': file_name}
                return HttpResponse(json.dumps(ret_json))

            signals.filebrowser_pre_upload.send(sender=request,
                                                path=folder,
                                                file=filedata,
                                                site=self)
            uploadedfile = handle_file_upload(path, filedata, site=self)
            local_storage = True
            if file_already_exists and OVERWRITE_EXISTING:
                old_file = smart_text(file_path)
                new_file = smart_text(uploadedfile)
                self.storage.move(new_file, old_file, allow_overwrite=True)
                try:
                    full_path = FileObject(smart_text(old_file),
                                           site=self).path_full
                except NotImplementedError:
                    local_storage = False
            else:
                file_name = smart_text(uploadedfile)
                filedata.name = os.path.relpath(file_name, path)
                try:
                    full_path = FileObject(smart_text(file_name),
                                           site=self).path_full
                except NotImplementedError:
                    local_storage = False

            # set permissions
            if local_storage and DEFAULT_PERMISSIONS is not None:
                os.chmod(full_path, DEFAULT_PERMISSIONS)

            f = FileObject(smart_text(file_name), site=self)
            signals.filebrowser_post_upload.send(sender=request,
                                                 path=folder,
                                                 file=f,
                                                 site=self)

            # let Ajax Upload know whether we saved it or not
            ret_json = {'success': True, 'filename': f.filename}
            return HttpResponse(json.dumps(ret_json),
                                content_type="application/json")
Пример #35
0
def batch_edit_translations(request):
    """Perform an action on a list of translations.

    Available actions are defined in `ACTIONS_FN_MAP`. Arguments to this view
    are defined in `models.BatchActionsForm`.

    """
    form = forms.BatchActionsForm(request.POST)
    if not form.is_valid():
        return HttpResponseBadRequest(form.errors.as_json())

    locale = get_object_or_404(Locale, code=form.cleaned_data['locale'])

    entities = (
        Entity.objects
        .filter(pk__in=form.cleaned_data['entities'])
        .prefetch_translations(locale)
    )

    if not entities.exists():
        return JsonResponse({'count': 0})

    # Batch editing is only available to translators. Check if user has
    # translate permissions for all of the projects in passed entities.
    # Also make sure projects are not enabled in read-only mode for a locale.
    projects_pk = entities.values_list('resource__project__pk', flat=True)
    projects = Project.objects.filter(pk__in=projects_pk.distinct())

    for project in projects:
        if (
            not request.user.can_translate(project=project, locale=locale)
            or readonly_exists(projects, locale)
        ):
            return HttpResponseForbidden(
                "Forbidden: You don't have permission for batch editing"
            )

    active_translation_pks = set()

    # Find all impacted active translations, including plural forms.
    for entity in entities:
        if entity.string_plural == "":
            active_translation_pks.add(entity.get_translation()['pk'])
        else:
            for plural_form in range(0, locale.nplurals or 1):
                active_translation_pks.add(
                    entity.get_translation(plural_form)['pk']
                )

    active_translation_pks.discard(None)

    active_translations = (
        Translation.objects
        .filter(pk__in=active_translation_pks)
    )

    # Execute the actual action.
    action_function = ACTIONS_FN_MAP[form.cleaned_data['action']]
    action_status = action_function(
        form,
        request.user,
        active_translations,
        locale,
    )

    if action_status.get('error'):
        return JsonResponse(action_status)

    if action_status['count'] == 0:
        return JsonResponse({'count': 0})

    update_stats(action_status['translated_resources'], entity, locale)
    mark_changed_translation(action_status['changed_entities'], locale)

    # Update latest translation.
    if action_status['latest_translation_pk']:
        Translation.objects.get(
            pk=action_status['latest_translation_pk']
        ).update_latest_translation()

    update_translation_memory(
        action_status['changed_translation_pks'],
        project,
        locale
    )

    return JsonResponse({
        'count': action_status['count']
    })
Пример #36
0
 def wrap(request, *args, **kwargs):
     if not request.is_ajax():
         return HttpResponseBadRequest("Bad Request: Request must be AJAX")
     return f(request, *args, **kwargs)
Пример #37
0
def handler400(request):
    response = HttpResponseBadRequest()
    context = RequestContext(request)
    response.content = render_to_string('400.html', context_instance=context)
    return response
Пример #38
0
 def __init__(self, request, msg):
   HttpResponseBadRequest.__init__(self, '<h1>400 Bad Request</h1><p>%s</p>'%msg)