Exemplo n.º 1
0
    def process_view(self, request, view_func, view_args, view_kwargs):
        if settings.DEBUG_SECURE:
            return
            
        secure_request = request.is_secure()
        secure_view = isinstance(view_func, SecureView)
        
        # If the non-secure session is marked secure, refuse the request.
        # Likewise, if the secure session isn't marked secure, refuse the
        # request and delete the cookie.
        if request.session.get('is_secure'):
            return HttpResponseForbidden('Invalid session_id', mimetype='text/plain')
        if request.secure_session and not request.secure_session.get('is_secure'):
            resp = HttpResponseForbidden('Invalid secure_session_id', mimetype='text/plain')
            resp.delete_cookie('secure_session_id')
            return resp

        if secure_view and not secure_request:
            uri = request.build_absolute_uri().split(':', 1)
            uri = 'https:' + uri[1]
            return view_func.redirect(uri, request, 'secure')
        if not secure_view and secure_request:
            uri = request.build_absolute_uri().split(':', 1)
            uri = 'http:' + uri[1]
            if uri == 'http://%s/' % request.META.get('HTTP_HOST', ''):
                uri += '?preview=true'
            
            if isinstance(view_func, BaseView):
                return view_func.redirect(uri, request, 'secure')
            else:
                return HttpResponsePermanentRedirect(uri)
Exemplo n.º 2
0
def submit_vote(request):
  authenticate(request, VALID_FACTORS)
  admin = ('admin' == authenticate(request, VALID_FACTORS))
  
  if request.method != 'POST':
    raise Http404
  
  fp = get_fp()
  
  if not check_status(fp,DURING_V) and not admin:
    return HttpResponse403()
  
  d = request.POST
  query = d.copy()
  
  voter = request.user
  
  try:
    FundingPollVote.objects.save_fp_data_list(FundingPollOrganization, fp, voter, query)
  except IntegrityError:
    if not admin:
      r = HttpResponseForbidden()
      r.write('<p>Error, you may not vote twice in fundingpoll.</p>')
      return r
  
  return render_to_response('fundingpoll/voting_success.html', context_instance=RequestContext(request))
Exemplo n.º 3
0
 def wrapper(self, request, *args, **kwargs):
     user = request.user
     if user:
         if isinstance(user, Account):
             return func(self, request, *args, **kwargs)
     response = HttpResponseForbidden('403 Forbidden')
     # Added back bit required by django-piston
     response._is_string = True
     return response
Exemplo n.º 4
0
	def put(self, args):
		plan = Plan()

		if not self.request.user.is_authenticated():
			if not 'captcha-id' in args:
				return HttpResponseBadRequest('Weird')
			if not 'captcha-value' in args:
				return HttpResponseBadRequest('Please enter a value')

			captcha_id = args['captcha-id']
			captcha_value = args['captcha-value']

			if not captcha_value.isdigit():
				return HttpResponseBadRequest('Please enter a number')

			captcha_value = int(captcha_value)
			answer = CaptchaRequest.validate(captcha_id, captcha_value)

			if answer != CAPTCHA_ANSWER_OK:
				captcha = generate_sum_captcha()
				response = HttpResponseForbidden('Wrong answer')
				response['location'] = captcha.uid
				return response

		if 'title' in args:
			plan.title = args['title']
		if 'instructions' in args:
			plan.instructions = args['instructions']
		if 'expires' in args:
			expires = args['expires']
			if not isinstance(expires, int):
				if expires.isdigit():
					expires = int(expires)
				else:
					return HttpResponseBadRequest()
			expires = min(max(expires,1),6)
		else:
			expires = 1

		today = datetime.date.today()
		delta = relativedelta(months=+expires)
		plan.expires = today + delta

		plan.save()
		response = HttpResponseCreated('/rpc/%s' % plan.hash)

		data = {
			'id': plan.hash,
			'title': plan.title,
			'instructions': plan.instructions,
			'expires': str(plan.expires),
		}
		response.content = simplejson.dumps(data)
		response['Content-type'] = 'application/json'
		return response
Exemplo n.º 5
0
def Forbidden(msg):
    error = {
            'success': False,
            'data': {
                'code': 403,
                'message': msg
            }
        }
    resp = HttpResponseForbidden()
    resp.content = json.dumps(error)
    return resp
Exemplo n.º 6
0
 def process_exception(self, request, exception):
     if isinstance(exception, BearerTokenError):
         response = HttpResponseForbidden()
         auth_fields = [
             'error="{}"'.format(exception.code),
             'error_description="{}"'.format(exception.description)
         ]
         if 'scope' in request.POST:
             auth_fields = ['Bearer realm="{}"'.format(request.POST['scope'])] + auth_fields
         response.__setitem__('WWW-Authenticate', ', '.join(auth_fields))
         return response
Exemplo n.º 7
0
def srt(request, id, layer, index=None):
    item = get_object_or_404(models.Item, itemId=id)
    if not item.access(request.user):
        response = HttpResponseForbidden()
    else:
        response = HttpResponse()
        filename = u"%s.srt" % item.get('title')
        response['Content-Disposition'] = "attachment; filename*=UTF-8''%s" % quote(filename.encode('utf-8'))
        response['Content-Type'] = 'text/x-srt'
        response.write(item.srt(layer))
    return response
Exemplo n.º 8
0
def register_metaman(request):
    '''
    view function to handle the MetaMan file upload
    '''

    if request.method == 'POST':
        form = RegisterMetamanForm(request.POST, request.FILES)

        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            epn = form.cleaned_data['epn']

            logger.info('=== ingestion request for epn %s' % epn)

            user = authenticate(username=username, password=password)
            if user is None:
                logger.debug('authorisation failed')
                response = HttpResponseForbidden()
                response.write('authorization failed')
                return response
            elif user.is_active is False:
                logger.debug('user account %s is inactive' % user.username)
                response = HttpResponseForbidden()
                response.write('authorization failed')
                return response
            else:
                login(request, user)

                try:
                    logger.info('calling _parse_metaman for epn %s' % epn)
                    expid = _parse_metaman(request, form.cleaned_data)
                    logger.info('_parse_metaman SUCCESS,'
                                ' experiment id = %i' % expid)
                except:
                    logger.exception('exception')
                    logger.error('=== ingesting for epn %s FAILED' % epn)
                    return HttpResponseServerError()

                logger.info('=== ingestion FINISHED for epn %s' % epn)
                logout(request)

                return HttpResponse(str(expid))

        c = Context({'form': form,
                     'error': True,
                     'header': 'Register Metaman File'})
        render_to_response('tardis_portal/form_template.html', c)

    else:
        form = RegisterMetamanForm()

    c = Context({'form': form,
                 'header': 'Register Metaman File'})
    return render_to_response('tardis_portal/form_template.html', c)
