Handle upload on POST if authorized.
760395
def upload(name):
    ''''''
    storage = fs.by_name(name)
    return jsonify(success=True, **handle_upload(storage))
124269
def process_request(self, request):
        """"""
        assert hasattr(request, 'user')
        if not request.user.is_authenticated():
            path = request.path_info.lstrip('/')
            if not any(m.match(path) for m in EXEMPT_URLS):
                return HttpResponseRedirect(reverse(settings.LOGIN_URL))
631704
def handle_upload(repo, **kwargs):
    
    log.info('upload: %s' %(repo))
    name = kwargs.get('filename', 'Untitled')
    data = kwargs.get('filedata')
    repo.addItem(Item.from_string(repo=repo, name=name, string=data))
332337
protected function handleAuthentication()
    {
        if (isset($this->payload['options']['username'], $this->payload['options']['password'])) {
            $this->addCurlOption(CURLOPT_USERPWD, sprintf('%s:%s', $this->payload['options']['username'], $this->payload['options']['password']));
        }
    }
651161
def execute(self):
        """"""
        try:
            if self.upstream:
                if self.options['listings'] is True:
                    listing.upload(self.client, self.source_directory)
                    self.client.commit()
                if self.options['images'] is True:
                    image.upload(self.client, self.source_directory)
                    self.client.commit()
                if self.options['inapp'] is True:
                    inapp_product.upload(self.client, self.source_directory)
            else:
                if self.options['listings'] is True:
                    listing.download(self.client, self.source_directory)
                if self.options['images'] is True:
                    image.download(self.client, self.source_directory)
                if self.options['inapp'] is True:
                    inapp_product.download(self.client, self.source_directory)

        except client.AccessTokenRefreshError:
            print(
                'The credentials have been revoked or expired, please re-run'
                'the application to re-authorize')
216270
def post(self, *args, **kwargs):
        
        # Look for a wizard_prev_step element in the posted data which
        # contains a valid step name. If one was found, render the requested
        # form. (This makes stepping back a lot easier).
        wizard_prev_step = self.request.POST.get('wizard_prev_step', None)
        if wizard_prev_step and wizard_prev_step in self.get_form_list():
            self.storage.current_step = wizard_prev_step
            form = self.get_form(
                data=self.storage.get_step_data(self.steps.current),
                files=self.storage.get_step_files(self.steps.current))
            return self.render(form)

        # Check if form was refreshed
        management_form = ManagementForm(self.request.POST, prefix=self.prefix)
        if not management_form.is_valid():
            raise ValidationError(
                'ManagementForm data is missing or has been tampered.')

        form_current_step = management_form.cleaned_data['current_step']
        if (form_current_step != self.steps.current and
                self.storage.current_step is not None):
            # form refreshed, change current step
            self.storage.current_step = form_current_step

        # get the form for the current step
        form = self.get_form(data=self.request.POST, files=self.request.FILES)

        # and try to validate
        if form.is_valid():
            # if the form is valid, store the cleaned data and files.
            self.storage.set_step_data(self.steps.current, self.process_step(form))
            self.storage.set_step_files(self.steps.current, self.process_step_files(form))

            # check if the current step is the last step
            if self.steps.current == self.steps.last:
                # no more steps, render done view
                return self.render_done(form, **kwargs)
            else:
                # proceed to the next step
                return self.render_next_step(form)
        return self.render(form)
