How to use the werkzeug.secure_filename function in Werkzeug

To help you get started, we’ve selected a few Werkzeug examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github distributed-system-analysis / sarjitsu / lib / backend / src / upload_processor.py View on Github external
def upload_files(target, sessionID, datafiles):
    """Upload the files to the server directory

    Keyword arguments:
    target - The target directory to upload the files to
    sessionID - The user session ID
    datafiles - The list of the files to be uploaded

    Returns:
        List
    """

    filename_list = []
    for datafile in datafiles:
        filename = secure_filename(datafile.filename).rsplit("/")[0]
        update_file_metadata(sessionID, filename)
        filename_list.append(filename)
        destination = os.path.join(target, filename)
        app.logger.info("Accepting incoming file: %s" % filename)
        app.logger.info("Saving it to %s" % destination)
        datafile.save(destination)
    return filename_list
github x3dom / pipeline / modelconvert / api / views.py View on Github external
current_app.logger.info("Found {0} payload".format(url.scheme))

    if url.scheme == 'http':
        #
        #  FIXME BIGTIME
        #  THE URL DOWNLOADING SHOULD OCCUR IN THE TASK AND NOT BLOCK
        #  THE INTERFACE
        #
        if not security.is_allowed_host(data['payload']):
            resp = jsonify(message="Tried to download from a insecure source ({0}). Only the following hosts are allowed: {1}".format(url.netloc, ", ".join(current_app.config['ALLOWED_DOWNLOAD_HOSTS'])))
            resp.status_code = 403 #forbidden
            return resp

        # download file to disk
        r = requests.get(data['payload'], stream=True, verify=False)
        filename = werkzeug.secure_filename(os.path.split(data['payload'])[-1].split("?")[0])

        # FIXME: this should check the mimetype in the http response header
        # as well
        if not security.is_allowed_file(filename):
            resp = jsonify(message="Please upload a file of the following type: %s" %
            ", ".join(current_app.config['ALLOWED_EXTENSIONS']))
            resp.status_code = 403 #forbidden
            return resp


        if r.status_code == requests.codes.ok:

            if int(r.headers['content-length']) > current_app.config['MAX_CONTENT_LENGTH']:
                resp = jsonify(message="File too big. Please don't try to use files greater than {0}".format(humanize.bytes(current_app.config['MAX_CONTENT_LENGTH'])))
                resp.status_code = 416 # request range unsatifieable
                return resp
github claritylab / lucida / lucida / commandcenter / controllers / Utilities.py View on Github external
def check_image_extension(upload_file):
	if upload_file is None:
		return
	filename = secure_filename(upload_file.filename)
	valid_extensions = ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'JPEG', \
		'bmp', 'BMP', 'gif', 'GIF']
	allowed_extensions = set(valid_extensions)
	if not (('.' in filename) and \
		(filename.rsplit('.', 1)[1] in allowed_extensions)):
		raise RuntimeError('Invalid file: extension must be one of ' \
			+ str(valid_extensions))
github Sketchy502 / SDV-Summary / sdv / __init__.py View on Github external
def file_uploaded(inputfile):
    memfile = io.BytesIO()
    inputfile.save(memfile)
    md5_info = md5(memfile)
    try:
        save = savefile(memfile.getvalue(), True)
        player_info = GameInfo(save).get_info()
    except defusedxml.common.EntitiesForbidden:
        g.error = _("I don't think that's very funny")
        return {'type':'render','target':'index.html','parameters':{"error":g.error}}
    except IOError:
        g.error = _("Savegame failed sanity check (if you think this is in error please let us know)")
        db = get_db()
        cur = db.cursor()
        cur.execute('INSERT INTO errors (ip, time, notes) VALUES ('+app.sqlesc+','+app.sqlesc+','+app.sqlesc+')',(request.environ['REMOTE_ADDR'],time.time(),'failed sanity check '+str(secure_filename(inputfile.filename))))
        db.commit()
        return {'type': 'render', 'target': 'index.html', 'parameters': {"error": g.error}}
    except AttributeError as e:
        g.error = _("Not valid save file - did you select file 'SaveGameInfo' instead of 'playername_number'?")
        # print(e)
        return {'type': 'render', 'target': 'index.html', 'parameters': {"error": g.error}}
    except ParseError as e:
        g.error = _("Not well-formed xml")
        return {'type':'render','target':'index.html','parameters':{"error":g.error}}
    except AssertionError as e:
        g.error = _("Savegame failed an internal check (often caused by mods) sorry :(")
        return {'type':'render','target':'index.html','parameters':{"error":g.error}}
    except Exception as e:
        logger.error("An unexpected error occoured: {}".format(e))
        g.error = _("An unexpected error has occoured.")
        return {'type': 'render', 'target': 'index.html', 'parameters': {"error": g.error}}