Exemplo n.º 9
0
def get_upload_params(request):
    """Authorises user and validates given file properties."""
    file_name = request.POST['name']
    file_type = request.POST['type']
    file_size = int(request.POST['size'])
    key_args = request.POST.get('keyArgs')

    dest = get_s3direct_destinations().get(request.POST.get('dest', None),
                                           None)
    if not dest:
        resp = json.dumps({'error': 'File destination does not exist.'})
        return HttpResponseNotFound(resp, content_type='application/json')

    auth = dest.get('auth')
    if auth and not auth(request.user):
        resp = json.dumps({'error': 'Permission denied.'})
        return HttpResponseForbidden(resp, content_type='application/json')

    allowed = dest.get('allowed')
    if (allowed and file_type not in allowed) and allowed != '*':
        resp = json.dumps({'error': 'Invalid file type (%s).' % file_type})
        return HttpResponseBadRequest(resp, content_type='application/json')

    cl_range = dest.get('content_length_range')
    if (cl_range and not cl_range[0] <= file_size <= cl_range[1]):
        msg = 'Invalid file size (must be between %s and %s bytes).'
        resp = json.dumps({'error': (msg % cl_range)})
        return HttpResponseBadRequest(resp, content_type='application/json')

    key = dest.get('key')
    if not key:
        resp = json.dumps({'error': 'Missing destination path.'})
        return HttpResponseServerError(resp, content_type='application/json')

    if key_args:
        try:
            key_args = json.loads(key_args)
        except Exception:
            resp = json.dumps({
                'error':
                'Malformed key_args override defined on widget, make sure it\'s json serializable'
            })
            return HttpResponseServerError(resp,
                                           content_type='application/json')

    bucket = dest.get('bucket',
                      getattr(settings, 'AWS_STORAGE_BUCKET_NAME', None))
    if not bucket:
        resp = json.dumps({'error': 'S3 bucket config missing.'})
        return HttpResponseServerError(resp, content_type='application/json')

    region = dest.get('region', getattr(settings, 'AWS_S3_REGION_NAME', None))
    if not region:
        resp = json.dumps({'error': 'S3 region config missing.'})
        return HttpResponseServerError(resp, content_type='application/json')

    endpoint = dest.get('endpoint',
                        getattr(settings, 'AWS_S3_ENDPOINT_URL', None))
    if not endpoint:
        resp = json.dumps({'error': 'S3 endpoint config missing.'})
        return HttpResponseServerError(resp, content_type='application/json')

    aws_credentials = get_aws_credentials()
    if not aws_credentials.secret_key or not aws_credentials.access_key:
        resp = json.dumps({'error': 'AWS credentials config missing.'})
        return HttpResponseServerError(resp, content_type='application/json')

    upload_data = {
        'object_key':
        get_key(key, file_name, dest, key_args),
        'access_key_id':
        aws_credentials.access_key,
        'session_token':
        aws_credentials.token,
        'region':
        region,
        'bucket':
        bucket,
        'endpoint':
        endpoint,
        'acl':
        dest.get('acl') or 'public-read',
        'allow_existence_optimization':
        dest.get('allow_existence_optimization', False)
    }

    optional_params = [
        'content_disposition', 'cache_control', 'server_side_encryption'
    ]

    for optional_param in optional_params:
        if optional_param in dest:
            option = dest.get(optional_param)
            if hasattr(option, '__call__'):
                upload_data[optional_param] = option(file_name)
            else:
                upload_data[optional_param] = option

    resp = json.dumps(upload_data)
    return HttpResponse(resp, content_type='application/json')
Exemplo n.º 10
0
    def put(self, request, pk):
        try:
            odlc = find_odlc(request, int(pk))
        except Odlc.DoesNotExist:
            return HttpResponseNotFound('Odlc %s not found' % pk)
        except ValueError as e:
            return HttpResponseForbidden(str(e))

        try:
            data = json.loads(request.body)
        except ValueError:
            return HttpResponseBadRequest('Request body is not valid JSON.')

        # Must be a json dictionary.
        if not isinstance(data, dict):
            return HttpResponseBadRequest('Request body not a JSON dict.')

        # Cannot submit JSON with actionable_override if not superuser.
        if 'actionable_override' in data and not request.user.is_superuser:
            return HttpResponseForbidden(
                'Non-admin users cannot submit actionable override.')

        try:
            data = normalize_data(data)
        except ValueError as e:
            return HttpResponseBadRequest(str(e))

        # We update any of the included values, except id and user
        if 'type' in data:
            odlc.odlc_type = data['type']
        if 'orientation' in data:
            odlc.orientation = data['orientation']
        if 'shape' in data:
            odlc.shape = data['shape']
        if 'background_color' in data:
            odlc.background_color = data['background_color']
        if 'alphanumeric' in data:
            odlc.alphanumeric = data['alphanumeric']
        if 'alphanumeric_color' in data:
            odlc.alphanumeric_color = data['alphanumeric_color']
        if 'description' in data:
            odlc.description = data['description']
        if 'autonomous' in data:
            odlc.autonomous = data['autonomous']
        if 'actionable_override' in data:
            odlc.actionable_override = data['actionable_override']

        # Location is special because it is in a GpsPosition model

        # If lat/lon exist and are None, the user wants to clear them.
        # If they exist and are not None, the user wants to update/add them.
        # If they don't exist, the user wants to leave them alone.
        clear_lat = False
        clear_lon = False
        update_lat = False
        update_lon = False

        if 'latitude' in data:
            if data['latitude'] is None:
                clear_lat = True
            else:
                update_lat = True

        if 'longitude' in data:
            if data['longitude'] is None:
                clear_lon = True
            else:
                update_lon = True

        if (clear_lat and not clear_lon) or (not clear_lat and clear_lon):
            # Location must be cleared entirely, we can't clear just lat or
            # just lon.
            return HttpResponseBadRequest(
                'Only none or both of latitude and longitude can be cleared.')

        if clear_lat and clear_lon:
            odlc.location = None
        elif update_lat or update_lon:
            if odlc.location is not None:
                # We can directly update individual components
                if update_lat:
                    odlc.location.latitude = data['latitude']
                if update_lon:
                    odlc.location.longitude = data['longitude']
                odlc.location.save()
            else:
                # We need a new GpsPosition, this requires both lat and lon
                if not update_lat or not update_lon:
                    return HttpResponseBadRequest(
                        'Either none or both of latitude and longitude required.'
                    )

                l = GpsPosition(
                    latitude=data['latitude'], longitude=data['longitude'])
                l.save()
                odlc.location = l

        odlc.save()

        return JsonResponse(odlc.json(is_superuser=request.user.is_superuser))
Exemplo n.º 11
0
def problem_submit(request, problem=None, submission=None):
    if submission is not None and not request.user.has_perm('judge.resubmit_other') and \
                    get_object_or_404(Submission, id=int(submission)).user.user != request.user:
        raise PermissionDenied()

    profile = request.user.profile
    if request.method == 'POST':
        form = ProblemSubmitForm(request.POST, instance=Submission(user=profile))
        if form.is_valid():
            if (not request.user.has_perm('judge.spam_submission') and
                        Submission.objects.filter(user=profile, is_being_rejudged=False).exclude(
                            status__in=['D', 'IE', 'CE', 'AB']).count() > 2):
                return HttpResponse('<h1>You submitted too many submissions.</h1>', status=503)
            if not form.cleaned_data['problem'].allowed_languages.filter(
                    id=form.cleaned_data['language'].id).exists():
                raise PermissionDenied()
            if not form.cleaned_data['problem'].is_accessible_by(request.user):
                user_logger.info('Naughty user %s wants to submit to %s without permission',
                                 request.user.username, form.cleaned_data['problem'].code)
                return HttpResponseForbidden('<h1>Do you want me to ban you?</h1>')
            if not request.user.is_superuser and form.cleaned_data['problem'].banned_users.filter(
                    id=profile.id).exists():
                return generic_message(request, _('Banned from Submitting'),
                                       _('You have been declared persona non grata for this problem. '
                                         'You are permanently barred from submitting this problem.'))
            model = form.save()

            profile.update_contest()
            if profile.current_contest is not None:
                try:
                    contest_problem = model.problem.contests.get(contest=profile.current_contest.contest)
                except ContestProblem.DoesNotExist:
                    pass
                else:
                    contest = ContestSubmission(submission=model, problem=contest_problem,
                                                participation=profile.current_contest)
                    contest.save()

            model.judge()
            return HttpResponseRedirect(reverse('submission_status', args=[str(model.id)]))
        else:
            form_data = form.cleaned_data
    else:
        initial = {'language': profile.language}
        if problem is not None:
            initial['problem'] = get_object_or_404(Problem, code=problem)
            if not initial['problem'].is_accessible_by(request.user):
                raise Http404()
        if submission is not None:
            try:
                sub = get_object_or_404(Submission, id=int(submission))
                initial['source'] = sub.source
                initial['language'] = sub.language
            except ValueError:
                raise Http404()
        form = ProblemSubmitForm(initial=initial)
        form_data = initial
    if 'problem' in form_data:
        form.fields['language'].queryset = (form_data['problem'].usable_languages.order_by('name', 'key')
                                            .prefetch_related(
            Prefetch('runtimeversion_set', RuntimeVersion.objects.order_by('priority'))))
    if 'language' in form_data:
        form.fields['source'].widget.mode = form_data['language'].ace
    form.fields['source'].widget.theme = profile.ace_theme
    return render(request, 'problem/submit.jade', {
        'form': form,
        'title': _('Submit'),
        'langs': Language.objects.all(),
        'no_judges': not form.fields['language'].queryset,
        'ACE_URL': ACE_URL
    })
Exemplo n.º 12
0
 def post(self, request, *args, **kwargs):
     if request.user.is_authenticated and not request.user.is_staff:
         Resume.objects.create(author=request.user, description=request.POST["description"])
         return redirect('home/')
     return HttpResponseForbidden()