336830
function authorized (req, res) {
  const { params, uppy } = req
  const providerName = params.providerName

  if (!uppy.providerTokens || !uppy.providerTokens[providerName]) {
    return res.json({ authenticated: false })
  }

  const token = uppy.providerTokens[providerName]
  uppy.provider.list({ token, uppy }, (err, response, body) => {
    const notAuthenticated = Boolean(err)
    if (notAuthenticated) {
      logger.debug(`${providerName} failed authorizarion test err:${err}`, 'provider.auth.check')
    }
    return res.json({ authenticated: !notAuthenticated })
  })
}
1205837
protected function handleUpload()
    {
        $this->uploadedField = array_keys($_FILES)[0];
        //check if any uploaded file for a defined field
        $this->uploadOk = $this->checkUpload();
        if(!$this->uploadOk) {
            return;
        }
        //exec upload
        $this->uploadOk = $this->uploadFields[$this->uploadedField]->handleUpload($this->uploader);
        if(!$this->uploadOk) {
            return;
        }
        //outputs post processing
        $outputs = $this->uploadFields[$this->uploadedField]->getOutputsFiles();
        foreach($this->uploadFieldsDefinitions[$this->uploadedField]['outputs'] as $output => $outputDefinition) {
            if(isset($outputDefinition['processor'])) {
                $this->{$outputDefinition['processor']}($outputs[$output]['path']);
            }
        }
    }
1004305
def _HandleApi(self, request):
    """"""
    # Checks CSRF token. CSRF token cookie is updated when homepage is visited
    # or via GetPendingUserNotificationsCount API call.
    ValidateCSRFTokenOrRaise(request)

    response = http_api.RenderHttpResponse(request)

    # GetPendingUserNotificationsCount is an API method that is meant
    # to be invoked very often (every 10 seconds). So it's ideal
    # for updating the CSRF token.
    # We should also store the CSRF token if it wasn't yet stored at all.
    if (("csrftoken" not in request.cookies) or response.headers.get(
        "X-API-Method", "") == "GetPendingUserNotificationsCount"):
      StoreCSRFCookie(request.user, response)

    return response
1205686
def do_POST(self):  # pylint: disable=g-bad-name
    """"""
    self._IncrementActiveCount()
    try:
      if self.path.startswith("/upload"):
        stats_collector_instance.Get().IncrementCounter(
            "frontend_http_requests", fields=["upload", "http"])

        logging.error("Requested no longer supported file upload through HTTP.")
        self.Send("File upload though HTTP is no longer supported", status=404)
      else:
        stats_collector_instance.Get().IncrementCounter(
            "frontend_http_requests", fields=["control", "http"])
        self.Control()

    except Exception as e:  # pylint: disable=broad-except
      if flags.FLAGS.pdb_post_mortem:
        pdb.post_mortem()

      logging.exception("Had to respond with status 500.")
      self.Send("Error: %s" % e, status=500)
    finally:
      self._DecrementActiveCount()