github pcbje / gransk / gransk / boot / ui.py View on Github external
def upload():
  """Receive and process an uploaded file."""
  _file = request.files.get('file')

  doc = document.get_document(
      secure_filename(_file.filename),
      parent=document.get_document('root'))

  doc.tag = 'upload'

  _globals['gransk'].add_file(doc, file_object=_file)

  return Response('ok')
github kframework / kweb / app / views.py View on Github external
@app.route('/_upload_file', methods=['POST'])
def upload_file():
    file = request.files['file']
    collection = request.form['collection']
    path = request.form['path']
    if '..' in path or '~' in path:
        return ''
    filename = secure_filename(file.filename)
    file.save(os.path.join(get_collection(int(collection)).get_collection_path() + path, filename))
    flash('Successfully uploaded ' + filename + ' in ' + path, category='success')
    return redirect(request.referrer)
github kylewm / redwind / redwind / admin.py View on Github external
def create_attachment(post, filename, mimetype=None, default_ext=None):
    filename = secure_filename(filename)
    basename, ext = os.path.splitext(filename)
    if not mimetype:
        mimetype, _ = mimetypes.guess_type(filename)

    # special handling for ugly filenames from OwnYourGram
    if basename.startswith('tmp_') and ext.lower() in ('.png', '.jpg'):
        basename = 'photo'

    unique_filename = ''.join(
        random.choice(string.ascii_letters + string.digits)
        for _ in range(8)) + '-' + filename
    now = datetime.datetime.now()
    storage_path = '{}/{:02d}/{:02d}/{}'.format(
        now.year, now.month, now.day, unique_filename)

    idx = 0
github tech-quantum / sia-cog / mlapi.py View on Github external
@app.route('/api/ml/upload/', methods=['GET', 'POST'])
def upload(name):
    message = "Success"
    code = 200
    try:
        datasetFolder = "./data/" + name + "/dataset/"
        if not os.path.exists(datasetFolder):
            os.makedirs(datasetFolder)
        if len(request.files) == 0:
            code = 1002
            message = "No file found"
            return jsonify({"statuscode": code, "message": message})
        
        postedfile = request.files.items(0)[0][1]
        postedfile.save(os.path.join(datasetFolder, werkzeug.secure_filename(postedfile.filename)))
    except Exception as e:
        code = 500
        message = str(e)

    return jsonify({"statuscode": code, "message": message})
github Open-Transport / synthese / tools / synthesepy / web / manager / imports.py View on Github external
def import_update(template_id, import_id):
    import_ = _get_import(template_id, import_id)

    f = request.form
    for param in import_.params.itervalues():
        if param.type == 'file':
            file = request.files[param.id]
            filename = werkzeug.secure_filename(file.filename)
            if not filename:
                continue
            relative_path = u'files/{0}'.format(filename)
            target_path = join(import_.path, 'files', filename)
            utils.maybe_makedirs(os.path.dirname(target_path))

            file.save(target_path)

            param.value = relative_path
        else:
            value = f.get(param.id)
            if value is not None:
                param.value = value

            # TODO: bool type: convert checkbox values to 0 or 1.
github Pagure / pagure / pagure / ui / repo.py View on Github external
else:
            _log.debug("Found %s instead of a tag", tag)
            flask.abort(400, description="Invalid reference provided")
    else:
        try:
            commit = repo_obj.get(ref)
        except ValueError:
            flask.abort(404, description="Invalid commit provided")

    if not isinstance(commit, pygit2.Commit):
        flask.abort(400, description="Invalid reference specified")

    tag_path = ""
    tag_filename = None
    if tag:
        tag_filename = werkzeug.secure_filename(ref)
        tag_path = os.path.join("tags", tag_filename)

    path = os.path.join(
        archive_folder,
        flask.g.repo.fullname,
        tag_path,
        commit.oid.hex,
        "%s.%s" % (name, extension),
    )
    headers = {
        str("Content-Disposition"): "attachment",
        str("Content-Type"): "application/x-gzip",
    }
    if os.path.exists(path):

        def _send_data():