Exemplo n.º 13
0
 def http_response_forbidden(message, content_type):
     if django.VERSION[:2] > (1, 3):
         kwargs = {'content_type': content_type}
     else:
         kwargs = {'mimetype': content_type}
     return HttpResponseForbidden(message, **kwargs)
Exemplo n.º 14
0
def data_export(request, username, id_string, export_type):
    owner = get_object_or_404(User, username=username)
    xform = get_object_or_404(XForm, id_string=id_string, user=owner)
    helper_auth_helper(request)
    if not has_permission(xform, owner, request):
        return HttpResponseForbidden(_(u'Not shared.'))
    query = request.GET.get("query")
    extension = export_type

    # check if we should force xlsx
    force_xlsx = request.GET.get('xls') != 'true'
    if export_type == Export.XLS_EXPORT and force_xlsx:
        extension = 'xlsx'
    elif export_type in [Export.CSV_ZIP_EXPORT, Export.SAV_ZIP_EXPORT]:
        extension = 'zip'

    audit = {
        "xform": xform.id_string,
        "export_type": export_type
    }
    # check if we need to re-generate,
    # we always re-generate if a filter is specified
    if should_create_new_export(xform, export_type) or query or\
            'start' in request.GET or 'end' in request.GET:
        format_date_for_mongo = lambda x, datetime: datetime.strptime(
            x, '%y_%m_%d_%H_%M_%S').strftime('%Y-%m-%dT%H:%M:%S')
        # check for start and end params
        if 'start' in request.GET or 'end' in request.GET:
            if not query:
                query = '{}'
            query = json.loads(query)
            query[SUBMISSION_TIME] = {}
            try:
                if request.GET.get('start'):
                    query[SUBMISSION_TIME]['$gte'] = format_date_for_mongo(
                        request.GET['start'], datetime)
                if request.GET.get('end'):
                    query[SUBMISSION_TIME]['$lte'] = format_date_for_mongo(
                        request.GET['end'], datetime)
            except ValueError:
                return HttpResponseBadRequest(
                    _("Dates must be in the format YY_MM_DD_hh_mm_ss"))
            else:
                query = json.dumps(query)
        try:
            export = generate_export(
                export_type, extension, username, id_string, None, query)
            audit_log(
                Actions.EXPORT_CREATED, request.user, owner,
                _("Created %(export_type)s export on '%(id_string)s'.") %
                {
                    'id_string': xform.id_string,
                    'export_type': export_type.upper()
                }, audit, request)
        except NoRecordsFoundError:
            return HttpResponseNotFound(_("No records found to export"))
    else:
        export = newset_export_for(xform, export_type)

    # log download as well
    audit_log(
        Actions.EXPORT_DOWNLOADED, request.user, owner,
        _("Downloaded %(export_type)s export on '%(id_string)s'.") %
        {
            'id_string': xform.id_string,
            'export_type': export_type.upper()
        }, audit, request)

    if not export.filename:
        # tends to happen when using newset_export_for.
        return HttpResponseNotFound("File does not exist!")
    # get extension from file_path, exporter could modify to
    # xlsx if it exceeds limits
    path, ext = os.path.splitext(export.filename)
    ext = ext[1:]
    if request.GET.get('raw'):
        id_string = None
    response = response_with_mimetype_and_name(
        Export.EXPORT_MIMES[ext], id_string, extension=ext,
        file_path=export.filepath)
    return response
Exemplo n.º 15
0
def finish_authorize(request: HttpRequest) -> HttpResponse:
    """
    Set parameter secret to something valid.

    The external service redirects here after _we_ redirect to _it_ in
    start_authorize(). We cannot include pk in the URL (since the external
    service -- e.g., Google -- requires a fixed URL), so we store the pk in
    the session.
    """
    try:
        flow = request.session['oauth-flow']
    except KeyError:
        return HttpResponseForbidden(
            'Missing auth session. Please try connecting again.')

    try:
        scope = Scope(**flow)
    except TypeError:
        # This would _normally_ be a crash-worthy exception. But there might
        # be sessions in progress as we deploy, [2018-12-21]. TODO nix this
        # `except` to keep our code clean.
        logger.exception('Malformed auth session. Data: %r', flow)
        return HttpResponseForbidden(
            'Malformed auth session. Please try connecting again.')

    service = oauth.OAuthService.lookup_or_none(scope.service_id)
    if not service:
        return HttpResponseNotFound('Service not configured')

    offline_token = service.acquire_refresh_token_or_str_error(
        request.GET, scope.state)
    if isinstance(offline_token, str):
        return HttpResponseForbidden(offline_token)

    username = service.extract_username_from_token(offline_token)

    try:
        with Workflow.authorized_lookup_and_cooperative_lock(
                'owner',  # only owner can modify params
                request.user,
                request.session,
                pk=scope.workflow_id) as workflow:
            # raises WfModule.DoesNotExist, ModuleVersion.DoesNotExist
            wf_module, _ = _load_wf_module_and_service(workflow,
                                                       scope.wf_module_id,
                                                       scope.param)
            wf_module.secrets = {
                **wf_module.secrets, scope.param: {
                    'name': username,
                    'secret': offline_token,
                }
            }
            wf_module.save(update_fields=['secrets'])

            delta_json = {
                'updateWfModules': {
                    str(wf_module.id): {
                        'secrets': wf_module.secret_metadata,
                    }
                }
            }
    except Workflow.DoesNotExist as err:
        # Possibilities:
        # str(err) = 'owner access denied'
        # str(err) = 'Workflow matching query does not exist'
        return HttpResponseForbidden(str(err))
    except (ModuleVersion.DoesNotExist, WfModule.DoesNotExist):
        return HttpResponseNotFound('Step or parameter was deleted.')

    async_to_sync(websockets.ws_client_send_delta_async)(workflow.id,
                                                         delta_json)
    response = HttpResponse(
        b"""<!DOCTYPE html>
            <html lang="en-US">
                <head>
                    <title>Authorized</title>
                </head>
                <body>
                    <p class="success">
                        You have logged in. You may close this window now.
                    </p>
                </body>
            </html>
        """,
        content_type='text/html; charset=utf-8',
    )
    response['Cache-Control'] = 'no-cache'
    return response
Exemplo n.º 16
0
def stats(request):
    if not request.user.is_superuser:
        return HttpResponseForbidden()
    before = request.GET.get('before', timezone.now())
    after = request.GET.get('after', timezone.now() - timedelta(days=1))
    period = request.GET.get('period', 'day')
    is_csv = (request.GET.get('csv', False) == 'true')

    def toWeek(dt):
        sunday = dt.strftime('%Y-%U-0')
        return datetime.strptime(sunday, '%Y-%U-%w').strftime('%Y-%m-%d')

    def toDay(dt):
        return dt.strftime('%Y-%m-%d')

    def toMonth(dt):
        return dt.strftime('%Y-%m')

    if period == 'day':
        period_fn = toDay
    elif period == 'week':
        period_fn = toWeek
    elif period == 'month':
        period_fn = toMonth

    users = User.objects.only('date_joined').filter(
        date_joined__gte=after,
        date_joined__lte=before).order_by('-date_joined')

    grouped_users_by_period = {}
    for gu in itertools.groupby(users, lambda u: period_fn(u.date_joined)):
        grouped_users_by_period[gu[0]] = len(list(gu[1]))

    queryset = Job.objects.only('created_at',
                                'the_geom').order_by('-created_at')
    if before:
        queryset = queryset.filter(Q(created_at__lte=before))
    if after:
        queryset = queryset.filter(Q(created_at__gte=after))

    grouped_jobs = itertools.groupby(queryset,
                                     lambda j: period_fn(j.created_at))

    geoms = []
    periods = []
    for x in grouped_jobs:
        top_regions = Counter()
        jobs_in_group = list(x[1])
        for j in jobs_in_group:
            centroid = j.the_geom.centroid
            geoms.append([centroid.x, centroid.y])
            result = next(
                idx.nearest((centroid.x, centroid.y), 1, objects=True))
            top_regions[result.object[2]] += 1

        users_in_period = grouped_users_by_period.get(x[0], 0)

        top_regions_string = ' '.join(
            ["{0}:{1}".format(x[0], x[1]) for x in top_regions.most_common(5)])
        periods.append({
            'start_date': x[0],
            'jobs_count': len(jobs_in_group),
            'users_count': users_in_period,
            'top_regions': top_regions_string
        })

    if is_csv:
        output = io.StringIO()
        writer = csv.writer(output)
        writer.writerow(
            ['start_date', 'jobs_count', 'users_count', 'top_regions'])
        for period in periods:
            writer.writerow([
                period['start_date'], period['jobs_count'],
                period['users_count'], period['top_regions']
            ])
        return HttpResponse(output.getvalue())
    else:
        return HttpResponse(json.dumps({'periods': periods, 'geoms': geoms}))