419379
protected function checkUploadPostback()
    {
        if ($this->readOnly) {
            return;
        }

        $fileName = null;
        $quickMode = false;

        if (
            (!($uniqueId = Request::header('X-OCTOBER-FILEUPLOAD')) || $uniqueId != $this->getId()) &&
            (!$quickMode = post('X_OCTOBER_MEDIA_MANAGER_QUICK_UPLOAD'))
        ) {
            return;
        }

        try {
            if (!Input::hasFile('file_data')) {
                throw new ApplicationException('File missing from request');
            }

            $uploadedFile = Input::file('file_data');

            $fileName = $uploadedFile->getClientOriginalName();

            /*
             * Convert uppcare case file extensions to lower case
             */
            $extension = strtolower($uploadedFile->getClientOriginalExtension());
            $fileName = File::name($fileName).'.'.$extension;

            /*
             * File name contains non-latin characters, attempt to slug the value
             */
            if (!$this->validateFileName($fileName)) {
                $fileNameClean = $this->cleanFileName(File::name($fileName));
                $fileName = $fileNameClean . '.' . $extension;
            }

            /*
             * Check for unsafe file extensions
             */
            if (!$this->validateFileType($fileName)) {
                throw new ApplicationException(Lang::get('backend::lang.media.type_blocked'));
            }

            /*
             * See mime type handling in the asset manager
             */
            if (!$uploadedFile->isValid()) {
                throw new ApplicationException($uploadedFile->getErrorMessage());
            }

            $path = $quickMode ? '/uploaded-files' : Input::get('path');
            $path = MediaLibrary::validatePath($path);
            $filePath = $path.'/'.$fileName;

            /*
             * getRealPath() can be empty for some environments (IIS)
             */
            $realPath = empty(trim($uploadedFile->getRealPath()))
                             ? $uploadedFile->getPath() . DIRECTORY_SEPARATOR . $uploadedFile->getFileName()
                             : $uploadedFile->getRealPath();

            MediaLibrary::instance()->put(
                $filePath,
                File::get($realPath)
            );

            /**
             * @event media.file.upload
             * Called after a file is uploaded
             *
             * Example usage:
             *
             *     Event::listen('media.file.upload', function((\Backend\Widgets\MediaManager) $mediaWidget, (string) $path, (\Symfony\Component\HttpFoundation\File\UploadedFile) $uploadedFile) {
             *         \Log::info($path . " was upoaded.");
             *     });
             *
             * Or
             *
             *     $mediaWidget->bindEvent('file.upload', function ((string) $path, (\Symfony\Component\HttpFoundation\File\UploadedFile) $uploadedFile) {
             *         \Log::info($path . " was uploaded");
             *     });
             *
             */
            $this->fireSystemEvent('media.file.upload', [$filePath, $uploadedFile]);

            Response::json([
                'link' => MediaLibrary::url($filePath),
                'result' => 'success'
            ])->send();
        }
        catch (Exception $ex) {
            Response::json($ex->getMessage(), 400)->send();
        }

        exit;
    }
875125
def post(self, request, *args, **kwargs):
        
        return self.lock(request, *args, **kwargs)
1147517
def upload_verify(self, file_location, dataset=None):
        """"""

        path = '/api/1.0/upload/verify'
        query = 'doNotGenerateAdvanceReport=true&filePath={}'.format(file_location)
        if dataset:
            query = 'doNotGenerateAdvanceReport=true&filePath={}&datasetId={}'.format(file_location, dataset)

        return self._api_get(definition.UploadVerifyResponse, path, query)
418061
def InitializeUpload(self, http_request, http=None, client=None):
        """"""
        if self.strategy is None:
            raise exceptions.UserError(
                'No upload strategy set; did you call ConfigureRequest?')
        if http is None and client is None:
            raise exceptions.UserError('Must provide client or http.')
        if self.strategy != RESUMABLE_UPLOAD:
            return
        http = http or client.http
        if client is not None:
            http_request.url = client.FinalizeTransferUrl(http_request.url)
        self.EnsureUninitialized()
        http_response = http_wrapper.MakeRequest(http, http_request,
                                                 retries=self.num_retries)
        if http_response.status_code != http_client.OK:
            raise exceptions.HttpError.FromResponse(http_response)

        self.__server_chunk_granularity = http_response.info.get(
            'X-Goog-Upload-Chunk-Granularity')
        url = http_response.info['location']
        if client is not None:
            url = client.FinalizeTransferUrl(url)
        self._Initialize(http, url)

        # Unless the user has requested otherwise, we want to just
        # go ahead and pump the bytes now.
        if self.auto_transfer:
            return self.StreamInChunks()
        return http_response
570908
private void captureUploadStateIfPossible() {
        if (origReq.getSSECustomerKey() == null) {
            persistableUpload = new PersistableUpload(origReq.getBucketName(),
                    origReq.getKey(), origReq.getFile()
                            .getAbsolutePath(), multipartUploadId,
                    configuration.getMinimumUploadPartSize(),
                    configuration.getMultipartUploadThreshold());
            notifyPersistableTransferAvailability();
        }
    }
221836
async def check_permission(request, permission, context=None):
    

    await check_authorized(request)
    allowed = await permits(request, permission, context)
    if not allowed:
        raise web.HTTPForbidden()
1372388
def post(self, request, *args, **kwargs):
        
        return self.approve(request, *args, **kwargs)