Exemplo n.º 17
0
    def move_plugin(self, request):
        """
        Performs a move or a "paste" operation (when «move_a_copy» is set)

        POST request with following parameters:
        - plugin_id
        - placeholder_id
        - plugin_language (optional)
        - plugin_parent (optional)
        - plugin_order (array, optional)
        - move_a_copy (Boolean, optional) (anything supplied here except a case-
                                        insensitive "false" is True)
        NOTE: If move_a_copy is set, the plugin_order should contain an item
              '__COPY__' with the desired destination of the copied plugin.
        """
        # plugin_id and placeholder_id are required, so, if nothing is supplied,
        # an ValueError exception will be raised by get_int().
        try:
            plugin_id = get_int(request.POST.get('plugin_id'))
        except TypeError:
            raise RuntimeError("'plugin_id' is a required parameter.")
        plugin = CMSPlugin.objects.get(pk=plugin_id)
        try:
            placeholder_id = get_int(request.POST.get('placeholder_id'))
        except TypeError:
            raise RuntimeError("'placeholder_id' is a required parameter.")
        except ValueError:
            raise RuntimeError("'placeholder_id' must be an integer string.")
        placeholder = Placeholder.objects.get(pk=placeholder_id)
        # The rest are optional
        parent_id = get_int(request.POST.get('plugin_parent', ""), None)
        language = request.POST.get('plugin_language', None)
        move_a_copy = request.POST.get('move_a_copy', False)
        move_a_copy = (move_a_copy and move_a_copy != "0" and
                       move_a_copy.lower() != "false")

        source_placeholder = plugin.placeholder
        if not language and plugin.language:
            language = plugin.language
        order = request.POST.getlist("plugin_order[]")

        if not self.has_move_plugin_permission(request, plugin, placeholder):
            return HttpResponseForbidden(
                force_text(_("You have no permission to move this plugin")))
        if placeholder != source_placeholder:
            try:
                template = self.get_placeholder_template(request, placeholder)
                has_reached_plugin_limit(placeholder, plugin.plugin_type,
                                         plugin.language, template=template)
            except PluginLimitReached as er:
                return HttpResponseBadRequest(er)

        if move_a_copy:  # "paste"
            if plugin.plugin_type == "PlaceholderPlugin":
                parent_id = None
                inst = plugin.get_plugin_instance()[0]
                plugins = inst.placeholder_ref.get_plugins()
            else:
                plugins = [plugin] + list(plugin.get_descendants())

            new_plugins = copy_plugins.copy_plugins_to(
                plugins,
                placeholder,
                language,
                parent_plugin_id=parent_id,
            )

            top_plugins = []
            top_parent = new_plugins[0][0].parent_id
            for new_plugin, old_plugin in new_plugins:
                if new_plugin.parent_id == top_parent:
                    # NOTE: There is no need to save() the plugins here.
                    new_plugin.position = old_plugin.position
                    top_plugins.append(new_plugin)

            # Creates a list of string PKs of the top-level plugins ordered by
            # their position.
            top_plugins_pks = [str(p.pk) for p in sorted(
                top_plugins, key=lambda x: x.position)]

            if parent_id:
                parent = CMSPlugin.objects.get(pk=parent_id)

                for plugin in top_plugins:
                    plugin.parent = parent
                    plugin.placeholder = placeholder
                    plugin.language = language
                    plugin.save()

            # If an ordering was supplied, we should replace the item that has
            # been copied with the new copy
            if order:
                if '__COPY__' in order:
                    copy_idx = order.index('__COPY__')
                    del order[copy_idx]
                    order[copy_idx:0] = top_plugins_pks
                else:
                    order.extend(top_plugins_pks)

            # Set the plugin variable to point to the newly created plugin.
            plugin = new_plugins[0][0]
        else:
            # Regular move
            if parent_id:
                if plugin.parent_id != parent_id:
                    parent = CMSPlugin.objects.get(pk=parent_id)
                    if parent.placeholder_id != placeholder.pk:
                        return HttpResponseBadRequest(force_text(
                            _('parent must be in the same placeholder')))
                    if parent.language != language:
                        return HttpResponseBadRequest(force_text(
                            _('parent must be in the same language as '
                              'plugin_language')))
                    plugin.parent_id = parent.pk
                    plugin.language = language
                    plugin.save()
                    plugin = plugin.move(parent, pos='last-child')
            else:
                sibling = CMSPlugin.get_last_root_node()
                plugin.parent = plugin.parent_id = None
                plugin.placeholder = placeholder
                plugin.save()
                plugin = plugin.move(sibling, pos='right')

            plugins = [plugin] + list(plugin.get_descendants())

            # Don't neglect the children
            for child in plugins:
                child.placeholder = placeholder
                child.language = language
                child.save()

        reorder_plugins(placeholder, parent_id, language, order)

        # When this is executed we are in the admin class of the source placeholder
        # It can be a page or a model with a placeholder field.
        # Because of this we need to get the admin class instance of the
        # target placeholder and call post_move_plugin() on it.
        # By doing this we make sure that both the source and target are
        # informed of the operation.
        target_placeholder_admin = self._get_attached_admin(placeholder)

        if move_a_copy:  # "paste"
            self.post_copy_plugins(request, source_placeholder, placeholder, plugins)

            if (target_placeholder_admin and
                    target_placeholder_admin.model != self.model):
                target_placeholder_admin.post_copy_plugins(
                    request,
                    source_placeholder=source_placeholder,
                    target_placeholder=placeholder,
                    plugins=plugins,
                )
        else:
            self.post_move_plugin(request, source_placeholder, placeholder, plugin)

            if (target_placeholder_admin and
                    target_placeholder_admin.model != self.model):
                target_placeholder_admin.post_move_plugin(
                    request,
                    source_placeholder=source_placeholder,
                    target_placeholder=placeholder,
                    plugin=plugin,
                )

        try:
            language = request.toolbar.toolbar_language
        except AttributeError:
            language = get_language_from_request(request)

        with force_language(language):
            plugin_urls = plugin.get_action_urls()

        json_response = {
            'urls': plugin_urls,
            'reload': move_a_copy or requires_reload(
                PLUGIN_MOVE_ACTION, [plugin])
        }
        return HttpResponse(
            json.dumps(json_response), content_type='application/json')
Exemplo n.º 18
0
 def __init__(self):
   HttpResponseForbidden.__init__(self)
   self.write(render_to_string('errors/http_forbidden.phtml'))
Exemplo n.º 19
0
 def get(self, request, rcon_server_port, rcon_cmd):
     if not request.user.is_staff or not request.user.is_superuser or not request.user.is_authenticated:
         return HttpResponseForbidden()
     context = {}
     context = run_rcon_cmd(rcon_server_port, rcon_cmd)
     return render(request, 'remote_admin/rcon_cmd.html', context)
Exemplo n.º 20
0
 def dispatch(self, request, *args, **kwargs):
     if self.permission is None or request.user.has_perm(self.permission):
         return super(Submit, self).dispatch(request, *args, **kwargs)
     else:
         return HttpResponseForbidden()
Exemplo n.º 21
0
 def test_bad_guard(self):
     settings.STATSD_RECORD_GUARD = lambda r: HttpResponseForbidden()
     assert self.client.get(self.url, self.good).status_code == 403
Exemplo n.º 22
0
def admin_question(request, pid):
    if not request.user.is_authenticated():
        return HttpResponseForbidden()
    p = get_object_or_404(Poll, id=pid)
    context = {'poll': p, 'pid': pid, "errors": []}
    return render(request, 'poll/admin/results.html', context)
Exemplo n.º 23
0
 def __init__(self, request, msg):
   HttpResponseForbidden.__init__(self,'<h1>403 Forbidden</h1><p>%s</p>'%msg)
Exemplo n.º 24
0
def profile(request):
    profile = request.user.profile
    # Switch user back to its default team
    if profile.current_team_id != profile.id:
        request.team = profile
        profile.current_team_id = profile.id
        profile.save()

    show_api_key = False
    if request.method == "POST":
        if "set_password" in request.POST:
            profile.send_set_password_link()
            return redirect("hc-set-password-link-sent")
        elif "create_api_key" in request.POST:
            profile.set_api_key()
            show_api_key = True
            messages.success(request, "The API key has been created!")
        elif "revoke_api_key" in request.POST:
            profile.api_key = ""
            profile.save()
            messages.info(request, "The API key has been revoked!")
        elif "show_api_key" in request.POST:
            show_api_key = True
        elif "update_reports_allowed" in request.POST:
            form = ReportSettingsForm(request.POST)
            if form.is_valid():
                profile.reports_allowed = form.cleaned_data["reports_allowed"]
                profile.save()
                messages.success(request, "Your settings have been updated!")

        elif "update_weekly_reports_allowed" in request.POST:
            form = WeeklyReportsForm(request.POST)
            if form.is_valid():
                profile.weekly_reports_allowed = form.cleaned_data[
                    "weekly_reports_allowed"]
                profile.save()
                messages.success(request, "Your settings have been updated")

        elif "update_daily_reports_allowed" in request.POST:
            form = DailyReportSettingsForm(request.POST)
            if form.is_valid():
                profile.daily_reports_allowed = form.cleaned_data[
                    "daily_reports_allowed"]
                profile.save()
                messages.success(request, "Your settings have been updated")

        elif "invite_team_member" in request.POST:
            if not profile.team_access_allowed:
                return HttpResponseForbidden()

            form = InviteTeamMemberForm(request.POST)
            if form.is_valid():
                email = form.cleaned_data["email"]
                user_checks = [
                    value for key, value in request.POST.items()
                    if 'check' in key
                ]
                print(user_checks)
                try:
                    user = User.objects.get(email=email)
                except User.DoesNotExist:
                    user = _make_user(email)

                for chek in user_checks:
                    notify = UserToNotify(recepient=user)
                    check_object = Check.objects.get(id=chek)
                    notify.check_id = check_object
                    notify.save()

                profile.invite(user)
                messages.success(request, "Invitation to %s sent!" % email)
        elif "remove_team_member" in request.POST:
            form = RemoveTeamMemberForm(request.POST)
            if form.is_valid():

                email = form.cleaned_data["email"]
                farewell_user = User.objects.get(email=email)
                farewell_user.profile.current_team = None
                farewell_user.profile.save()

                Member.objects.filter(team=profile,
                                      user=farewell_user).delete()

                messages.info(request, "%s removed from team!" % email)
        elif "set_team_name" in request.POST:
            if not profile.team_access_allowed:
                return HttpResponseForbidden()

            form = TeamNameForm(request.POST)
            if form.is_valid():
                profile.team_name = form.cleaned_data["team_name"]
                profile.save()
                messages.success(request, "Team Name updated!")

    tags = set()
    filtered_checks = Check.objects.filter(
        user=request.team.user).order_by("created")
    checks = list(filtered_checks)
    for check in filtered_checks:
        tags.update(check.tags_list())

    username = request.team.user.username
    badge_urls = []
    for tag in sorted(tags, key=lambda s: s.lower()):
        if not re.match("^[\w-]+$", tag):
            continue

        badge_urls.append(get_badge_url(username, tag))

    ctx = {
        "page": "profile",
        "badge_urls": badge_urls,
        "profile": profile,
        "show_api_key": show_api_key,
        "checks": checks
    }

    return render(request, "accounts/profile.html", ctx)
Exemplo n.º 25
0
def csrf_failure(request, reason='', template=None):
    return HttpResponseForbidden(
        render(request, template),
        content_type='text/html'
    )
Exemplo n.º 26
0
def profile(request):
    _ensure_own_team(request)
    profile = request.profile

    ctx = {
        "page": "profile",
        "profile": profile,
        "show_api_key": False,
        "api_status": "default",
        "team_status": "default"
    }

    if request.method == "POST":
        if "change_email" in request.POST:
            profile.send_change_email_link()
            return redirect("hc-link-sent")
        elif "set_password" in request.POST:
            profile.send_set_password_link()
            return redirect("hc-link-sent")
        elif "create_api_key" in request.POST:
            profile.set_api_key()
            ctx["show_api_key"] = True
            ctx["api_key_created"] = True
            ctx["api_status"] = "success"
        elif "revoke_api_key" in request.POST:
            profile.api_key = ""
            profile.save()
            ctx["api_key_revoked"] = True
            ctx["api_status"] = "info"
        elif "show_api_key" in request.POST:
            ctx["show_api_key"] = True
        elif "invite_team_member" in request.POST:
            if not profile.can_invite():
                return HttpResponseForbidden()

            form = InviteTeamMemberForm(request.POST)
            if form.is_valid():

                email = form.cleaned_data["email"]
                try:
                    user = User.objects.get(email=email)
                except User.DoesNotExist:
                    user = _make_user(email)

                profile.invite(user)
                ctx["team_member_invited"] = email
                ctx["team_status"] = "success"

        elif "remove_team_member" in request.POST:
            form = RemoveTeamMemberForm(request.POST)
            if form.is_valid():

                email = form.cleaned_data["email"]
                farewell_user = User.objects.get(email=email)
                farewell_user.profile.current_team = None
                farewell_user.profile.save()

                Member.objects.filter(team=profile,
                                      user=farewell_user).delete()

                ctx["team_member_removed"] = email
                ctx["team_status"] = "info"
        elif "set_team_name" in request.POST:
            form = TeamNameForm(request.POST)
            if form.is_valid():
                profile.team_name = form.cleaned_data["team_name"]
                profile.save()
                ctx["team_name_updated"] = True
                ctx["team_status"] = "success"

    return render(request, "accounts/profile.html", ctx)
Exemplo n.º 27
0
def edit_dashboard(request, pk=None):
    if request.method == 'GET':
        user = request.user
        if request.user.is_authenticated():
            saved_queries = Query.objects.filter(user=user).exclude(
                document__from=[])
        else:
            saved_queries = []

        for q in saved_queries:
            doc = q.document
            changed = False
            for f in doc['from']:
                for s in f['select']:
                    if s['type'] == "VALUE":
                        if 'datatype' not in s.keys():
                            try:
                                s['datatype'] = Variable.objects.get(
                                    pk=int(f['type'])).dataType
                                changed = True
                            except:
                                s['datatype'] = 'FLOAT'
                                pass
                    else:
                        if 'datatype' not in s.keys():
                            try:
                                s['datatype'] = Dimension.objects.get(
                                    pk=int(s['type'])).dataType
                                changed = True
                            except:
                                s['datatype'] = 'FLOAT'
                                pass
            if changed:
                q.document = doc
                q.save()

        try:
            dashboard = Dashboard.objects.get(pk=pk)
        except ObjectDoesNotExist:
            message = 'You cannot edit this Dashboard!\nThe Dashboard does not exist or has already been deleted!'
            return render(request, 'error_page.html', {'message': message})

        # try:
        #     if dashboard.user_id != user.id:
        #         raise PermissionDenied
        # except:
        #     return HttpResponseForbidden()
        # check for the access
        try:
            access_decision = PEP.access_to_edit_dashboard(
                request, dashboard.id)
            if access_decision is False:
                raise PermissionDenied
        except:
            return HttpResponseForbidden()

        # variables_list = []
        # dimensions_list = []
        # var_list = Variable.objects.all()
        # dim_list = Dimension.objects.all()
        # for el in var_list:
        #     if not (el.name in variables_list):
        #         variables_list.append(el.name.encode('ascii'))
        # for el in dim_list:
        #     if not (el.name in dimensions_list):
        #         dimensions_list.append(el.name.encode('ascii'))
        # toCreate = dashboard.title
        form_class = forms.CkEditorForm
        dashboard.viz_components = convert_unicode_json(
            dashboard.viz_components)
        print dashboard.viz_components
        conf_viz_json = ''
        try:
            with open(
                    'visualizer/static/visualizer/visualisations_settings.json'
            ) as f:
                conf_viz_json = json.dumps(json.load(f))
        except:
            pass

        # check if user is the owner or just has been granted access
        owner = False
        if dashboard.user_id == user.id:
            owner = True

        return render(
            request,
            'dashboard_builder/dashboard_editor_new.html',
            {
                'dashboard':
                dashboard,
                'dashboard_json':
                json.dumps(dashboard.viz_components),
                'dashboard_pk':
                pk,
                'dashboard_title':
                dashboard.title,
                'is_owner':
                owner,
                'sidebar_active':
                'products',
                'saved_queries':
                saved_queries,
                'available_viz':
                Visualization.objects.filter(hidden=False).order_by(
                    '-type', '-title'),
                'form':
                form_class,
                # 'toCreate': toCreate,
                # 'variables_list': variables_list,
                # 'dimensions_list': dimensions_list,
                'visualisation_configuration':
                conf_viz_json
            })
    return None
Exemplo n.º 28
0
def change_enrollment(request, check_access=True):
    """
    Modify the enrollment status for the logged-in user.

    TODO: This is lms specific and does not belong in common code.

    The request parameter must be a POST request (other methods return 405)
    that specifies course_id and enrollment_action parameters. If course_id or
    enrollment_action is not specified, if course_id is not valid, if
    enrollment_action is something other than "enroll" or "unenroll", if
    enrollment_action is "enroll" and enrollment is closed for the course, or
    if enrollment_action is "unenroll" and the user is not enrolled in the
    course, a 400 error will be returned. If the user is not logged in, 403
    will be returned; it is important that only this case return 403 so the
    front end can redirect the user to a registration or login page when this
    happens. This function should only be called from an AJAX request, so
    the error messages in the responses should never actually be user-visible.

    Args:
        request (`Request`): The Django request object

    Keyword Args:
        check_access (boolean): If True, we check that an accessible course actually
            exists for the given course_key before we enroll the student.
            The default is set to False to avoid breaking legacy code or
            code with non-standard flows (ex. beta tester invitations), but
            for any standard enrollment flow you probably want this to be True.

    Returns:
        Response

    """
    # Get the user
    user = request.user

    # Ensure the user is authenticated
    if not user.is_authenticated:
        return HttpResponseForbidden()

    # Ensure we received a course_id
    action = request.POST.get("enrollment_action")
    if 'course_id' not in request.POST:
        return HttpResponseBadRequest(_("Course id not specified"))

    try:
        course_id = CourseKey.from_string(request.POST.get("course_id"))
    except InvalidKeyError:
        log.warning(
            u"User %s tried to %s with invalid course id: %s",
            user.username,
            action,
            request.POST.get("course_id"),
        )
        return HttpResponseBadRequest(_("Invalid course id"))

    # Allow us to monitor performance of this transaction on a per-course basis since we often roll-out features
    # on a per-course basis.
    monitoring_utils.set_custom_attribute('course_id', text_type(course_id))

    if action == "enroll":
        # Make sure the course exists
        # We don't do this check on unenroll, or a bad course id can't be unenrolled from
        if not modulestore().has_course(course_id):
            log.warning(u"User %s tried to enroll in non-existent course %s",
                        user.username, course_id)
            return HttpResponseBadRequest(_("Course id is invalid"))

        # Record the user's email opt-in preference
        if settings.FEATURES.get('ENABLE_MKTG_EMAIL_OPT_IN'):
            _update_email_opt_in(request, course_id.org)

        available_modes = CourseMode.modes_for_course_dict(course_id)

        # Check whether the user is blocked from enrolling in this course
        # This can occur if the user's IP is on a global blacklist
        # or if the user is enrolling in a country in which the course
        # is not available.
        redirect_url = embargo_api.redirect_if_blocked(
            course_id, user=user, ip_address=get_ip(request), url=request.path)
        if redirect_url:
            return HttpResponse(redirect_url)

        if CourseEntitlement.check_for_existing_entitlement_and_enroll(
                user=user, course_run_key=course_id):
            return HttpResponse(
                reverse('courseware', args=[six.text_type(course_id)]))

        # Check that auto enrollment is allowed for this course
        # (= the course is NOT behind a paywall)
        if CourseMode.can_auto_enroll(course_id):
            # Enroll the user using the default mode (audit)
            # We're assuming that users of the course enrollment table
            # will NOT try to look up the course enrollment model
            # by its slug.  If they do, it's possible (based on the state of the database)
            # for no such model to exist, even though we've set the enrollment type
            # to "audit".
            try:
                enroll_mode = CourseMode.auto_enroll_mode(
                    course_id, available_modes)
                if enroll_mode:
                    CourseEnrollment.enroll(user,
                                            course_id,
                                            check_access=check_access,
                                            mode=enroll_mode)
            except Exception:  # pylint: disable=broad-except
                return HttpResponseBadRequest(_("Could not enroll"))

        # If we have more than one course mode or professional ed is enabled,
        # then send the user to the choose your track page.
        # (In the case of no-id-professional/professional ed, this will redirect to a page that
        # funnels users directly into the verification / payment flow)
        if CourseMode.has_verified_mode(
                available_modes) or CourseMode.has_professional_mode(
                    available_modes):
            return HttpResponse(
                reverse("course_modes_choose",
                        kwargs={'course_id': text_type(course_id)}))

        # Otherwise, there is only one mode available (the default)
        return HttpResponse()
    elif action == "unenroll":
        enrollment = CourseEnrollment.get_enrollment(user, course_id)
        if not enrollment:
            return HttpResponseBadRequest(
                _("You are not enrolled in this course"))

        certificate_info = cert_info(user, enrollment.course_overview)
        if certificate_info.get('status') in DISABLE_UNENROLL_CERT_STATES:
            return HttpResponseBadRequest(
                _("Your certificate prevents you from unenrolling from this course"
                  ))

        CourseEnrollment.unenroll(user, course_id)
        REFUND_ORDER.send(sender=None, course_enrollment=enrollment)
        return HttpResponse()
    else:
        return HttpResponseBadRequest(_("Enrollment action is invalid"))
Exemplo n.º 29
0
	def __call__(self, request):
		if request.user.is_authenticated and not request.user.is_active():
			return HttpResponseForbidden()
		response = self.get_response(request)

		return response
Exemplo n.º 30
0
Arquivo: views.py Projeto: AKBQuiz/Web
def infoapply(request):
    ultra = False
    from crawler.models import OfficialInfo,Relation
    from memberinfo.models import MemberInfo,Group,Team
    import memberinfo.divisions as div

    if request.GET.has_key('ultra'):
        if not request.user.is_staff:
            return HttpResponseForbidden('You are not a staff of this site.')
        else:
            ultra = True
            rela = Relation.objects.filter(mid__isnull = False)
            for r in rela:
                OfficialInfo.objects.filter(mid__isnull = True, name__iexact = r.jp_name).update(mid = r.mid)
            pass
    counter = 0
    infolist = OfficialInfo.objects.filter(mid__isnull = False, applied = False).all()
    namelist = infolist.values('name').all()
    for name in namelist:
        items = infolist.filter(name__iexact = name['name']).all()
        member = {}
        for item in items:
            for k in item._meta.get_all_field_names():
                v = getattr(item,k)
                if v:
                    member[k] = v
        try:
            m = member['mid']
            g = Group.objects.get(groupname__iexact = member['group'])
            t = g.team_set.get(teamname__iexact = member['team'])
            m.team = t
            m.comefrom = div.getIdByJp(member['hometown'])
            m.birthday = member['birthday']
            if ultra:
                from memberinfo.cn_jp import jp2cn
                m.name = member['name']
                l = []
                for c in m.cn_name:
                    l.append(jp2cn(c))
                m.cn_name = ''.join(l)

            if member.get('nick', False):
                m.nick = member['nick']
            if member.get('avatar', False):
                m.avatar = member['avatar']
            if member.get('concurrent_group',False):
                cg = Group.objects.get(groupname__iexact = member['concurrent_group'])
                ct = cg.team_set.get(teamname__iexact = member['concurrent_team'])
                m.bothin = ct
                pass

            des = []
            if member.get('managercom',False):
                if member.get('managercom_href',False):
                    des.append(u'经纪公司:<a href="' + member['managercom_href'] + '">' + member['managercom'] + '</a>')
                else:
                    des.append(u'经纪公司:' + member['managercom'])
            if member.get('bloodtype',False):
                des.append(u'血型:' + member['bloodtype'])
            if member.get('height',False):
                des.append(u'身高:' + member['height'])
            if member.get('catchphrase',False):
                des.append(u'Catch Phrase:' + member['catchphrase'])
            if member.get('stunt',False):
                des.append(u'特技:' + member['stunt'])
            if member.get('dream',False):
                des.append(u'梦想:' + member['dream'])
            if member.get('favfood',False):
                des.append(u'最爱的食物:' + member['favfood'])
            if member.get('favquote',False):
                des.append(u'座右铭:' + member['favquote'])
            if member.get('favfood',False):
                des.append(u'最爱的食物:' + member['favfood'])
            if member.get('hobby',False):
                des.append(u'爱好:' + member['hobby'])
            if member.get('charm',False):
                des.append(u'魅力点:' + member['charm'])
            if member.get('msg',False):
                des.append(member['msg'])
            m.description = '<br />'.join(des)
            m.save()
            counter += 1
        except Exception, e:
            print e
            continue
        items.update(applied = True)
        pass
Exemplo n.º 31
0
    def post(self, request):
        try:
            data = json.loads(request.body)
        except ValueError:
            return HttpResponseBadRequest('Request body is not valid JSON.')

        # Must be a json dictionary.
        if not isinstance(data, dict):
            return HttpResponseBadRequest('Request body not a JSON dict.')

        # Odlc type is required.
        if 'type' not in data:
            return HttpResponseBadRequest('Odlc type required.')

        # Team id can only be specified if superuser.
        user = request.user
        if 'team_id' in data:
            if request.user.is_superuser:
                user = User.objects.get(username=data['team_id'])
            else:
                return HttpResponseForbidden(
                    'Non-admin users cannot send team_id')

        latitude = data.get('latitude')
        longitude = data.get('longitude')

        # Require zero or both of latitude and longitude.
        if (latitude is not None and longitude is None) or \
            (latitude is None and longitude is not None):
            return HttpResponseBadRequest(
                'Either none or both of latitude and longitude required.')

        # Cannot submit JSON with actionable_override if not superuser.
        if 'actionable_override' in data and not request.user.is_superuser:
            return HttpResponseForbidden(
                'Non-admin users cannot submit actionable override.')

        try:
            data = normalize_data(data)
        except ValueError as e:
            return HttpResponseBadRequest(str(e))

        l = None
        if latitude is not None and longitude is not None:
            l = GpsPosition(
                latitude=data['latitude'], longitude=data['longitude'])
            l.save()

        # Use the dictionary get() method to default non-existent values to None.
        t = Odlc(
            user=user,
            odlc_type=data['type'],
            location=l,
            orientation=data.get('orientation'),
            shape=data.get('shape'),
            background_color=data.get('background_color'),
            alphanumeric=data.get('alphanumeric', ''),
            alphanumeric_color=data.get('alphanumeric_color'),
            description=data.get('description', ''),
            autonomous=data.get('autonomous', False),
            actionable_override=data.get('actionable_override', False))
        t.save()

        return JsonResponse(
            t.json(is_superuser=request.user.is_superuser), status=201)
Exemplo n.º 32
0
 def wrapper(req, *args, **kwargs):
     user = req.user
     in_group = user.groups.filter(id__in=groups).first()
     if in_group or user.is_superuser:
         return func(req, *args, **kwargs)
     return HttpResponseForbidden()
Exemplo n.º 33
0
def parameterval_oauth_generate_access_token(request, pk) -> HttpResponse:
    """Return a temporary access_token the client can use.

    Only the owner can generate an access token: we must keep the secret away
    from prying eyes. This access token lets the client read all the owner's
    documents on GDrive.

    The response is always text/plain. Status codes:

    200 OK -- a token
    404 Not Found -- param not found, or param has no secret
    403 Forbidden -- user not allowed to generate token

    We expect the caller to silently accept 404 Not Found but log other errors.
    """
    param = parameter_val_or_response_for_read(pk, request)
    if isinstance(param, HttpResponse):
        return param

    workflow = param.wf_module.workflow
    # Let's be abundantly clear: this is a _secret_. Users give us their
    # refresh tokens under the assmption that we won't share access to all
    # their files with _anybody_.
    #
    # We aren't checking if writes are allowed. We're checking the user's
    # identity.
    #
    # See Workflow.request_authorized_write(), which is _currently_ the same
    # but may not stay that way.
    is_owner = False
    if request.user and request.user == workflow.owner:
        is_owner = True
    if workflow.anonymous_owner_session_key and request.session.session_key:
        if workflow.anonymous_owner_session_key == request.session.session_key:
            is_owner = True
    if not is_owner:
        return HttpResponseForbidden(
            'Only the workspace owner can generate an access token')

    spec = param.parameter_spec
    if spec.type != ParameterSpec.SECRET:
        return HttpResponseForbidden(f'This is a {spec.type}, not a SECRET')

    service = oauth.OAuthService.lookup_or_none(spec.id_name)
    if not service:
        allowed_services = settings.PARAMETER_OAUTH_SERVICES.keys()
        return HttpResponseForbidden(
            f'We only support id_name {", ".join(allowed_services)}')

    secret_json = param.value
    if not secret_json:
        return HttpResponseNotFound('secret not set')
    try:
        secret_data = json.loads(secret_json)
    except json.decoder.JSONDecodeError:
        return HttpResponseForbidden('non-JSON secret')
    try:
        offline_token = secret_data['secret']
    except KeyError:
        return HttpResponseForbidden('secret value has no secret')

    token = service.generate_access_token_or_str_error(offline_token)
    if isinstance(token, str):
        return HttpResponseForbidden(token)

    # token['access_token'] is short-term (1hr). token['refresh_token'] is
    # super-private and we should never transmit it.
    return HttpResponse(token['access_token'], content_type='text/plain')
Exemplo n.º 34
0
 def wrapper(obj, req, *args, **kwargs):
     user = req.user
     if user.has_perm(perm):
         return func(obj, req, *args, **kwargs)
     else:
         return HttpResponseForbidden()
Exemplo n.º 35
0
def fc_callback(request):
    fc_base = settings.FC_AS_FS_BASE_URL
    fc_callback_uri = f"{settings.FC_AS_FS_CALLBACK_URL}/callback"
    # fc_callback_uri_logout = f"{settings.FC_AS_FS_CALLBACK_URL}/logout-callback"
    fc_id = settings.FC_AS_FS_ID
    fc_secret = settings.FC_AS_FS_SECRET

    state = request.GET.get("state")

    try:
        connection = Connection.objects.get(state=state)
    except Connection.DoesNotExist:
        log.info("FC as FS - This state does not seem to exist")
        log.info(state)
        return HttpResponseForbidden()

    if connection.expiresOn < timezone.now():
        log.info("403: The connection has expired.")
        return HttpResponseForbidden()

    code = request.GET.get("code")
    if not code:
        log.info("403: No code has been provided.")
        return HttpResponseForbidden()

    token_url = f"{fc_base}/token"
    payload = {
        "grant_type": "authorization_code",
        "redirect_uri": fc_callback_uri,
        "client_id": fc_id,
        "client_secret": fc_secret,
        "code": code,
    }

    headers = {"Accept": "application/json"}

    request_for_token = python_request.post(token_url,
                                            data=payload,
                                            headers=headers)
    content = request_for_token.json()
    connection.access_token = content.get("access_token")
    connection.save()
    fc_id_token = content.get("id_token")

    try:
        decoded_token = jwt.decode(
            fc_id_token,
            settings.FC_AS_FS_SECRET,
            audience=settings.FC_AS_FS_ID,
            algorithm="HS256",
        )
    except ExpiredSignatureError:
        log.info("403: token signature has expired.")
        return HttpResponseForbidden()
    if connection.nonce != decoded_token.get("nonce"):
        log.info("403: The nonce is different than the one expected.")
        return HttpResponseForbidden()
    if connection.expiresOn < timezone.now():
        log.info("403: The connection has expired.")
        return HttpResponseForbidden()
    try:
        usager = Usager.objects.get(sub=decoded_token["sub"])

    except Usager.DoesNotExist:

        usager, error = get_user_info(fc_base, connection.access_token)
        if error:
            messages.error(request, error)
            return redirect("dashboard")

    connection.usager = usager
    connection.save()

    # logout_base = f"{fc_base}/logout"
    # logout_id_token = f"id_token_hint={fc_id_token}"
    # logout_state = f"state={state}"
    # logout_redirect = f"post_logout_redirect_uri={fc_callback_uri_logout}"
    # logout_url = f"{logout_base}?{logout_id_token}&{logout_state}&{logout_redirect}"
    return redirect("new_mandat_recap")  # revert to logout_url
Exemplo n.º 36
0
 def __init__(self):
   HttpResponseForbidden.__init__(self)#,msg="You don't have permission to access the requested object.")
   # Hopefully this doesn't break the error
   self.write(render_to_string('errors/http_forbidden.phtml'))
   self.write("You don't have permission to access the requested object.")
Exemplo n.º 37
0
 def get(self, request):
     user = request.user
     if not user.is_staff or not user.is_superuser or not user.is_authenticated:
         return HttpResponseForbidden()
     return render(request, 'remote_admin/rcon.html')
Exemplo n.º 38
0
def user_repo_sync(request, repo_id):
    """
    POST /repo/:id/sync
    or
    DELETE /repo/:id/sync

    Sets repo synced property as True or False (POST or DELETE)
    """
    try:
        repo = Repo.objects.get(id=repo_id)
    except Repo.DoesNotExist:
        raise Http404

    if not repo.user == request.user:
        return HttpResponseForbidden()

    if request.method == 'POST':
        # See tests for the why on this awfulness
        if 'testing' in request.GET:
            return HttpResponse('ok', status=201)

        repo.synced = True
        repo.sync_status = repo.SYNCING

        # Create a GitHub web hook so we get notified when this repo is pushed
        hook_data = {
            'name': 'web',
            'active': True,
            'events': ['push'],
            'config': {
                'url': repo.hook_url,
                'content_type': 'json'
            }
        }
        github = GitHub(repo.user)
        gh_request = github.post('/repos/{0}/hooks'.format(repo.full_name), hook_data)
        if gh_request.status_code == 201:
            logger.info('Hook created for repo: {0}'.format(repo))
        else:
            logger.info('Hook not created for repo: {0}'.format(repo))
        repo.save()
        get_repo_feature_sets.apply_async((repo,))
        return HttpResponse(json.dumps({'status': 'ok'}), content_type='application/json', status=201)
    else:  # DELETE
        # See tests for the why on this awfulness
        if 'testing' in request.GET:
            return HttpResponse('ok', status=204)

        repo.synced = False
        repo.sync_status = repo.NOT_SYNCED
        github = GitHub(repo.user)
        gh_request = github.get('/repos/{0}/hooks'.format(repo.full_name))
        hook_id_to_delete = None

        for hook in gh_request.json():
            if 'url' in hook['config'] and hook['config']['url'] == repo.hook_url:
                hook_id_to_delete = hook['id']
                continue

        if hook_id_to_delete is not None:
            gh_request = github.delete('/repos/{0}/hooks/{1}'.format(repo.full_name, hook_id_to_delete))
            if gh_request.status_code == 204:
                logger.info('Hook deleted for repo: {0}'.format(repo))
                delete_repo_feature_sets.apply_async((repo,))
            else:
                logger.warning('Hook not deleted for repo: {0}'.format(repo))
        repo.save()
        return HttpResponse(json.dumps({'status': 'ok'}), content_type='application/json', status=204)
Exemplo n.º 39
0
        auth, created = AuthProfile.objects.get_or_create(user=request.user)
        # store dropbox_access_token
        auth.dropbox_access_token = dropbox_access_token
        auth.dropbox_userid = user_id
        auth.user = request.user
        auth.save()

        return HttpResponseRedirect("/profile/")
    except dropbox.client.DropboxOAuth2Flow.BadRequestException, e:
        return HttpResponseBadRequest(e)
    except dropbox.client.DropboxOAuth2Flow.BadStateException, e:
        # Start the auth flow again.
        return HttpResponseRedirect(
            "http://www.mydomain.com/dropbox_auth_start")
    except dropbox.client.DropboxOAuth2Flow.CsrfException, e:
        return HttpResponseForbidden()
    except dropbox.client.DropboxOAuth2Flow.NotApprovedException, e:
        raise e
    except dropbox.client.DropboxOAuth2Flow.ProviderException, e:
        raise e


# URL handler for /dropbox-auth-start
def dropbox_auth_disconnect(request):
    request.user.authprofile.dropbox_access_token = ""
    request.user.authprofile.save()
    return HttpResponseRedirect("/profile/")


def process_file(path, metadata, client, user):
    def get_app_config(client, path):
Exemplo n.º 40
0
def user_feature_set(request, feature_set_id):
    per_page = 50

    feature_set = get_object_or_404(FeatureSet, id=feature_set_id)

    if not feature_set.repo.user == request.user:
        return HttpResponseForbidden()

    if request.method == 'GET':
        if feature_set.is_syncing:
            context = {'feature_set': feature_set}
        else:
            count = Feature.objects.filter(feature_set=feature_set).count()

            requested_page = request.GET.get('page', 1)

            try:
                requested_page = int(requested_page)
            except ValueError:
                return redirect('user_feature_set', feature_set_id=feature_set_id)

            features = Feature.objects.filter(feature_set=feature_set).geojson()

            paginated = Paginator(features, per_page)

            try:
                current_page = paginated.page(requested_page)
            except EmptyPageException:
                if requested_page == 0:
                    return redirect('%s?page=%s' % (reverse('user_feature_set', args=(feature_set_id,)), 1))
                else:
                    return redirect('%s?page=%s' % (reverse('user_feature_set', args=(feature_set_id,)), paginated.num_pages))

            current_features = current_page.object_list
            previous_page_number = current_page.previous_page_number() if current_page.has_previous() else None
            next_page_number = current_page.next_page_number() if current_page.has_next() else None

            prop_keys = json.loads(current_features[0].properties).keys()

            processed_features = []
            geojson = {'type': 'FeatureCollection', 'features': []}
            for current_feature in current_features:
                processed_feature = {'id': current_feature.id}
                current_feature_props = json.loads(current_feature.properties)
                for prop_key in prop_keys:
                    processed_feature[prop_key] = current_feature_props.get(prop_key)
                processed_features.append(processed_feature)

                geometry = json.loads(current_feature.geojson)
                geojson_feature = {'type': 'Feature', 'geometry': geometry, 'properties': current_feature_props, 'id': current_feature.id}
                geojson['features'].append(geojson_feature)

            context = {
                'feature_set': feature_set,
                'api_url': '{0}{1}'.format(
                    'http://gitspatial.com',
                    reverse('v1_feature_set_query', kwargs={'user_name': feature_set.repo.user.username, 'repo_name': feature_set.repo.name, 'feature_set_name': feature_set.name})),
                'count': count,
                'center_lat': feature_set.center[1],
                'center_lng': feature_set.center[0],
                'bounds': list(feature_set.bounds),
                'features': processed_features,
                'geojson': json.dumps(geojson),
                'prop_keys': prop_keys,
                'page_range': paginated.page_range,
                'current_page': requested_page,
                'previous_page_number': previous_page_number,
                'next_page_number': next_page_number,
                'start_index': current_page.start_index(),
                'end_index': current_page.end_index()}

        return render(request, 'user_feature_set.html', context)
    else:
        raw_data = request.body
        parts = raw_data.split('&')
        data = {}
        for part in parts:
            key, value = part.split('=')
            data[key] = value

        if 'value' not in data:
            return HttpResponseBadRequest('No value found')

        value = data['value']

        if not (0 < len(value) < 1000):
            return HttpResponseBadRequest('Feature set name must be between 1 and 1,000 characters.')

        feature_set.name = value
        feature_set.save()

        return HttpResponse('Success! Seeya.')
Exemplo n.º 41
0
    def form_valid(self, form):

        if not self.request.user.has_perm('groups.delete_group'):
            raise HttpResponseForbidden()
        else:
            return super().form_valid(form)
Exemplo n.º 42
0
 def __init__(self, message):
     DjangoHttpResponseForbidden.__init__(self,
                                          message_to_json(message),
                                          content_type='application/json')